1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Objective-C portions of the Parser interface.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Parse/Parser.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/PrettyDeclStackTrace.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/Scope.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
24 using namespace clang;
26 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
27 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
28 ParsedAttributes attrs(AttrFactory);
29 if (Tok.is(tok::kw___attribute)) {
30 if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
31 Diag(Tok, diag::err_objc_postfix_attribute_hint)
32 << (Kind == tok::objc_protocol);
34 Diag(Tok, diag::err_objc_postfix_attribute);
35 ParseGNUAttributes(attrs);
39 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
40 /// external-declaration: [C99 6.9]
41 /// [OBJC] objc-class-definition
42 /// [OBJC] objc-class-declaration
43 /// [OBJC] objc-alias-declaration
44 /// [OBJC] objc-protocol-definition
45 /// [OBJC] objc-method-definition
47 Parser::DeclGroupPtrTy
48 Parser::ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs) {
49 SourceLocation AtLoc = ConsumeToken(); // the "@"
51 if (Tok.is(tok::code_completion)) {
52 Actions.CodeCompleteObjCAtDirective(getCurScope());
57 Decl *SingleDecl = nullptr;
58 switch (Tok.getObjCKeywordID()) {
60 return ParseObjCAtClassDeclaration(AtLoc);
61 case tok::objc_interface:
62 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, Attrs);
64 case tok::objc_protocol:
65 return ParseObjCAtProtocolDeclaration(AtLoc, Attrs);
66 case tok::objc_implementation:
67 return ParseObjCAtImplementationDeclaration(AtLoc, Attrs);
69 return ParseObjCAtEndDeclaration(AtLoc);
70 case tok::objc_compatibility_alias:
71 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
73 case tok::objc_synthesize:
74 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
76 case tok::objc_dynamic:
77 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
79 case tok::objc_import:
80 if (getLangOpts().Modules || getLangOpts().DebuggerSupport) {
81 SingleDecl = ParseModuleImport(AtLoc);
84 Diag(AtLoc, diag::err_atimport);
86 return Actions.ConvertDeclToDeclGroup(nullptr);
88 Diag(AtLoc, diag::err_unexpected_at);
93 return Actions.ConvertDeclToDeclGroup(SingleDecl);
96 /// Class to handle popping type parameters when leaving the scope.
97 class Parser::ObjCTypeParamListScope {
100 ObjCTypeParamList *Params;
103 ObjCTypeParamListScope(Sema &Actions, Scope *S)
104 : Actions(Actions), S(S), Params(nullptr) {}
106 ~ObjCTypeParamListScope() {
110 void enter(ObjCTypeParamList *P) {
117 Actions.popObjCTypeParamList(S, Params);
123 /// objc-class-declaration:
124 /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';'
126 /// objc-class-forward-decl:
127 /// identifier objc-type-parameter-list[opt]
129 Parser::DeclGroupPtrTy
130 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
131 ConsumeToken(); // the identifier "class"
132 SmallVector<IdentifierInfo *, 8> ClassNames;
133 SmallVector<SourceLocation, 8> ClassLocs;
134 SmallVector<ObjCTypeParamList *, 8> ClassTypeParams;
137 MaybeSkipAttributes(tok::objc_class);
138 if (expectIdentifier()) {
139 SkipUntil(tok::semi);
140 return Actions.ConvertDeclToDeclGroup(nullptr);
142 ClassNames.push_back(Tok.getIdentifierInfo());
143 ClassLocs.push_back(Tok.getLocation());
146 // Parse the optional objc-type-parameter-list.
147 ObjCTypeParamList *TypeParams = nullptr;
148 if (Tok.is(tok::less))
149 TypeParams = parseObjCTypeParamList();
150 ClassTypeParams.push_back(TypeParams);
151 if (!TryConsumeToken(tok::comma))
156 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
157 return Actions.ConvertDeclToDeclGroup(nullptr);
159 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
165 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
167 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
168 if (ock == Sema::OCK_None)
171 Decl *Decl = Actions.getObjCDeclContext();
172 if (CurParsedObjCImpl) {
173 CurParsedObjCImpl->finish(AtLoc);
175 Actions.ActOnAtEnd(getCurScope(), AtLoc);
177 Diag(AtLoc, diag::err_objc_missing_end)
178 << FixItHint::CreateInsertion(AtLoc, "@end\n");
180 Diag(Decl->getBeginLoc(), diag::note_objc_container_start) << (int)ock;
185 /// objc-class-interface-attributes[opt] objc-class-interface
186 /// objc-category-interface
188 /// objc-class-interface:
189 /// '@' 'interface' identifier objc-type-parameter-list[opt]
190 /// objc-superclass[opt] objc-protocol-refs[opt]
191 /// objc-class-instance-variables[opt]
192 /// objc-interface-decl-list
195 /// objc-category-interface:
196 /// '@' 'interface' identifier objc-type-parameter-list[opt]
197 /// '(' identifier[opt] ')' objc-protocol-refs[opt]
198 /// objc-interface-decl-list
202 /// ':' identifier objc-type-arguments[opt]
204 /// objc-class-interface-attributes:
205 /// __attribute__((visibility("default")))
206 /// __attribute__((visibility("hidden")))
207 /// __attribute__((deprecated))
208 /// __attribute__((unavailable))
209 /// __attribute__((objc_exception)) - used by NSException on 64-bit
210 /// __attribute__((objc_root_class))
212 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
213 ParsedAttributes &attrs) {
214 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
215 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
216 CheckNestedObjCContexts(AtLoc);
217 ConsumeToken(); // the "interface" identifier
219 // Code completion after '@interface'.
220 if (Tok.is(tok::code_completion)) {
221 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
226 MaybeSkipAttributes(tok::objc_interface);
228 if (expectIdentifier())
229 return nullptr; // missing class or category name.
231 // We have a class or category name - consume it.
232 IdentifierInfo *nameId = Tok.getIdentifierInfo();
233 SourceLocation nameLoc = ConsumeToken();
235 // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter
236 // case, LAngleLoc will be valid and ProtocolIdents will capture the
237 // protocol references (that have not yet been resolved).
238 SourceLocation LAngleLoc, EndProtoLoc;
239 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
240 ObjCTypeParamList *typeParameterList = nullptr;
241 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
242 if (Tok.is(tok::less))
243 typeParameterList = parseObjCTypeParamListOrProtocolRefs(
244 typeParamScope, LAngleLoc, ProtocolIdents, EndProtoLoc);
246 if (Tok.is(tok::l_paren) &&
247 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
249 BalancedDelimiterTracker T(*this, tok::l_paren);
252 SourceLocation categoryLoc;
253 IdentifierInfo *categoryId = nullptr;
254 if (Tok.is(tok::code_completion)) {
255 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
260 // For ObjC2, the category name is optional (not an error).
261 if (Tok.is(tok::identifier)) {
262 categoryId = Tok.getIdentifierInfo();
263 categoryLoc = ConsumeToken();
265 else if (!getLangOpts().ObjC) {
266 Diag(Tok, diag::err_expected)
267 << tok::identifier; // missing category name.
272 if (T.getCloseLocation().isInvalid())
275 // Next, we need to check for any protocol references.
276 assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols");
277 SmallVector<Decl *, 8> ProtocolRefs;
278 SmallVector<SourceLocation, 8> ProtocolLocs;
279 if (Tok.is(tok::less) &&
280 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
281 LAngleLoc, EndProtoLoc,
282 /*consumeLastToken=*/true))
285 Decl *CategoryType = Actions.ActOnStartCategoryInterface(
286 AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc,
287 ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(),
290 if (Tok.is(tok::l_brace))
291 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
293 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
297 // Parse a class interface.
298 IdentifierInfo *superClassId = nullptr;
299 SourceLocation superClassLoc;
300 SourceLocation typeArgsLAngleLoc;
301 SmallVector<ParsedType, 4> typeArgs;
302 SourceLocation typeArgsRAngleLoc;
303 SmallVector<Decl *, 4> protocols;
304 SmallVector<SourceLocation, 4> protocolLocs;
305 if (Tok.is(tok::colon)) { // a super class is specified.
308 // Code completion of superclass names.
309 if (Tok.is(tok::code_completion)) {
310 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
315 if (expectIdentifier())
316 return nullptr; // missing super class name.
317 superClassId = Tok.getIdentifierInfo();
318 superClassLoc = ConsumeToken();
320 // Type arguments for the superclass or protocol conformances.
321 if (Tok.is(tok::less)) {
322 parseObjCTypeArgsOrProtocolQualifiers(
323 nullptr, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc,
324 protocols, protocolLocs, EndProtoLoc,
325 /*consumeLastToken=*/true,
326 /*warnOnIncompleteProtocols=*/true);
327 if (Tok.is(tok::eof))
332 // Next, we need to check for any protocol references.
333 if (LAngleLoc.isValid()) {
334 if (!ProtocolIdents.empty()) {
335 // We already parsed the protocols named when we thought we had a
336 // type parameter list. Translate them into actual protocol references.
337 for (const auto &pair : ProtocolIdents) {
338 protocolLocs.push_back(pair.second);
340 Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true,
341 /*ForObjCContainer=*/true,
342 ProtocolIdents, protocols);
344 } else if (protocols.empty() && Tok.is(tok::less) &&
345 ParseObjCProtocolReferences(protocols, protocolLocs, true, true,
346 LAngleLoc, EndProtoLoc,
347 /*consumeLastToken=*/true)) {
351 if (Tok.isNot(tok::less))
352 Actions.ActOnTypedefedProtocols(protocols, protocolLocs,
353 superClassId, superClassLoc);
355 Decl *ClsType = Actions.ActOnStartClassInterface(
356 getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId,
357 superClassLoc, typeArgs,
358 SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(),
359 protocols.size(), protocolLocs.data(), EndProtoLoc, attrs);
361 if (Tok.is(tok::l_brace))
362 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
364 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
369 /// Add an attribute for a context-sensitive type nullability to the given
371 static void addContextSensitiveTypeNullability(Parser &P,
373 NullabilityKind nullability,
374 SourceLocation nullabilityLoc,
375 bool &addedToDeclSpec) {
376 // Create the attribute.
377 auto getNullabilityAttr = [&](AttributePool &Pool) -> ParsedAttr * {
378 return Pool.create(P.getNullabilityKeyword(nullability),
379 SourceRange(nullabilityLoc), nullptr, SourceLocation(),
380 nullptr, 0, ParsedAttr::AS_ContextSensitiveKeyword);
383 if (D.getNumTypeObjects() > 0) {
384 // Add the attribute to the declarator chunk nearest the declarator.
385 D.getTypeObject(0).getAttrs().addAtEnd(
386 getNullabilityAttr(D.getAttributePool()));
387 } else if (!addedToDeclSpec) {
388 // Otherwise, just put it on the declaration specifiers (if one
389 // isn't there already).
390 D.getMutableDeclSpec().getAttributes().addAtEnd(
391 getNullabilityAttr(D.getMutableDeclSpec().getAttributes().getPool()));
392 addedToDeclSpec = true;
396 /// Parse an Objective-C type parameter list, if present, or capture
397 /// the locations of the protocol identifiers for a list of protocol
400 /// objc-type-parameter-list:
401 /// '<' objc-type-parameter (',' objc-type-parameter)* '>'
403 /// objc-type-parameter:
404 /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt]
406 /// objc-type-parameter-bound:
409 /// objc-type-parameter-variance:
411 /// '__contravariant'
413 /// \param lAngleLoc The location of the starting '<'.
415 /// \param protocolIdents Will capture the list of identifiers, if the
416 /// angle brackets contain a list of protocol references rather than a
417 /// type parameter list.
419 /// \param rAngleLoc The location of the ending '>'.
420 ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs(
421 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc,
422 SmallVectorImpl<IdentifierLocPair> &protocolIdents,
423 SourceLocation &rAngleLoc, bool mayBeProtocolList) {
424 assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list");
426 // Within the type parameter list, don't treat '>' as an operator.
427 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
429 // Local function to "flush" the protocol identifiers, turning them into
431 SmallVector<Decl *, 4> typeParams;
432 auto makeProtocolIdentsIntoTypeParameters = [&]() {
434 for (const auto &pair : protocolIdents) {
435 DeclResult typeParam = Actions.actOnObjCTypeParam(
436 getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(),
437 index++, pair.first, pair.second, SourceLocation(), nullptr);
438 if (typeParam.isUsable())
439 typeParams.push_back(typeParam.get());
442 protocolIdents.clear();
443 mayBeProtocolList = false;
446 bool invalid = false;
447 lAngleLoc = ConsumeToken();
450 // Parse the variance, if any.
451 SourceLocation varianceLoc;
452 ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant;
453 if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) {
454 variance = Tok.is(tok::kw___covariant)
455 ? ObjCTypeParamVariance::Covariant
456 : ObjCTypeParamVariance::Contravariant;
457 varianceLoc = ConsumeToken();
459 // Once we've seen a variance specific , we know this is not a
460 // list of protocol references.
461 if (mayBeProtocolList) {
462 // Up until now, we have been queuing up parameters because they
463 // might be protocol references. Turn them into parameters now.
464 makeProtocolIdentsIntoTypeParameters();
468 // Parse the identifier.
469 if (!Tok.is(tok::identifier)) {
471 if (Tok.is(tok::code_completion)) {
472 // FIXME: If these aren't protocol references, we'll need different
474 Actions.CodeCompleteObjCProtocolReferences(protocolIdents);
477 // FIXME: Better recovery here?.
481 Diag(Tok, diag::err_objc_expected_type_parameter);
486 IdentifierInfo *paramName = Tok.getIdentifierInfo();
487 SourceLocation paramLoc = ConsumeToken();
489 // If there is a bound, parse it.
490 SourceLocation colonLoc;
491 TypeResult boundType;
492 if (TryConsumeToken(tok::colon, colonLoc)) {
493 // Once we've seen a bound, we know this is not a list of protocol
495 if (mayBeProtocolList) {
496 // Up until now, we have been queuing up parameters because they
497 // might be protocol references. Turn them into parameters now.
498 makeProtocolIdentsIntoTypeParameters();
502 boundType = ParseTypeName();
503 if (boundType.isInvalid())
505 } else if (mayBeProtocolList) {
506 // If this could still be a protocol list, just capture the identifier.
507 // We don't want to turn it into a parameter.
508 protocolIdents.push_back(std::make_pair(paramName, paramLoc));
512 // Create the type parameter.
513 DeclResult typeParam = Actions.actOnObjCTypeParam(
514 getCurScope(), variance, varianceLoc, typeParams.size(), paramName,
515 paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : nullptr);
516 if (typeParam.isUsable())
517 typeParams.push_back(typeParam.get());
518 } while (TryConsumeToken(tok::comma));
522 SkipUntil(tok::greater, tok::at, StopBeforeMatch);
523 if (Tok.is(tok::greater))
525 } else if (ParseGreaterThanInTemplateList(rAngleLoc,
526 /*ConsumeLastToken=*/true,
527 /*ObjCGenericList=*/true)) {
528 Diag(lAngleLoc, diag::note_matching) << "'<'";
529 SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus,
530 tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace,
531 tok::comma, tok::semi },
533 if (Tok.is(tok::greater))
537 if (mayBeProtocolList) {
538 // A type parameter list must be followed by either a ':' (indicating the
539 // presence of a superclass) or a '(' (indicating that this is a category
540 // or extension). This disambiguates between an objc-type-parameter-list
541 // and a objc-protocol-refs.
542 if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) {
543 // Returning null indicates that we don't have a type parameter list.
544 // The results the caller needs to handle the protocol references are
545 // captured in the reference parameters already.
549 // We have a type parameter list that looks like a list of protocol
550 // references. Turn that parameter list into type parameters.
551 makeProtocolIdentsIntoTypeParameters();
554 // Form the type parameter list and enter its scope.
555 ObjCTypeParamList *list = Actions.actOnObjCTypeParamList(
562 // Clear out the angle locations; they're used by the caller to indicate
563 // whether there are any protocol references.
564 lAngleLoc = SourceLocation();
565 rAngleLoc = SourceLocation();
566 return invalid ? nullptr : list;
569 /// Parse an objc-type-parameter-list.
570 ObjCTypeParamList *Parser::parseObjCTypeParamList() {
571 SourceLocation lAngleLoc;
572 SmallVector<IdentifierLocPair, 1> protocolIdents;
573 SourceLocation rAngleLoc;
575 ObjCTypeParamListScope Scope(Actions, getCurScope());
576 return parseObjCTypeParamListOrProtocolRefs(Scope, lAngleLoc, protocolIdents,
578 /*mayBeProtocolList=*/false);
581 /// objc-interface-decl-list:
583 /// objc-interface-decl-list objc-property-decl [OBJC2]
584 /// objc-interface-decl-list objc-method-requirement [OBJC2]
585 /// objc-interface-decl-list objc-method-proto ';'
586 /// objc-interface-decl-list declaration
587 /// objc-interface-decl-list ';'
589 /// objc-method-requirement: [OBJC2]
593 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
595 SmallVector<Decl *, 32> allMethods;
596 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
597 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
602 // If this is a method prototype, parse it.
603 if (Tok.isOneOf(tok::minus, tok::plus)) {
604 if (Decl *methodPrototype =
605 ParseObjCMethodPrototype(MethodImplKind, false))
606 allMethods.push_back(methodPrototype);
607 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
608 // method definitions.
609 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
610 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
611 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
612 if (Tok.is(tok::semi))
617 if (Tok.is(tok::l_paren)) {
618 Diag(Tok, diag::err_expected_minus_or_plus);
619 ParseObjCMethodDecl(Tok.getLocation(),
621 MethodImplKind, false);
624 // Ignore excess semicolons.
625 if (Tok.is(tok::semi)) {
626 // FIXME: This should use ConsumeExtraSemi() for extraneous semicolons,
627 // to make -Wextra-semi diagnose them.
632 // If we got to the end of the file, exit the loop.
636 // Code completion within an Objective-C interface.
637 if (Tok.is(tok::code_completion)) {
638 Actions.CodeCompleteOrdinaryName(getCurScope(),
639 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
640 : Sema::PCC_ObjCInterface);
641 return cutOffParsing();
644 // If we don't have an @ directive, parse it as a function definition.
645 if (Tok.isNot(tok::at)) {
646 // The code below does not consume '}'s because it is afraid of eating the
647 // end of a namespace. Because of the way this code is structured, an
648 // erroneous r_brace would cause an infinite loop if not handled here.
649 if (Tok.is(tok::r_brace))
652 ParsedAttributesWithRange attrs(AttrFactory);
654 // Since we call ParseDeclarationOrFunctionDefinition() instead of
655 // ParseExternalDeclaration() below (so that this doesn't parse nested
656 // @interfaces), this needs to duplicate some code from the latter.
657 if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
658 SourceLocation DeclEnd;
659 allTUVariables.push_back(
660 ParseDeclaration(DeclaratorContext::FileContext, DeclEnd, attrs));
664 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
668 // Otherwise, we have an @ directive, eat the @.
669 SourceLocation AtLoc = ConsumeToken(); // the "@"
670 if (Tok.is(tok::code_completion)) {
671 Actions.CodeCompleteObjCAtDirective(getCurScope());
672 return cutOffParsing();
675 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
677 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
678 AtEnd.setBegin(AtLoc);
679 AtEnd.setEnd(Tok.getLocation());
681 } else if (DirectiveKind == tok::objc_not_keyword) {
682 Diag(Tok, diag::err_objc_unknown_at);
683 SkipUntil(tok::semi);
687 // Eat the identifier.
690 switch (DirectiveKind) {
692 // FIXME: If someone forgets an @end on a protocol, this loop will
693 // continue to eat up tons of stuff and spew lots of nonsense errors. It
694 // would probably be better to bail out if we saw an @class or @interface
695 // or something like that.
696 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
697 // Skip until we see an '@' or '}' or ';'.
698 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
701 case tok::objc_implementation:
702 case tok::objc_interface:
703 Diag(AtLoc, diag::err_objc_missing_end)
704 << FixItHint::CreateInsertion(AtLoc, "@end\n");
705 Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
706 << (int)Actions.getObjCContainerKind();
710 case tok::objc_required:
711 case tok::objc_optional:
712 // This is only valid on protocols.
713 if (contextKey != tok::objc_protocol)
714 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
716 MethodImplKind = DirectiveKind;
719 case tok::objc_property:
721 SourceLocation LParenLoc;
722 // Parse property attribute list, if any.
723 if (Tok.is(tok::l_paren)) {
724 LParenLoc = Tok.getLocation();
725 ParseObjCPropertyAttribute(OCDS);
728 bool addedToDeclSpec = false;
729 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
730 if (FD.D.getIdentifier() == nullptr) {
731 Diag(AtLoc, diag::err_objc_property_requires_field_name)
732 << FD.D.getSourceRange();
735 if (FD.BitfieldSize) {
736 Diag(AtLoc, diag::err_objc_property_bitfield)
737 << FD.D.getSourceRange();
741 // Map a nullability property attribute to a context-sensitive keyword
743 if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
744 addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(),
745 OCDS.getNullabilityLoc(),
748 // Install the property declarator into interfaceDecl.
749 IdentifierInfo *SelName =
750 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
752 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
753 IdentifierInfo *SetterName = OCDS.getSetterName();
756 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
758 SetterSel = SelectorTable::constructSetterSelector(
759 PP.getIdentifierTable(), PP.getSelectorTable(),
760 FD.D.getIdentifier());
761 Decl *Property = Actions.ActOnProperty(
762 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
765 FD.complete(Property);
768 // Parse all the comma separated declarators.
769 ParsingDeclSpec DS(*this);
770 ParseStructDeclaration(DS, ObjCPropertyCallback);
772 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
777 // We break out of the big loop in two cases: when we see @end or when we see
778 // EOF. In the former case, eat the @end. In the later case, emit an error.
779 if (Tok.is(tok::code_completion)) {
780 Actions.CodeCompleteObjCAtDirective(getCurScope());
781 return cutOffParsing();
782 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
783 ConsumeToken(); // the "end" identifier
785 Diag(Tok, diag::err_objc_missing_end)
786 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
787 Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
788 << (int)Actions.getObjCContainerKind();
789 AtEnd.setBegin(Tok.getLocation());
790 AtEnd.setEnd(Tok.getLocation());
793 // Insert collected methods declarations into the @interface object.
794 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
795 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
798 /// Diagnose redundant or conflicting nullability information.
799 static void diagnoseRedundantPropertyNullability(Parser &P,
801 NullabilityKind nullability,
802 SourceLocation nullabilityLoc){
803 if (DS.getNullability() == nullability) {
804 P.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
805 << DiagNullabilityKind(nullability, true)
806 << SourceRange(DS.getNullabilityLoc());
810 P.Diag(nullabilityLoc, diag::err_nullability_conflicting)
811 << DiagNullabilityKind(nullability, true)
812 << DiagNullabilityKind(DS.getNullability(), true)
813 << SourceRange(DS.getNullabilityLoc());
816 /// Parse property attribute declarations.
818 /// property-attr-decl: '(' property-attrlist ')'
819 /// property-attrlist:
820 /// property-attribute
821 /// property-attrlist ',' property-attribute
822 /// property-attribute:
823 /// getter '=' identifier
824 /// setter '=' identifier ':'
834 /// unsafe_unretained
841 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
842 assert(Tok.getKind() == tok::l_paren);
843 BalancedDelimiterTracker T(*this, tok::l_paren);
847 if (Tok.is(tok::code_completion)) {
848 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
849 return cutOffParsing();
851 const IdentifierInfo *II = Tok.getIdentifierInfo();
853 // If this is not an identifier at all, bail out early.
859 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
861 if (II->isStr("readonly"))
862 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
863 else if (II->isStr("assign"))
864 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
865 else if (II->isStr("unsafe_unretained"))
866 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
867 else if (II->isStr("readwrite"))
868 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
869 else if (II->isStr("retain"))
870 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
871 else if (II->isStr("strong"))
872 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
873 else if (II->isStr("copy"))
874 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
875 else if (II->isStr("nonatomic"))
876 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
877 else if (II->isStr("atomic"))
878 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
879 else if (II->isStr("weak"))
880 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
881 else if (II->isStr("getter") || II->isStr("setter")) {
882 bool IsSetter = II->getNameStart()[0] == 's';
884 // getter/setter require extra treatment.
885 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
886 diag::err_objc_expected_equal_for_getter;
888 if (ExpectAndConsume(tok::equal, DiagID)) {
889 SkipUntil(tok::r_paren, StopAtSemi);
893 if (Tok.is(tok::code_completion)) {
895 Actions.CodeCompleteObjCPropertySetter(getCurScope());
897 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
898 return cutOffParsing();
901 SourceLocation SelLoc;
902 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
905 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
907 SkipUntil(tok::r_paren, StopAtSemi);
912 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
913 DS.setSetterName(SelIdent, SelLoc);
915 if (ExpectAndConsume(tok::colon,
916 diag::err_expected_colon_after_setter_name)) {
917 SkipUntil(tok::r_paren, StopAtSemi);
921 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
922 DS.setGetterName(SelIdent, SelLoc);
924 } else if (II->isStr("nonnull")) {
925 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
926 diagnoseRedundantPropertyNullability(*this, DS,
927 NullabilityKind::NonNull,
929 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
930 DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull);
931 } else if (II->isStr("nullable")) {
932 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
933 diagnoseRedundantPropertyNullability(*this, DS,
934 NullabilityKind::Nullable,
936 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
937 DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable);
938 } else if (II->isStr("null_unspecified")) {
939 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
940 diagnoseRedundantPropertyNullability(*this, DS,
941 NullabilityKind::Unspecified,
943 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
944 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
945 } else if (II->isStr("null_resettable")) {
946 if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability)
947 diagnoseRedundantPropertyNullability(*this, DS,
948 NullabilityKind::Unspecified,
950 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability);
951 DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified);
953 // Also set the null_resettable bit.
954 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable);
955 } else if (II->isStr("class")) {
956 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_class);
958 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
959 SkipUntil(tok::r_paren, StopAtSemi);
963 if (Tok.isNot(tok::comma))
972 /// objc-method-proto:
973 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
974 /// objc-class-method objc-method-decl objc-method-attributes[opt]
976 /// objc-instance-method: '-'
977 /// objc-class-method: '+'
979 /// objc-method-attributes: [OBJC2]
980 /// __attribute__((deprecated))
982 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
983 bool MethodDefinition) {
984 assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-");
986 tok::TokenKind methodType = Tok.getKind();
987 SourceLocation mLoc = ConsumeToken();
988 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
990 // Since this rule is used for both method declarations and definitions,
991 // the caller is (optionally) responsible for consuming the ';'.
998 /// enum struct union if else while do for switch case default
999 /// break continue return goto asm sizeof typeof __alignof
1000 /// unsigned long const short volatile signed restrict _Complex
1001 /// in out inout bycopy byref oneway int char float double void _Bool
1003 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
1005 switch (Tok.getKind()) {
1009 // Empty selector piece uses the location of the ':'.
1010 SelectorLoc = Tok.getLocation();
1018 case tok::exclaimequal:
1020 case tok::pipeequal:
1022 case tok::caretequal: {
1023 std::string ThisTok(PP.getSpelling(Tok));
1024 if (isLetter(ThisTok[0])) {
1025 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok);
1026 Tok.setKind(tok::identifier);
1027 SelectorLoc = ConsumeToken();
1033 case tok::identifier:
1043 case tok::kw_const_cast:
1044 case tok::kw_continue:
1045 case tok::kw_default:
1046 case tok::kw_delete:
1048 case tok::kw_double:
1049 case tok::kw_dynamic_cast:
1052 case tok::kw_explicit:
1053 case tok::kw_export:
1054 case tok::kw_extern:
1058 case tok::kw_friend:
1061 case tok::kw_inline:
1064 case tok::kw_mutable:
1065 case tok::kw_namespace:
1067 case tok::kw_operator:
1068 case tok::kw_private:
1069 case tok::kw_protected:
1070 case tok::kw_public:
1071 case tok::kw_register:
1072 case tok::kw_reinterpret_cast:
1073 case tok::kw_restrict:
1074 case tok::kw_return:
1076 case tok::kw_signed:
1077 case tok::kw_sizeof:
1078 case tok::kw_static:
1079 case tok::kw_static_cast:
1080 case tok::kw_struct:
1081 case tok::kw_switch:
1082 case tok::kw_template:
1087 case tok::kw_typedef:
1088 case tok::kw_typeid:
1089 case tok::kw_typename:
1090 case tok::kw_typeof:
1092 case tok::kw_unsigned:
1094 case tok::kw_virtual:
1096 case tok::kw_volatile:
1097 case tok::kw_wchar_t:
1100 case tok::kw__Complex:
1101 case tok::kw___alignof:
1102 case tok::kw___auto_type:
1103 IdentifierInfo *II = Tok.getIdentifierInfo();
1104 SelectorLoc = ConsumeToken();
1109 /// objc-for-collection-in: 'in'
1111 bool Parser::isTokIdentifier_in() const {
1112 // FIXME: May have to do additional look-ahead to only allow for
1113 // valid tokens following an 'in'; such as an identifier, unary operators,
1115 return (getLangOpts().ObjC && Tok.is(tok::identifier) &&
1116 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
1119 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
1120 /// qualifier list and builds their bitmask representation in the input
1123 /// objc-type-qualifiers:
1124 /// objc-type-qualifier
1125 /// objc-type-qualifiers objc-type-qualifier
1127 /// objc-type-qualifier:
1136 /// 'null_unspecified'
1138 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
1139 DeclaratorContext Context) {
1140 assert(Context == DeclaratorContext::ObjCParameterContext ||
1141 Context == DeclaratorContext::ObjCResultContext);
1144 if (Tok.is(tok::code_completion)) {
1145 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
1146 Context == DeclaratorContext::ObjCParameterContext);
1147 return cutOffParsing();
1150 if (Tok.isNot(tok::identifier))
1153 const IdentifierInfo *II = Tok.getIdentifierInfo();
1154 for (unsigned i = 0; i != objc_NumQuals; ++i) {
1155 if (II != ObjCTypeQuals[i] ||
1156 NextToken().is(tok::less) ||
1157 NextToken().is(tok::coloncolon))
1160 ObjCDeclSpec::ObjCDeclQualifier Qual;
1161 NullabilityKind Nullability;
1163 default: llvm_unreachable("Unknown decl qualifier");
1164 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
1165 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
1166 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
1167 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
1168 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
1169 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
1172 Qual = ObjCDeclSpec::DQ_CSNullability;
1173 Nullability = NullabilityKind::NonNull;
1177 Qual = ObjCDeclSpec::DQ_CSNullability;
1178 Nullability = NullabilityKind::Nullable;
1181 case objc_null_unspecified:
1182 Qual = ObjCDeclSpec::DQ_CSNullability;
1183 Nullability = NullabilityKind::Unspecified;
1187 // FIXME: Diagnose redundant specifiers.
1188 DS.setObjCDeclQualifier(Qual);
1189 if (Qual == ObjCDeclSpec::DQ_CSNullability)
1190 DS.setNullability(Tok.getLocation(), Nullability);
1197 // If this wasn't a recognized qualifier, bail out.
1202 /// Take all the decl attributes out of the given list and add
1203 /// them to the given attribute set.
1204 static void takeDeclAttributes(ParsedAttributesView &attrs,
1205 ParsedAttributesView &from) {
1206 for (auto &AL : llvm::reverse(from)) {
1207 if (!AL.isUsedAsTypeAttr()) {
1209 attrs.addAtEnd(&AL);
1214 /// takeDeclAttributes - Take all the decl attributes from the given
1215 /// declarator and add them to the given list.
1216 static void takeDeclAttributes(ParsedAttributes &attrs,
1218 // First, take ownership of all attributes.
1219 attrs.getPool().takeAllFrom(D.getAttributePool());
1220 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
1222 // Now actually move the attributes over.
1223 takeDeclAttributes(attrs, D.getMutableDeclSpec().getAttributes());
1224 takeDeclAttributes(attrs, D.getAttributes());
1225 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
1226 takeDeclAttributes(attrs, D.getTypeObject(i).getAttrs());
1230 /// '(' objc-type-qualifiers[opt] type-name ')'
1231 /// '(' objc-type-qualifiers[opt] ')'
1233 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
1234 DeclaratorContext context,
1235 ParsedAttributes *paramAttrs) {
1236 assert(context == DeclaratorContext::ObjCParameterContext ||
1237 context == DeclaratorContext::ObjCResultContext);
1238 assert((paramAttrs != nullptr) ==
1239 (context == DeclaratorContext::ObjCParameterContext));
1241 assert(Tok.is(tok::l_paren) && "expected (");
1243 BalancedDelimiterTracker T(*this, tok::l_paren);
1246 ObjCDeclContextSwitch ObjCDC(*this);
1248 // Parse type qualifiers, in, inout, etc.
1249 ParseObjCTypeQualifierList(DS, context);
1250 SourceLocation TypeStartLoc = Tok.getLocation();
1253 if (isTypeSpecifierQualifier() || isObjCInstancetype()) {
1254 // Parse an abstract declarator.
1255 DeclSpec declSpec(AttrFactory);
1256 declSpec.setObjCQualifiers(&DS);
1257 DeclSpecContext dsContext = DeclSpecContext::DSC_normal;
1258 if (context == DeclaratorContext::ObjCResultContext)
1259 dsContext = DeclSpecContext::DSC_objc_method_result;
1260 ParseSpecifierQualifierList(declSpec, AS_none, dsContext);
1261 Declarator declarator(declSpec, context);
1262 ParseDeclarator(declarator);
1264 // If that's not invalid, extract a type.
1265 if (!declarator.isInvalidType()) {
1266 // Map a nullability specifier to a context-sensitive keyword attribute.
1267 bool addedToDeclSpec = false;
1268 if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability)
1269 addContextSensitiveTypeNullability(*this, declarator,
1270 DS.getNullability(),
1271 DS.getNullabilityLoc(),
1274 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
1275 if (!type.isInvalid())
1278 // If we're parsing a parameter, steal all the decl attributes
1279 // and add them to the decl spec.
1280 if (context == DeclaratorContext::ObjCParameterContext)
1281 takeDeclAttributes(*paramAttrs, declarator);
1285 if (Tok.is(tok::r_paren))
1287 else if (Tok.getLocation() == TypeStartLoc) {
1288 // If we didn't eat any tokens, then this isn't a type.
1289 Diag(Tok, diag::err_expected_type);
1290 SkipUntil(tok::r_paren, StopAtSemi);
1292 // Otherwise, we found *something*, but didn't get a ')' in the right
1293 // place. Emit an error then return what we have as the type.
1299 /// objc-method-decl:
1301 /// objc-keyword-selector objc-parmlist[opt]
1302 /// objc-type-name objc-selector
1303 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
1305 /// objc-keyword-selector:
1306 /// objc-keyword-decl
1307 /// objc-keyword-selector objc-keyword-decl
1309 /// objc-keyword-decl:
1310 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
1311 /// objc-selector ':' objc-keyword-attributes[opt] identifier
1312 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
1313 /// ':' objc-keyword-attributes[opt] identifier
1316 /// objc-parms objc-ellipsis[opt]
1319 /// objc-parms , parameter-declaration
1324 /// objc-keyword-attributes: [OBJC2]
1325 /// __attribute__((unused))
1327 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
1328 tok::TokenKind mType,
1329 tok::ObjCKeywordKind MethodImplKind,
1330 bool MethodDefinition) {
1331 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
1333 if (Tok.is(tok::code_completion)) {
1334 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1335 /*ReturnType=*/nullptr);
1340 // Parse the return type if present.
1341 ParsedType ReturnType;
1343 if (Tok.is(tok::l_paren))
1344 ReturnType = ParseObjCTypeName(DSRet, DeclaratorContext::ObjCResultContext,
1347 // If attributes exist before the method, parse them.
1348 ParsedAttributes methodAttrs(AttrFactory);
1349 if (getLangOpts().ObjC)
1350 MaybeParseGNUAttributes(methodAttrs);
1351 MaybeParseCXX11Attributes(methodAttrs);
1353 if (Tok.is(tok::code_completion)) {
1354 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1360 // Now parse the selector.
1361 SourceLocation selLoc;
1362 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1364 // An unnamed colon is valid.
1365 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1366 Diag(Tok, diag::err_expected_selector_for_method)
1367 << SourceRange(mLoc, Tok.getLocation());
1368 // Skip until we get a ; or @.
1369 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1373 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1374 if (Tok.isNot(tok::colon)) {
1375 // If attributes exist after the method, parse them.
1376 if (getLangOpts().ObjC)
1377 MaybeParseGNUAttributes(methodAttrs);
1378 MaybeParseCXX11Attributes(methodAttrs);
1380 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1381 Decl *Result = Actions.ActOnMethodDeclaration(
1382 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType,
1383 selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs,
1384 MethodImplKind, false, MethodDefinition);
1385 PD.complete(Result);
1389 SmallVector<IdentifierInfo *, 12> KeyIdents;
1390 SmallVector<SourceLocation, 12> KeyLocs;
1391 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1392 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1393 Scope::FunctionDeclarationScope | Scope::DeclScope);
1395 AttributePool allParamAttrs(AttrFactory);
1397 ParsedAttributes paramAttrs(AttrFactory);
1398 Sema::ObjCArgInfo ArgInfo;
1400 // Each iteration parses a single keyword argument.
1401 if (ExpectAndConsume(tok::colon))
1404 ArgInfo.Type = nullptr;
1405 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1406 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1407 DeclaratorContext::ObjCParameterContext,
1410 // If attributes exist before the argument name, parse them.
1411 // Regardless, collect all the attributes we've parsed so far.
1412 if (getLangOpts().ObjC)
1413 MaybeParseGNUAttributes(paramAttrs);
1414 MaybeParseCXX11Attributes(paramAttrs);
1415 ArgInfo.ArgAttrs = paramAttrs;
1417 // Code completion for the next piece of the selector.
1418 if (Tok.is(tok::code_completion)) {
1419 KeyIdents.push_back(SelIdent);
1420 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1421 mType == tok::minus,
1422 /*AtParameterName=*/true,
1423 ReturnType, KeyIdents);
1428 if (expectIdentifier())
1429 break; // missing argument name.
1431 ArgInfo.Name = Tok.getIdentifierInfo();
1432 ArgInfo.NameLoc = Tok.getLocation();
1433 ConsumeToken(); // Eat the identifier.
1435 ArgInfos.push_back(ArgInfo);
1436 KeyIdents.push_back(SelIdent);
1437 KeyLocs.push_back(selLoc);
1439 // Make sure the attributes persist.
1440 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1442 // Code completion for the next piece of the selector.
1443 if (Tok.is(tok::code_completion)) {
1444 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1445 mType == tok::minus,
1446 /*AtParameterName=*/false,
1447 ReturnType, KeyIdents);
1452 // Check for another keyword selector.
1453 SelIdent = ParseObjCSelectorPiece(selLoc);
1454 if (!SelIdent && Tok.isNot(tok::colon))
1457 SourceLocation ColonLoc = Tok.getLocation();
1458 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1459 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1460 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1461 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1464 // We have a selector or a colon, continue parsing.
1467 bool isVariadic = false;
1468 bool cStyleParamWarned = false;
1469 // Parse the (optional) parameter list.
1470 while (Tok.is(tok::comma)) {
1472 if (Tok.is(tok::ellipsis)) {
1477 if (!cStyleParamWarned) {
1478 Diag(Tok, diag::warn_cstyle_param);
1479 cStyleParamWarned = true;
1481 DeclSpec DS(AttrFactory);
1482 ParseDeclarationSpecifiers(DS);
1483 // Parse the declarator.
1484 Declarator ParmDecl(DS, DeclaratorContext::PrototypeContext);
1485 ParseDeclarator(ParmDecl);
1486 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1487 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1488 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1489 ParmDecl.getIdentifierLoc(),
1494 // FIXME: Add support for optional parameter list...
1495 // If attributes exist after the method, parse them.
1496 if (getLangOpts().ObjC)
1497 MaybeParseGNUAttributes(methodAttrs);
1498 MaybeParseCXX11Attributes(methodAttrs);
1500 if (KeyIdents.size() == 0)
1503 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1505 Decl *Result = Actions.ActOnMethodDeclaration(
1506 getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs,
1507 Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs,
1508 MethodImplKind, isVariadic, MethodDefinition);
1510 PD.complete(Result);
1514 /// objc-protocol-refs:
1515 /// '<' identifier-list '>'
1518 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1519 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1520 bool WarnOnDeclarations, bool ForObjCContainer,
1521 SourceLocation &LAngleLoc, SourceLocation &EndLoc,
1522 bool consumeLastToken) {
1523 assert(Tok.is(tok::less) && "expected <");
1525 LAngleLoc = ConsumeToken(); // the "<"
1527 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1530 if (Tok.is(tok::code_completion)) {
1531 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents);
1536 if (expectIdentifier()) {
1537 SkipUntil(tok::greater, StopAtSemi);
1540 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1541 Tok.getLocation()));
1542 ProtocolLocs.push_back(Tok.getLocation());
1545 if (!TryConsumeToken(tok::comma))
1550 if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken,
1551 /*ObjCGenericList=*/false))
1554 // Convert the list of protocols identifiers into a list of protocol decls.
1555 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1556 ProtocolIdents, Protocols);
1560 TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) {
1561 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1562 assert(getLangOpts().ObjC && "Protocol qualifiers only exist in Objective-C");
1564 SourceLocation lAngleLoc;
1565 SmallVector<Decl *, 8> protocols;
1566 SmallVector<SourceLocation, 8> protocolLocs;
1567 (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false,
1568 lAngleLoc, rAngleLoc,
1569 /*consumeLastToken=*/true);
1570 TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc,
1574 if (result.isUsable()) {
1575 Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id)
1576 << FixItHint::CreateInsertion(lAngleLoc, "id")
1577 << SourceRange(lAngleLoc, rAngleLoc);
1583 /// Parse Objective-C type arguments or protocol qualifiers.
1585 /// objc-type-arguments:
1586 /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>'
1588 void Parser::parseObjCTypeArgsOrProtocolQualifiers(
1589 ParsedType baseType,
1590 SourceLocation &typeArgsLAngleLoc,
1591 SmallVectorImpl<ParsedType> &typeArgs,
1592 SourceLocation &typeArgsRAngleLoc,
1593 SourceLocation &protocolLAngleLoc,
1594 SmallVectorImpl<Decl *> &protocols,
1595 SmallVectorImpl<SourceLocation> &protocolLocs,
1596 SourceLocation &protocolRAngleLoc,
1597 bool consumeLastToken,
1598 bool warnOnIncompleteProtocols) {
1599 assert(Tok.is(tok::less) && "Not at the start of type args or protocols");
1600 SourceLocation lAngleLoc = ConsumeToken();
1602 // Whether all of the elements we've parsed thus far are single
1603 // identifiers, which might be types or might be protocols.
1604 bool allSingleIdentifiers = true;
1605 SmallVector<IdentifierInfo *, 4> identifiers;
1606 SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs;
1608 // Parse a list of comma-separated identifiers, bailing out if we
1609 // see something different.
1611 // Parse a single identifier.
1612 if (Tok.is(tok::identifier) &&
1613 (NextToken().is(tok::comma) ||
1614 NextToken().is(tok::greater) ||
1615 NextToken().is(tok::greatergreater))) {
1616 identifiers.push_back(Tok.getIdentifierInfo());
1617 identifierLocs.push_back(ConsumeToken());
1621 if (Tok.is(tok::code_completion)) {
1622 // FIXME: Also include types here.
1623 SmallVector<IdentifierLocPair, 4> identifierLocPairs;
1624 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1625 identifierLocPairs.push_back(IdentifierLocPair(identifiers[i],
1626 identifierLocs[i]));
1629 QualType BaseT = Actions.GetTypeFromParser(baseType);
1630 if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) {
1631 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
1633 Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs);
1639 allSingleIdentifiers = false;
1641 } while (TryConsumeToken(tok::comma));
1643 // If we parsed an identifier list, semantic analysis sorts out
1644 // whether it refers to protocols or to type arguments.
1645 if (allSingleIdentifiers) {
1646 // Parse the closing '>'.
1647 SourceLocation rAngleLoc;
1648 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1649 /*ObjCGenericList=*/true);
1651 // Let Sema figure out what we parsed.
1652 Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(),
1664 warnOnIncompleteProtocols);
1668 // We parsed an identifier list but stumbled into non single identifiers, this
1669 // means we might (a) check that what we already parsed is a legitimate type
1670 // (not a protocol or unknown type) and (b) parse the remaining ones, which
1671 // must all be type args.
1673 // Convert the identifiers into type arguments.
1674 bool invalid = false;
1675 IdentifierInfo *foundProtocolId = nullptr, *foundValidTypeId = nullptr;
1676 SourceLocation foundProtocolSrcLoc, foundValidTypeSrcLoc;
1677 SmallVector<IdentifierInfo *, 2> unknownTypeArgs;
1678 SmallVector<SourceLocation, 2> unknownTypeArgsLoc;
1680 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1682 = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope());
1684 DeclSpec DS(AttrFactory);
1685 const char *prevSpec = nullptr;
1687 DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID,
1688 typeArg, Actions.getASTContext().getPrintingPolicy());
1690 // Form a declarator to turn this into a type.
1691 Declarator D(DS, DeclaratorContext::TypeNameContext);
1692 TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D);
1693 if (fullTypeArg.isUsable()) {
1694 typeArgs.push_back(fullTypeArg.get());
1695 if (!foundValidTypeId) {
1696 foundValidTypeId = identifiers[i];
1697 foundValidTypeSrcLoc = identifierLocs[i];
1701 unknownTypeArgs.push_back(identifiers[i]);
1702 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1706 if (!Actions.LookupProtocol(identifiers[i], identifierLocs[i])) {
1707 unknownTypeArgs.push_back(identifiers[i]);
1708 unknownTypeArgsLoc.push_back(identifierLocs[i]);
1709 } else if (!foundProtocolId) {
1710 foundProtocolId = identifiers[i];
1711 foundProtocolSrcLoc = identifierLocs[i];
1716 // Continue parsing type-names.
1718 Token CurTypeTok = Tok;
1719 TypeResult typeArg = ParseTypeName();
1721 // Consume the '...' for a pack expansion.
1722 SourceLocation ellipsisLoc;
1723 TryConsumeToken(tok::ellipsis, ellipsisLoc);
1724 if (typeArg.isUsable() && ellipsisLoc.isValid()) {
1725 typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc);
1728 if (typeArg.isUsable()) {
1729 typeArgs.push_back(typeArg.get());
1730 if (!foundValidTypeId) {
1731 foundValidTypeId = CurTypeTok.getIdentifierInfo();
1732 foundValidTypeSrcLoc = CurTypeTok.getLocation();
1737 } while (TryConsumeToken(tok::comma));
1739 // Diagnose the mix between type args and protocols.
1740 if (foundProtocolId && foundValidTypeId)
1741 Actions.DiagnoseTypeArgsAndProtocols(foundProtocolId, foundProtocolSrcLoc,
1743 foundValidTypeSrcLoc);
1745 // Diagnose unknown arg types.
1747 if (unknownTypeArgs.size())
1748 for (unsigned i = 0, e = unknownTypeArgsLoc.size(); i < e; ++i)
1749 Actions.DiagnoseUnknownTypeName(unknownTypeArgs[i], unknownTypeArgsLoc[i],
1750 getCurScope(), nullptr, T);
1752 // Parse the closing '>'.
1753 SourceLocation rAngleLoc;
1754 (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken,
1755 /*ObjCGenericList=*/true);
1762 // Record left/right angle locations.
1763 typeArgsLAngleLoc = lAngleLoc;
1764 typeArgsRAngleLoc = rAngleLoc;
1767 void Parser::parseObjCTypeArgsAndProtocolQualifiers(
1768 ParsedType baseType,
1769 SourceLocation &typeArgsLAngleLoc,
1770 SmallVectorImpl<ParsedType> &typeArgs,
1771 SourceLocation &typeArgsRAngleLoc,
1772 SourceLocation &protocolLAngleLoc,
1773 SmallVectorImpl<Decl *> &protocols,
1774 SmallVectorImpl<SourceLocation> &protocolLocs,
1775 SourceLocation &protocolRAngleLoc,
1776 bool consumeLastToken) {
1777 assert(Tok.is(tok::less));
1779 // Parse the first angle-bracket-delimited clause.
1780 parseObjCTypeArgsOrProtocolQualifiers(baseType,
1789 /*warnOnIncompleteProtocols=*/false);
1790 if (Tok.is(tok::eof)) // Nothing else to do here...
1793 // An Objective-C object pointer followed by type arguments
1794 // can then be followed again by a set of protocol references, e.g.,
1795 // \c NSArray<NSView><NSTextDelegate>
1796 if ((consumeLastToken && Tok.is(tok::less)) ||
1797 (!consumeLastToken && NextToken().is(tok::less))) {
1798 // If we aren't consuming the last token, the prior '>' is still hanging
1799 // there. Consume it before we parse the protocol qualifiers.
1800 if (!consumeLastToken)
1803 if (!protocols.empty()) {
1804 SkipUntilFlags skipFlags = SkipUntilFlags();
1805 if (!consumeLastToken)
1806 skipFlags = skipFlags | StopBeforeMatch;
1807 Diag(Tok, diag::err_objc_type_args_after_protocols)
1808 << SourceRange(protocolLAngleLoc, protocolRAngleLoc);
1809 SkipUntil(tok::greater, tok::greatergreater, skipFlags);
1811 ParseObjCProtocolReferences(protocols, protocolLocs,
1812 /*WarnOnDeclarations=*/false,
1813 /*ForObjCContainer=*/false,
1814 protocolLAngleLoc, protocolRAngleLoc,
1820 TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers(
1823 bool consumeLastToken,
1824 SourceLocation &endLoc) {
1825 assert(Tok.is(tok::less));
1826 SourceLocation typeArgsLAngleLoc;
1827 SmallVector<ParsedType, 4> typeArgs;
1828 SourceLocation typeArgsRAngleLoc;
1829 SourceLocation protocolLAngleLoc;
1830 SmallVector<Decl *, 4> protocols;
1831 SmallVector<SourceLocation, 4> protocolLocs;
1832 SourceLocation protocolRAngleLoc;
1834 // Parse type arguments and protocol qualifiers.
1835 parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs,
1836 typeArgsRAngleLoc, protocolLAngleLoc,
1837 protocols, protocolLocs,
1838 protocolRAngleLoc, consumeLastToken);
1840 if (Tok.is(tok::eof))
1841 return true; // Invalid type result.
1843 // Compute the location of the last token.
1844 if (consumeLastToken)
1845 endLoc = PrevTokLocation;
1847 endLoc = Tok.getLocation();
1849 return Actions.actOnObjCTypeArgsAndProtocolQualifiers(
1862 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1863 BalancedDelimiterTracker &T,
1864 SmallVectorImpl<Decl *> &AllIvarDecls,
1865 bool RBraceMissing) {
1869 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1870 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1871 Actions.ActOnObjCContainerFinishDefinition();
1872 // Call ActOnFields() even if we don't have any decls. This is useful
1873 // for code rewriting tools that need to be aware of the empty list.
1874 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls,
1875 T.getOpenLocation(), T.getCloseLocation(),
1876 ParsedAttributesView());
1879 /// objc-class-instance-variables:
1880 /// '{' objc-instance-variable-decl-list[opt] '}'
1882 /// objc-instance-variable-decl-list:
1883 /// objc-visibility-spec
1884 /// objc-instance-variable-decl ';'
1886 /// objc-instance-variable-decl-list objc-visibility-spec
1887 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1888 /// objc-instance-variable-decl-list static_assert-declaration
1889 /// objc-instance-variable-decl-list ';'
1891 /// objc-visibility-spec:
1895 /// @package [OBJC2]
1897 /// objc-instance-variable-decl:
1898 /// struct-declaration
1900 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1901 tok::ObjCKeywordKind visibility,
1902 SourceLocation atLoc) {
1903 assert(Tok.is(tok::l_brace) && "expected {");
1904 SmallVector<Decl *, 32> AllIvarDecls;
1906 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1907 ObjCDeclContextSwitch ObjCDC(*this);
1909 BalancedDelimiterTracker T(*this, tok::l_brace);
1911 // While we still have something to read, read the instance variables.
1912 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1913 // Each iteration of this loop reads one objc-instance-variable-decl.
1915 // Check for extraneous top-level semicolon.
1916 if (Tok.is(tok::semi)) {
1917 ConsumeExtraSemi(InstanceVariableList);
1921 // Set the default visibility to private.
1922 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1923 if (Tok.is(tok::code_completion)) {
1924 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1925 return cutOffParsing();
1928 switch (Tok.getObjCKeywordID()) {
1929 case tok::objc_private:
1930 case tok::objc_public:
1931 case tok::objc_protected:
1932 case tok::objc_package:
1933 visibility = Tok.getObjCKeywordID();
1938 Diag(Tok, diag::err_objc_unexpected_atend);
1939 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1940 Tok.setKind(tok::at);
1942 PP.EnterToken(Tok, /*IsReinject*/true);
1943 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1944 T, AllIvarDecls, true);
1948 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1953 if (Tok.is(tok::code_completion)) {
1954 Actions.CodeCompleteOrdinaryName(getCurScope(),
1955 Sema::PCC_ObjCInstanceVariableList);
1956 return cutOffParsing();
1959 // This needs to duplicate a small amount of code from
1960 // ParseStructUnionBody() for things that should work in both
1961 // C struct and in Objective-C class instance variables.
1962 if (Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
1963 SourceLocation DeclEnd;
1964 ParseStaticAssertDeclaration(DeclEnd);
1968 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1969 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1970 // Install the declarator into the interface decl.
1971 FD.D.setObjCIvar(true);
1972 Decl *Field = Actions.ActOnIvar(
1973 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1974 FD.BitfieldSize, visibility);
1975 Actions.ActOnObjCContainerFinishDefinition();
1977 AllIvarDecls.push_back(Field);
1981 // Parse all the comma separated declarators.
1982 ParsingDeclSpec DS(*this);
1983 ParseStructDeclaration(DS, ObjCIvarCallback);
1985 if (Tok.is(tok::semi)) {
1988 Diag(Tok, diag::err_expected_semi_decl_list);
1989 // Skip to end of block or statement
1990 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1993 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1994 T, AllIvarDecls, false);
1997 /// objc-protocol-declaration:
1998 /// objc-protocol-definition
1999 /// objc-protocol-forward-reference
2001 /// objc-protocol-definition:
2002 /// \@protocol identifier
2003 /// objc-protocol-refs[opt]
2004 /// objc-interface-decl-list
2007 /// objc-protocol-forward-reference:
2008 /// \@protocol identifier-list ';'
2010 /// "\@protocol identifier ;" should be resolved as "\@protocol
2011 /// identifier-list ;": objc-interface-decl-list may not start with a
2012 /// semicolon in the first alternative if objc-protocol-refs are omitted.
2013 Parser::DeclGroupPtrTy
2014 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
2015 ParsedAttributes &attrs) {
2016 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
2017 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
2018 ConsumeToken(); // the "protocol" identifier
2020 if (Tok.is(tok::code_completion)) {
2021 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
2026 MaybeSkipAttributes(tok::objc_protocol);
2028 if (expectIdentifier())
2029 return nullptr; // missing protocol name.
2030 // Save the protocol name, then consume it.
2031 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
2032 SourceLocation nameLoc = ConsumeToken();
2034 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
2035 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
2036 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtoInfo, attrs);
2039 CheckNestedObjCContexts(AtLoc);
2041 if (Tok.is(tok::comma)) { // list of forward declarations.
2042 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
2043 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
2045 // Parse the list of forward declarations.
2047 ConsumeToken(); // the ','
2048 if (expectIdentifier()) {
2049 SkipUntil(tok::semi);
2052 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
2053 Tok.getLocation()));
2054 ConsumeToken(); // the identifier
2056 if (Tok.isNot(tok::comma))
2060 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
2063 return Actions.ActOnForwardProtocolDeclaration(AtLoc, ProtocolRefs, attrs);
2066 // Last, and definitely not least, parse a protocol declaration.
2067 SourceLocation LAngleLoc, EndProtoLoc;
2069 SmallVector<Decl *, 8> ProtocolRefs;
2070 SmallVector<SourceLocation, 8> ProtocolLocs;
2071 if (Tok.is(tok::less) &&
2072 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
2073 LAngleLoc, EndProtoLoc,
2074 /*consumeLastToken=*/true))
2077 Decl *ProtoType = Actions.ActOnStartProtocolInterface(
2078 AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(),
2079 ProtocolLocs.data(), EndProtoLoc, attrs);
2081 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
2082 return Actions.ConvertDeclToDeclGroup(ProtoType);
2085 /// objc-implementation:
2086 /// objc-class-implementation-prologue
2087 /// objc-category-implementation-prologue
2089 /// objc-class-implementation-prologue:
2090 /// @implementation identifier objc-superclass[opt]
2091 /// objc-class-instance-variables[opt]
2093 /// objc-category-implementation-prologue:
2094 /// @implementation identifier ( identifier )
2095 Parser::DeclGroupPtrTy
2096 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc,
2097 ParsedAttributes &Attrs) {
2098 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
2099 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
2100 CheckNestedObjCContexts(AtLoc);
2101 ConsumeToken(); // the "implementation" identifier
2103 // Code completion after '@implementation'.
2104 if (Tok.is(tok::code_completion)) {
2105 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
2110 MaybeSkipAttributes(tok::objc_implementation);
2112 if (expectIdentifier())
2113 return nullptr; // missing class or category name.
2114 // We have a class or category name - consume it.
2115 IdentifierInfo *nameId = Tok.getIdentifierInfo();
2116 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
2117 Decl *ObjCImpDecl = nullptr;
2119 // Neither a type parameter list nor a list of protocol references is
2120 // permitted here. Parse and diagnose them.
2121 if (Tok.is(tok::less)) {
2122 SourceLocation lAngleLoc, rAngleLoc;
2123 SmallVector<IdentifierLocPair, 8> protocolIdents;
2124 SourceLocation diagLoc = Tok.getLocation();
2125 ObjCTypeParamListScope typeParamScope(Actions, getCurScope());
2126 if (parseObjCTypeParamListOrProtocolRefs(typeParamScope, lAngleLoc,
2127 protocolIdents, rAngleLoc)) {
2128 Diag(diagLoc, diag::err_objc_parameterized_implementation)
2129 << SourceRange(diagLoc, PrevTokLocation);
2130 } else if (lAngleLoc.isValid()) {
2131 Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier)
2132 << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc));
2136 if (Tok.is(tok::l_paren)) {
2137 // we have a category implementation.
2139 SourceLocation categoryLoc, rparenLoc;
2140 IdentifierInfo *categoryId = nullptr;
2142 if (Tok.is(tok::code_completion)) {
2143 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
2148 if (Tok.is(tok::identifier)) {
2149 categoryId = Tok.getIdentifierInfo();
2150 categoryLoc = ConsumeToken();
2152 Diag(Tok, diag::err_expected)
2153 << tok::identifier; // missing category name.
2156 if (Tok.isNot(tok::r_paren)) {
2157 Diag(Tok, diag::err_expected) << tok::r_paren;
2158 SkipUntil(tok::r_paren); // don't stop at ';'
2161 rparenLoc = ConsumeParen();
2162 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2163 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2164 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2165 SmallVector<Decl *, 4> protocols;
2166 SmallVector<SourceLocation, 4> protocolLocs;
2167 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2168 /*warnOnIncompleteProtocols=*/false,
2169 /*ForObjCContainer=*/false,
2170 protocolLAngleLoc, protocolRAngleLoc,
2171 /*consumeLastToken=*/true);
2173 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
2174 AtLoc, nameId, nameLoc, categoryId, categoryLoc, Attrs);
2177 // We have a class implementation
2178 SourceLocation superClassLoc;
2179 IdentifierInfo *superClassId = nullptr;
2180 if (TryConsumeToken(tok::colon)) {
2181 // We have a super class
2182 if (expectIdentifier())
2183 return nullptr; // missing super class name.
2184 superClassId = Tok.getIdentifierInfo();
2185 superClassLoc = ConsumeToken(); // Consume super class name
2187 ObjCImpDecl = Actions.ActOnStartClassImplementation(
2188 AtLoc, nameId, nameLoc, superClassId, superClassLoc, Attrs);
2190 if (Tok.is(tok::l_brace)) // we have ivars
2191 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
2192 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
2193 Diag(Tok, diag::err_unexpected_protocol_qualifier);
2195 SourceLocation protocolLAngleLoc, protocolRAngleLoc;
2196 SmallVector<Decl *, 4> protocols;
2197 SmallVector<SourceLocation, 4> protocolLocs;
2198 (void)ParseObjCProtocolReferences(protocols, protocolLocs,
2199 /*warnOnIncompleteProtocols=*/false,
2200 /*ForObjCContainer=*/false,
2201 protocolLAngleLoc, protocolRAngleLoc,
2202 /*consumeLastToken=*/true);
2205 assert(ObjCImpDecl);
2207 SmallVector<Decl *, 8> DeclsInGroup;
2210 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
2211 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
2212 ParsedAttributesWithRange attrs(AttrFactory);
2213 MaybeParseCXX11Attributes(attrs);
2214 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
2215 DeclGroupRef DG = DGP.get();
2216 DeclsInGroup.append(DG.begin(), DG.end());
2221 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
2224 Parser::DeclGroupPtrTy
2225 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
2226 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
2227 "ParseObjCAtEndDeclaration(): Expected @end");
2228 ConsumeToken(); // the "end" identifier
2229 if (CurParsedObjCImpl)
2230 CurParsedObjCImpl->finish(atEnd);
2232 // missing @implementation
2233 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
2237 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
2239 finish(P.Tok.getLocation());
2240 if (P.isEofOrEom()) {
2241 P.Diag(P.Tok, diag::err_objc_missing_end)
2242 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
2243 P.Diag(Dcl->getBeginLoc(), diag::note_objc_container_start)
2244 << Sema::OCK_Implementation;
2247 P.CurParsedObjCImpl = nullptr;
2248 assert(LateParsedObjCMethods.empty());
2251 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
2253 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl, AtEnd.getBegin());
2254 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2255 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2258 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
2261 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
2262 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
2263 false/*c-functions*/);
2265 /// Clear and free the cached objc methods.
2266 for (LateParsedObjCMethodContainer::iterator
2267 I = LateParsedObjCMethods.begin(),
2268 E = LateParsedObjCMethods.end(); I != E; ++I)
2270 LateParsedObjCMethods.clear();
2275 /// compatibility-alias-decl:
2276 /// @compatibility_alias alias-name class-name ';'
2278 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
2279 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
2280 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
2281 ConsumeToken(); // consume compatibility_alias
2282 if (expectIdentifier())
2284 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
2285 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
2286 if (expectIdentifier())
2288 IdentifierInfo *classId = Tok.getIdentifierInfo();
2289 SourceLocation classLoc = ConsumeToken(); // consume class-name;
2290 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
2291 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
2295 /// property-synthesis:
2296 /// @synthesize property-ivar-list ';'
2298 /// property-ivar-list:
2300 /// property-ivar-list ',' property-ivar
2304 /// identifier '=' identifier
2306 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
2307 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
2308 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
2309 ConsumeToken(); // consume synthesize
2312 if (Tok.is(tok::code_completion)) {
2313 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2318 if (Tok.isNot(tok::identifier)) {
2319 Diag(Tok, diag::err_synthesized_property_name);
2320 SkipUntil(tok::semi);
2324 IdentifierInfo *propertyIvar = nullptr;
2325 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2326 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2327 SourceLocation propertyIvarLoc;
2328 if (TryConsumeToken(tok::equal)) {
2329 // property '=' ivar-name
2330 if (Tok.is(tok::code_completion)) {
2331 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
2336 if (expectIdentifier())
2338 propertyIvar = Tok.getIdentifierInfo();
2339 propertyIvarLoc = ConsumeToken(); // consume ivar-name
2341 Actions.ActOnPropertyImplDecl(
2342 getCurScope(), atLoc, propertyLoc, true,
2343 propertyId, propertyIvar, propertyIvarLoc,
2344 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2345 if (Tok.isNot(tok::comma))
2347 ConsumeToken(); // consume ','
2349 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
2353 /// property-dynamic:
2354 /// @dynamic property-list
2358 /// property-list ',' identifier
2360 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
2361 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
2362 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
2363 ConsumeToken(); // consume dynamic
2365 bool isClassProperty = false;
2366 if (Tok.is(tok::l_paren)) {
2368 const IdentifierInfo *II = Tok.getIdentifierInfo();
2371 Diag(Tok, diag::err_objc_expected_property_attr) << II;
2372 SkipUntil(tok::r_paren, StopAtSemi);
2374 SourceLocation AttrName = ConsumeToken(); // consume attribute name
2375 if (II->isStr("class")) {
2376 isClassProperty = true;
2377 if (Tok.isNot(tok::r_paren)) {
2378 Diag(Tok, diag::err_expected) << tok::r_paren;
2379 SkipUntil(tok::r_paren, StopAtSemi);
2383 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
2384 SkipUntil(tok::r_paren, StopAtSemi);
2390 if (Tok.is(tok::code_completion)) {
2391 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
2396 if (expectIdentifier()) {
2397 SkipUntil(tok::semi);
2401 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
2402 SourceLocation propertyLoc = ConsumeToken(); // consume property name
2403 Actions.ActOnPropertyImplDecl(
2404 getCurScope(), atLoc, propertyLoc, false,
2405 propertyId, nullptr, SourceLocation(),
2406 isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
2407 ObjCPropertyQueryKind::OBJC_PR_query_unknown);
2409 if (Tok.isNot(tok::comma))
2411 ConsumeToken(); // consume ','
2413 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
2417 /// objc-throw-statement:
2418 /// throw expression[opt];
2420 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
2422 ConsumeToken(); // consume throw
2423 if (Tok.isNot(tok::semi)) {
2424 Res = ParseExpression();
2425 if (Res.isInvalid()) {
2426 SkipUntil(tok::semi);
2431 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
2432 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
2435 /// objc-synchronized-statement:
2436 /// @synchronized '(' expression ')' compound-statement
2439 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
2440 ConsumeToken(); // consume synchronized
2441 if (Tok.isNot(tok::l_paren)) {
2442 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
2446 // The operand is surrounded with parentheses.
2447 ConsumeParen(); // '('
2448 ExprResult operand(ParseExpression());
2450 if (Tok.is(tok::r_paren)) {
2451 ConsumeParen(); // ')'
2453 if (!operand.isInvalid())
2454 Diag(Tok, diag::err_expected) << tok::r_paren;
2456 // Skip forward until we see a left brace, but don't consume it.
2457 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2460 // Require a compound statement.
2461 if (Tok.isNot(tok::l_brace)) {
2462 if (!operand.isInvalid())
2463 Diag(Tok, diag::err_expected) << tok::l_brace;
2467 // Check the @synchronized operand now.
2468 if (!operand.isInvalid())
2469 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
2471 // Parse the compound statement within a new scope.
2472 ParseScope bodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2473 StmtResult body(ParseCompoundStatementBody());
2476 // If there was a semantic or parse error earlier with the
2477 // operand, fail now.
2478 if (operand.isInvalid())
2481 if (body.isInvalid())
2482 body = Actions.ActOnNullStmt(Tok.getLocation());
2484 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
2487 /// objc-try-catch-statement:
2488 /// @try compound-statement objc-catch-list[opt]
2489 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
2491 /// objc-catch-list:
2492 /// @catch ( parameter-declaration ) compound-statement
2493 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
2494 /// catch-parameter-declaration:
2495 /// parameter-declaration
2498 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
2499 bool catch_or_finally_seen = false;
2501 ConsumeToken(); // consume try
2502 if (Tok.isNot(tok::l_brace)) {
2503 Diag(Tok, diag::err_expected) << tok::l_brace;
2506 StmtVector CatchStmts;
2507 StmtResult FinallyStmt;
2508 ParseScope TryScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2509 StmtResult TryBody(ParseCompoundStatementBody());
2511 if (TryBody.isInvalid())
2512 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
2514 while (Tok.is(tok::at)) {
2515 // At this point, we need to lookahead to determine if this @ is the start
2516 // of an @catch or @finally. We don't want to consume the @ token if this
2517 // is an @try or @encode or something else.
2518 Token AfterAt = GetLookAheadToken(1);
2519 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
2520 !AfterAt.isObjCAtKeyword(tok::objc_finally))
2523 SourceLocation AtCatchFinallyLoc = ConsumeToken();
2524 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
2525 Decl *FirstPart = nullptr;
2526 ConsumeToken(); // consume catch
2527 if (Tok.is(tok::l_paren)) {
2529 ParseScope CatchScope(this, Scope::DeclScope |
2530 Scope::CompoundStmtScope |
2531 Scope::AtCatchScope);
2532 if (Tok.isNot(tok::ellipsis)) {
2533 DeclSpec DS(AttrFactory);
2534 ParseDeclarationSpecifiers(DS);
2535 Declarator ParmDecl(DS, DeclaratorContext::ObjCCatchContext);
2536 ParseDeclarator(ParmDecl);
2538 // Inform the actions module about the declarator, so it
2539 // gets added to the current scope.
2540 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
2542 ConsumeToken(); // consume '...'
2544 SourceLocation RParenLoc;
2546 if (Tok.is(tok::r_paren))
2547 RParenLoc = ConsumeParen();
2548 else // Skip over garbage, until we get to ')'. Eat the ')'.
2549 SkipUntil(tok::r_paren, StopAtSemi);
2551 StmtResult CatchBody(true);
2552 if (Tok.is(tok::l_brace))
2553 CatchBody = ParseCompoundStatementBody();
2555 Diag(Tok, diag::err_expected) << tok::l_brace;
2556 if (CatchBody.isInvalid())
2557 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
2559 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
2563 if (!Catch.isInvalid())
2564 CatchStmts.push_back(Catch.get());
2567 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
2571 catch_or_finally_seen = true;
2573 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
2574 ConsumeToken(); // consume finally
2575 ParseScope FinallyScope(this,
2576 Scope::DeclScope | Scope::CompoundStmtScope);
2578 bool ShouldCapture =
2579 getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2581 Actions.ActOnCapturedRegionStart(Tok.getLocation(), getCurScope(),
2582 CR_ObjCAtFinally, 1);
2584 StmtResult FinallyBody(true);
2585 if (Tok.is(tok::l_brace))
2586 FinallyBody = ParseCompoundStatementBody();
2588 Diag(Tok, diag::err_expected) << tok::l_brace;
2590 if (FinallyBody.isInvalid()) {
2591 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
2593 Actions.ActOnCapturedRegionError();
2594 } else if (ShouldCapture) {
2595 FinallyBody = Actions.ActOnCapturedRegionEnd(FinallyBody.get());
2598 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
2600 catch_or_finally_seen = true;
2604 if (!catch_or_finally_seen) {
2605 Diag(atLoc, diag::err_missing_catch_finally);
2609 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
2614 /// objc-autoreleasepool-statement:
2615 /// @autoreleasepool compound-statement
2618 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
2619 ConsumeToken(); // consume autoreleasepool
2620 if (Tok.isNot(tok::l_brace)) {
2621 Diag(Tok, diag::err_expected) << tok::l_brace;
2624 // Enter a scope to hold everything within the compound stmt. Compound
2625 // statements can always hold declarations.
2626 ParseScope BodyScope(this, Scope::DeclScope | Scope::CompoundStmtScope);
2628 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
2631 if (AutoreleasePoolBody.isInvalid())
2632 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
2633 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
2634 AutoreleasePoolBody.get());
2637 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
2638 /// for later parsing.
2639 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
2640 if (SkipFunctionBodies && (!MDecl || Actions.canSkipFunctionBody(MDecl)) &&
2641 trySkippingFunctionBody()) {
2642 Actions.ActOnSkippedFunctionBody(MDecl);
2646 LexedMethod* LM = new LexedMethod(this, MDecl);
2647 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
2648 CachedTokens &Toks = LM->Toks;
2649 // Begin by storing the '{' or 'try' or ':' token.
2650 Toks.push_back(Tok);
2651 if (Tok.is(tok::kw_try)) {
2653 if (Tok.is(tok::colon)) {
2654 Toks.push_back(Tok);
2656 while (Tok.isNot(tok::l_brace)) {
2657 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2658 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2661 Toks.push_back(Tok); // also store '{'
2663 else if (Tok.is(tok::colon)) {
2665 // FIXME: This is wrong, due to C++11 braced initialization.
2666 while (Tok.isNot(tok::l_brace)) {
2667 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2668 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2670 Toks.push_back(Tok); // also store '{'
2673 // Consume everything up to (and including) the matching right brace.
2674 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2675 while (Tok.is(tok::kw_catch)) {
2676 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2677 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2681 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2683 Decl *Parser::ParseObjCMethodDefinition() {
2684 Decl *MDecl = ParseObjCMethodPrototype();
2686 PrettyDeclStackTraceEntry CrashInfo(Actions.Context, MDecl, Tok.getLocation(),
2687 "parsing Objective-C method");
2689 // parse optional ';'
2690 if (Tok.is(tok::semi)) {
2691 if (CurParsedObjCImpl) {
2692 Diag(Tok, diag::warn_semicolon_before_method_body)
2693 << FixItHint::CreateRemoval(Tok.getLocation());
2698 // We should have an opening brace now.
2699 if (Tok.isNot(tok::l_brace)) {
2700 Diag(Tok, diag::err_expected_method_body);
2702 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2703 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2705 // If we didn't find the '{', bail out.
2706 if (Tok.isNot(tok::l_brace))
2712 SkipUntil(tok::r_brace);
2716 // Allow the rest of sema to find private method decl implementations.
2717 Actions.AddAnyMethodToGlobalPool(MDecl);
2718 assert (CurParsedObjCImpl
2719 && "ParseObjCMethodDefinition - Method out of @implementation");
2720 // Consume the tokens and store them for later parsing.
2721 StashAwayMethodOrFunctionBodyTokens(MDecl);
2725 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc,
2726 ParsedStmtContext StmtCtx) {
2727 if (Tok.is(tok::code_completion)) {
2728 Actions.CodeCompleteObjCAtStatement(getCurScope());
2733 if (Tok.isObjCAtKeyword(tok::objc_try))
2734 return ParseObjCTryStmt(AtLoc);
2736 if (Tok.isObjCAtKeyword(tok::objc_throw))
2737 return ParseObjCThrowStmt(AtLoc);
2739 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2740 return ParseObjCSynchronizedStmt(AtLoc);
2742 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2743 return ParseObjCAutoreleasePoolStmt(AtLoc);
2745 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2746 getLangOpts().DebuggerSupport) {
2747 SkipUntil(tok::semi);
2748 return Actions.ActOnNullStmt(Tok.getLocation());
2751 ExprStatementTokLoc = AtLoc;
2752 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2753 if (Res.isInvalid()) {
2754 // If the expression is invalid, skip ahead to the next semicolon. Not
2755 // doing this opens us up to the possibility of infinite loops if
2756 // ParseExpression does not consume any tokens.
2757 SkipUntil(tok::semi);
2761 // Otherwise, eat the semicolon.
2762 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2763 return handleExprStmt(Res, StmtCtx);
2766 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2767 switch (Tok.getKind()) {
2768 case tok::code_completion:
2769 Actions.CodeCompleteObjCAtExpression(getCurScope());
2775 tok::TokenKind Kind = Tok.getKind();
2776 SourceLocation OpLoc = ConsumeToken();
2778 if (!Tok.is(tok::numeric_constant)) {
2779 const char *Symbol = nullptr;
2781 case tok::minus: Symbol = "-"; break;
2782 case tok::plus: Symbol = "+"; break;
2783 default: llvm_unreachable("missing unary operator case");
2785 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2790 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2791 if (Lit.isInvalid()) {
2794 ConsumeToken(); // Consume the literal token.
2796 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2797 if (Lit.isInvalid())
2800 return ParsePostfixExpressionSuffix(
2801 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2804 case tok::string_literal: // primary-expression: string-literal
2805 case tok::wide_string_literal:
2806 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2808 case tok::char_constant:
2809 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2811 case tok::numeric_constant:
2812 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2814 case tok::kw_true: // Objective-C++, etc.
2815 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2816 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2817 case tok::kw_false: // Objective-C++, etc.
2818 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2819 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2822 // Objective-C array literal
2823 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2826 // Objective-C dictionary literal
2827 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2830 // Objective-C boxed expression
2831 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2834 if (Tok.getIdentifierInfo() == nullptr)
2835 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2837 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2838 case tok::objc_encode:
2839 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2840 case tok::objc_protocol:
2841 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2842 case tok::objc_selector:
2843 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2844 case tok::objc_available:
2845 return ParseAvailabilityCheckExpr(AtLoc);
2847 const char *str = nullptr;
2848 // Only provide the @try/@finally/@autoreleasepool fixit when we're sure
2849 // that this is a proper statement where such directives could actually
2851 if (GetLookAheadToken(1).is(tok::l_brace) &&
2852 ExprStatementTokLoc == AtLoc) {
2853 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2856 : (ch == 'f' ? "finally"
2857 : (ch == 'a' ? "autoreleasepool" : nullptr));
2860 SourceLocation kwLoc = Tok.getLocation();
2861 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2862 FixItHint::CreateReplacement(kwLoc, str));
2865 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2871 /// Parse the receiver of an Objective-C++ message send.
2873 /// This routine parses the receiver of a message send in
2874 /// Objective-C++ either as a type or as an expression. Note that this
2875 /// routine must not be called to parse a send to 'super', since it
2876 /// has no way to return such a result.
2878 /// \param IsExpr Whether the receiver was parsed as an expression.
2880 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2881 /// IsExpr is true), the parsed expression. If the receiver was parsed
2882 /// as a type (\c IsExpr is false), the parsed type.
2884 /// \returns True if an error occurred during parsing or semantic
2885 /// analysis, in which case the arguments do not have valid
2886 /// values. Otherwise, returns false for a successful parse.
2888 /// objc-receiver: [C++]
2889 /// 'super' [not parsed here]
2891 /// simple-type-specifier
2892 /// typename-specifier
2893 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2894 InMessageExpressionRAIIObject InMessage(*this, true);
2896 if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename,
2897 tok::annot_cxxscope))
2898 TryAnnotateTypeOrScopeToken();
2900 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2903 // Make sure any typos in the receiver are corrected or diagnosed, so that
2904 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2905 // only the things that are valid ObjC receivers?
2906 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2907 if (Receiver.isInvalid())
2911 TypeOrExpr = Receiver.get();
2916 // typename-specifier
2917 // simple-type-specifier
2918 // expression (that starts with one of the above)
2919 DeclSpec DS(AttrFactory);
2920 ParseCXXSimpleTypeSpecifier(DS);
2922 if (Tok.is(tok::l_paren)) {
2923 // If we see an opening parentheses at this point, we are
2924 // actually parsing an expression that starts with a
2925 // function-style cast, e.g.,
2927 // postfix-expression:
2928 // simple-type-specifier ( expression-list [opt] )
2929 // typename-specifier ( expression-list [opt] )
2931 // Parse the remainder of this case, then the (optional)
2932 // postfix-expression suffix, followed by the (optional)
2933 // right-hand side of the binary expression. We have an
2935 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2936 if (!Receiver.isInvalid())
2937 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2938 if (!Receiver.isInvalid())
2939 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2940 if (Receiver.isInvalid())
2944 TypeOrExpr = Receiver.get();
2948 // We have a class message. Turn the simple-type-specifier or
2949 // typename-specifier we parsed into a type and parse the
2950 // remainder of the class message.
2951 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
2952 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2953 if (Type.isInvalid())
2957 TypeOrExpr = Type.get().getAsOpaquePtr();
2961 /// Determine whether the parser is currently referring to a an
2962 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2964 /// This routine will only return true for a subset of valid message-send
2966 bool Parser::isSimpleObjCMessageExpression() {
2967 assert(Tok.is(tok::l_square) && getLangOpts().ObjC &&
2968 "Incorrect start for isSimpleObjCMessageExpression");
2969 return GetLookAheadToken(1).is(tok::identifier) &&
2970 GetLookAheadToken(2).is(tok::identifier);
2973 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2974 if (!getLangOpts().ObjC || !NextToken().is(tok::identifier) ||
2975 InMessageExpression)
2980 if (Tok.is(tok::annot_typename))
2981 Type = getTypeAnnotation(Tok);
2982 else if (Tok.is(tok::identifier))
2983 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2988 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2989 const Token &AfterNext = GetLookAheadToken(2);
2990 if (AfterNext.isOneOf(tok::colon, tok::r_square)) {
2991 if (Tok.is(tok::identifier))
2992 TryAnnotateTypeOrScopeToken();
2994 return Tok.is(tok::annot_typename);
3001 /// objc-message-expr:
3002 /// '[' objc-receiver objc-message-args ']'
3004 /// objc-receiver: [C]
3010 ExprResult Parser::ParseObjCMessageExpression() {
3011 assert(Tok.is(tok::l_square) && "'[' expected");
3012 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
3014 if (Tok.is(tok::code_completion)) {
3015 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
3020 InMessageExpressionRAIIObject InMessage(*this, true);
3022 if (getLangOpts().CPlusPlus) {
3023 // We completely separate the C and C++ cases because C++ requires
3024 // more complicated (read: slower) parsing.
3026 // Handle send to super.
3027 // FIXME: This doesn't benefit from the same typo-correction we
3028 // get in Objective-C.
3029 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
3030 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
3031 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3034 // Parse the receiver, which is either a type or an expression.
3036 void *TypeOrExpr = nullptr;
3037 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
3038 SkipUntil(tok::r_square, StopAtSemi);
3043 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3044 static_cast<Expr *>(TypeOrExpr));
3046 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3047 ParsedType::getFromOpaquePtr(TypeOrExpr),
3051 if (Tok.is(tok::identifier)) {
3052 IdentifierInfo *Name = Tok.getIdentifierInfo();
3053 SourceLocation NameLoc = Tok.getLocation();
3054 ParsedType ReceiverType;
3055 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
3056 Name == Ident_super,
3057 NextToken().is(tok::period),
3059 case Sema::ObjCSuperMessage:
3060 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), nullptr,
3063 case Sema::ObjCClassMessage:
3064 if (!ReceiverType) {
3065 SkipUntil(tok::r_square, StopAtSemi);
3069 ConsumeToken(); // the type name
3071 // Parse type arguments and protocol qualifiers.
3072 if (Tok.is(tok::less)) {
3073 SourceLocation NewEndLoc;
3074 TypeResult NewReceiverType
3075 = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType,
3076 /*consumeLastToken=*/true,
3078 if (!NewReceiverType.isUsable()) {
3079 SkipUntil(tok::r_square, StopAtSemi);
3083 ReceiverType = NewReceiverType.get();
3086 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
3087 ReceiverType, nullptr);
3089 case Sema::ObjCInstanceMessage:
3090 // Fall through to parse an expression.
3095 // Otherwise, an arbitrary expression can be the receiver of a send.
3096 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
3097 if (Res.isInvalid()) {
3098 SkipUntil(tok::r_square, StopAtSemi);
3102 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), nullptr,
3106 /// Parse the remainder of an Objective-C message following the
3107 /// '[' objc-receiver.
3109 /// This routine handles sends to super, class messages (sent to a
3110 /// class name), and instance messages (sent to an object), and the
3111 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
3112 /// ReceiverExpr, respectively. Only one of these parameters may have
3115 /// \param LBracLoc The location of the opening '['.
3117 /// \param SuperLoc If this is a send to 'super', the location of the
3118 /// 'super' keyword that indicates a send to the superclass.
3120 /// \param ReceiverType If this is a class message, the type of the
3121 /// class we are sending a message to.
3123 /// \param ReceiverExpr If this is an instance message, the expression
3124 /// used to compute the receiver object.
3126 /// objc-message-args:
3128 /// objc-keywordarg-list
3130 /// objc-keywordarg-list:
3132 /// objc-keywordarg-list objc-keywordarg
3134 /// objc-keywordarg:
3135 /// selector-name[opt] ':' objc-keywordexpr
3137 /// objc-keywordexpr:
3138 /// nonempty-expr-list
3140 /// nonempty-expr-list:
3141 /// assignment-expression
3142 /// nonempty-expr-list , assignment-expression
3145 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
3146 SourceLocation SuperLoc,
3147 ParsedType ReceiverType,
3148 Expr *ReceiverExpr) {
3149 InMessageExpressionRAIIObject InMessage(*this, true);
3151 if (Tok.is(tok::code_completion)) {
3152 if (SuperLoc.isValid())
3153 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
3155 else if (ReceiverType)
3156 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
3159 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3165 // Parse objc-selector
3167 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
3169 SmallVector<IdentifierInfo *, 12> KeyIdents;
3170 SmallVector<SourceLocation, 12> KeyLocs;
3171 ExprVector KeyExprs;
3173 if (Tok.is(tok::colon)) {
3175 // Each iteration parses a single keyword argument.
3176 KeyIdents.push_back(selIdent);
3177 KeyLocs.push_back(Loc);
3179 if (ExpectAndConsume(tok::colon)) {
3180 // We must manually skip to a ']', otherwise the expression skipper will
3181 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3182 // the enclosing expression.
3183 SkipUntil(tok::r_square, StopAtSemi);
3187 /// Parse the expression after ':'
3189 if (Tok.is(tok::code_completion)) {
3190 if (SuperLoc.isValid())
3191 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3193 /*AtArgumentExpression=*/true);
3194 else if (ReceiverType)
3195 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3197 /*AtArgumentExpression=*/true);
3199 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3201 /*AtArgumentExpression=*/true);
3208 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3209 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3210 Expr = ParseBraceInitializer();
3212 Expr = ParseAssignmentExpression();
3214 ExprResult Res(Expr);
3215 if (Res.isInvalid()) {
3216 // We must manually skip to a ']', otherwise the expression skipper will
3217 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3218 // the enclosing expression.
3219 SkipUntil(tok::r_square, StopAtSemi);
3223 // We have a valid expression.
3224 KeyExprs.push_back(Res.get());
3226 // Code completion after each argument.
3227 if (Tok.is(tok::code_completion)) {
3228 if (SuperLoc.isValid())
3229 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
3231 /*AtArgumentExpression=*/false);
3232 else if (ReceiverType)
3233 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
3235 /*AtArgumentExpression=*/false);
3237 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
3239 /*AtArgumentExpression=*/false);
3244 // Check for another keyword selector.
3245 selIdent = ParseObjCSelectorPiece(Loc);
3246 if (!selIdent && Tok.isNot(tok::colon))
3248 // We have a selector or a colon, continue parsing.
3250 // Parse the, optional, argument list, comma separated.
3251 while (Tok.is(tok::comma)) {
3252 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
3253 /// Parse the expression after ','
3254 ExprResult Res(ParseAssignmentExpression());
3255 if (Tok.is(tok::colon))
3256 Res = Actions.CorrectDelayedTyposInExpr(Res);
3257 if (Res.isInvalid()) {
3258 if (Tok.is(tok::colon)) {
3259 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
3260 FixItHint::CreateRemoval(commaLoc);
3262 // We must manually skip to a ']', otherwise the expression skipper will
3263 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3264 // the enclosing expression.
3265 SkipUntil(tok::r_square, StopAtSemi);
3269 // We have a valid expression.
3270 KeyExprs.push_back(Res.get());
3272 } else if (!selIdent) {
3273 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
3275 // We must manually skip to a ']', otherwise the expression skipper will
3276 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3277 // the enclosing expression.
3278 SkipUntil(tok::r_square, StopAtSemi);
3282 if (Tok.isNot(tok::r_square)) {
3283 Diag(Tok, diag::err_expected)
3284 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
3285 // We must manually skip to a ']', otherwise the expression skipper will
3286 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3287 // the enclosing expression.
3288 SkipUntil(tok::r_square, StopAtSemi);
3292 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
3294 unsigned nKeys = KeyIdents.size();
3296 KeyIdents.push_back(selIdent);
3297 KeyLocs.push_back(Loc);
3299 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
3301 if (SuperLoc.isValid())
3302 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
3303 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3304 else if (ReceiverType)
3305 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
3306 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3307 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
3308 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
3311 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
3312 ExprResult Res(ParseStringLiteralExpression());
3313 if (Res.isInvalid()) return Res;
3315 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
3316 // expressions. At this point, we know that the only valid thing that starts
3317 // with '@' is an @"".
3318 SmallVector<SourceLocation, 4> AtLocs;
3319 ExprVector AtStrings;
3320 AtLocs.push_back(AtLoc);
3321 AtStrings.push_back(Res.get());
3323 while (Tok.is(tok::at)) {
3324 AtLocs.push_back(ConsumeToken()); // eat the @.
3326 // Invalid unless there is a string literal.
3327 if (!isTokenStringLiteral())
3328 return ExprError(Diag(Tok, diag::err_objc_concat_string));
3330 ExprResult Lit(ParseStringLiteralExpression());
3331 if (Lit.isInvalid())
3334 AtStrings.push_back(Lit.get());
3337 return Actions.ParseObjCStringLiteral(AtLocs.data(), AtStrings);
3340 /// ParseObjCBooleanLiteral -
3341 /// objc-scalar-literal : '@' boolean-keyword
3343 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
3345 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
3347 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
3348 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
3351 /// ParseObjCCharacterLiteral -
3352 /// objc-scalar-literal : '@' character-literal
3354 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
3355 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
3356 if (Lit.isInvalid()) {
3359 ConsumeToken(); // Consume the literal token.
3360 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3363 /// ParseObjCNumericLiteral -
3364 /// objc-scalar-literal : '@' scalar-literal
3366 /// scalar-literal : | numeric-constant /* any numeric constant. */
3368 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
3369 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
3370 if (Lit.isInvalid()) {
3373 ConsumeToken(); // Consume the literal token.
3374 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
3377 /// ParseObjCBoxedExpr -
3378 /// objc-box-expression:
3379 /// @( assignment-expression )
3381 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
3382 if (Tok.isNot(tok::l_paren))
3383 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
3385 BalancedDelimiterTracker T(*this, tok::l_paren);
3387 ExprResult ValueExpr(ParseAssignmentExpression());
3388 if (T.consumeClose())
3391 if (ValueExpr.isInvalid())
3394 // Wrap the sub-expression in a parenthesized expression, to distinguish
3395 // a boxed expression from a literal.
3396 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
3397 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
3398 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
3402 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
3403 ExprVector ElementExprs; // array elements.
3404 ConsumeBracket(); // consume the l_square.
3406 bool HasInvalidEltExpr = false;
3407 while (Tok.isNot(tok::r_square)) {
3408 // Parse list of array element expressions (all must be id types).
3409 ExprResult Res(ParseAssignmentExpression());
3410 if (Res.isInvalid()) {
3411 // We must manually skip to a ']', otherwise the expression skipper will
3412 // stop at the ']' when it skips to the ';'. We want it to skip beyond
3413 // the enclosing expression.
3414 SkipUntil(tok::r_square, StopAtSemi);
3418 Res = Actions.CorrectDelayedTyposInExpr(Res.get());
3419 if (Res.isInvalid())
3420 HasInvalidEltExpr = true;
3422 // Parse the ellipsis that indicates a pack expansion.
3423 if (Tok.is(tok::ellipsis))
3424 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
3425 if (Res.isInvalid())
3426 HasInvalidEltExpr = true;
3428 ElementExprs.push_back(Res.get());
3430 if (Tok.is(tok::comma))
3431 ConsumeToken(); // Eat the ','.
3432 else if (Tok.isNot(tok::r_square))
3433 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
3436 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
3438 if (HasInvalidEltExpr)
3441 MultiExprArg Args(ElementExprs);
3442 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
3445 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
3446 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
3447 ConsumeBrace(); // consume the l_square.
3448 bool HasInvalidEltExpr = false;
3449 while (Tok.isNot(tok::r_brace)) {
3450 // Parse the comma separated key : value expressions.
3453 ColonProtectionRAIIObject X(*this);
3454 KeyExpr = ParseAssignmentExpression();
3455 if (KeyExpr.isInvalid()) {
3456 // We must manually skip to a '}', otherwise the expression skipper will
3457 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3458 // the enclosing expression.
3459 SkipUntil(tok::r_brace, StopAtSemi);
3464 if (ExpectAndConsume(tok::colon)) {
3465 SkipUntil(tok::r_brace, StopAtSemi);
3469 ExprResult ValueExpr(ParseAssignmentExpression());
3470 if (ValueExpr.isInvalid()) {
3471 // We must manually skip to a '}', otherwise the expression skipper will
3472 // stop at the '}' when it skips to the ';'. We want it to skip beyond
3473 // the enclosing expression.
3474 SkipUntil(tok::r_brace, StopAtSemi);
3478 // Check the key and value for possible typos
3479 KeyExpr = Actions.CorrectDelayedTyposInExpr(KeyExpr.get());
3480 ValueExpr = Actions.CorrectDelayedTyposInExpr(ValueExpr.get());
3481 if (KeyExpr.isInvalid() || ValueExpr.isInvalid())
3482 HasInvalidEltExpr = true;
3484 // Parse the ellipsis that designates this as a pack expansion. Do not
3485 // ActOnPackExpansion here, leave it to template instantiation time where
3486 // we can get better diagnostics.
3487 SourceLocation EllipsisLoc;
3488 if (getLangOpts().CPlusPlus)
3489 TryConsumeToken(tok::ellipsis, EllipsisLoc);
3491 // We have a valid expression. Collect it in a vector so we can
3492 // build the argument list.
3493 ObjCDictionaryElement Element = {
3494 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
3496 Elements.push_back(Element);
3498 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
3499 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
3502 SourceLocation EndLoc = ConsumeBrace();
3504 if (HasInvalidEltExpr)
3507 // Create the ObjCDictionaryLiteral.
3508 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
3512 /// objc-encode-expression:
3513 /// \@encode ( type-name )
3515 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
3516 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
3518 SourceLocation EncLoc = ConsumeToken();
3520 if (Tok.isNot(tok::l_paren))
3521 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
3523 BalancedDelimiterTracker T(*this, tok::l_paren);
3526 TypeResult Ty = ParseTypeName();
3533 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
3534 Ty.get(), T.getCloseLocation());
3537 /// objc-protocol-expression
3538 /// \@protocol ( protocol-name )
3540 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
3541 SourceLocation ProtoLoc = ConsumeToken();
3543 if (Tok.isNot(tok::l_paren))
3544 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
3546 BalancedDelimiterTracker T(*this, tok::l_paren);
3549 if (expectIdentifier())
3552 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
3553 SourceLocation ProtoIdLoc = ConsumeToken();
3557 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
3558 T.getOpenLocation(), ProtoIdLoc,
3559 T.getCloseLocation());
3562 /// objc-selector-expression
3563 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
3564 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
3565 SourceLocation SelectorLoc = ConsumeToken();
3567 if (Tok.isNot(tok::l_paren))
3568 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
3570 SmallVector<IdentifierInfo *, 12> KeyIdents;
3571 SourceLocation sLoc;
3573 BalancedDelimiterTracker T(*this, tok::l_paren);
3575 bool HasOptionalParen = Tok.is(tok::l_paren);
3576 if (HasOptionalParen)
3579 if (Tok.is(tok::code_completion)) {
3580 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3585 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
3586 if (!SelIdent && // missing selector name.
3587 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3588 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
3590 KeyIdents.push_back(SelIdent);
3592 unsigned nColons = 0;
3593 if (Tok.isNot(tok::r_paren)) {
3595 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
3597 KeyIdents.push_back(nullptr);
3598 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
3602 if (Tok.is(tok::r_paren))
3605 if (Tok.is(tok::code_completion)) {
3606 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
3611 // Check for another keyword selector.
3613 SelIdent = ParseObjCSelectorPiece(Loc);
3614 KeyIdents.push_back(SelIdent);
3615 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
3619 if (HasOptionalParen && Tok.is(tok::r_paren))
3620 ConsumeParen(); // ')'
3622 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
3623 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
3624 T.getOpenLocation(),
3625 T.getCloseLocation(),
3629 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
3630 // MCDecl might be null due to error in method or c-function prototype, etc.
3631 Decl *MCDecl = LM.D;
3632 bool skip = MCDecl &&
3633 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
3634 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
3638 // Save the current token position.
3639 SourceLocation OrigLoc = Tok.getLocation();
3641 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
3642 // Store an artificial EOF token to ensure that we don't run off the end of
3643 // the method's body when we come to parse it.
3646 Eof.setKind(tok::eof);
3647 Eof.setEofData(MCDecl);
3648 Eof.setLocation(OrigLoc);
3649 LM.Toks.push_back(Eof);
3650 // Append the current token at the end of the new token stream so that it
3651 // doesn't get lost.
3652 LM.Toks.push_back(Tok);
3653 PP.EnterTokenStream(LM.Toks, true, /*IsReinject*/true);
3655 // Consume the previously pushed token.
3656 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3658 assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) &&
3659 "Inline objective-c method not starting with '{' or 'try' or ':'");
3660 // Enter a scope for the method or c-function body.
3661 ParseScope BodyScope(this, (parseMethod ? Scope::ObjCMethodScope : 0) |
3662 Scope::FnScope | Scope::DeclScope |
3663 Scope::CompoundStmtScope);
3665 // Tell the actions module that we have entered a method or c-function definition
3666 // with the specified Declarator for the method/function.
3668 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
3670 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
3671 if (Tok.is(tok::kw_try))
3672 ParseFunctionTryBlock(MCDecl, BodyScope);
3674 if (Tok.is(tok::colon))
3675 ParseConstructorInitializer(MCDecl);
3677 Actions.ActOnDefaultCtorInitializers(MCDecl);
3678 ParseFunctionStatementBody(MCDecl, BodyScope);
3681 if (Tok.getLocation() != OrigLoc) {
3682 // Due to parsing error, we either went over the cached tokens or
3683 // there are still cached tokens left. If it's the latter case skip the
3685 // Since this is an uncommon situation that should be avoided, use the
3686 // expensive isBeforeInTranslationUnit call.
3687 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
3689 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
3692 // Clean up the remaining EOF token.