1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Objective-C portions of the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Sema/DeclSpec.h"
19 #include "clang/Sema/PrettyDeclStackTrace.h"
20 #include "clang/Sema/Scope.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 using namespace clang;
25 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
26 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
27 ParsedAttributes attrs(AttrFactory);
28 if (Tok.is(tok::kw___attribute)) {
29 if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
30 Diag(Tok, diag::err_objc_postfix_attribute_hint)
31 << (Kind == tok::objc_protocol);
33 Diag(Tok, diag::err_objc_postfix_attribute);
34 ParseGNUAttributes(attrs);
38 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
39 /// external-declaration: [C99 6.9]
40 /// [OBJC] objc-class-definition
41 /// [OBJC] objc-class-declaration
42 /// [OBJC] objc-alias-declaration
43 /// [OBJC] objc-protocol-definition
44 /// [OBJC] objc-method-definition
46 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() {
47 SourceLocation AtLoc = ConsumeToken(); // the "@"
49 if (Tok.is(tok::code_completion)) {
50 Actions.CodeCompleteObjCAtDirective(getCurScope());
52 return DeclGroupPtrTy();
55 Decl *SingleDecl = nullptr;
56 switch (Tok.getObjCKeywordID()) {
58 return ParseObjCAtClassDeclaration(AtLoc);
59 case tok::objc_interface: {
60 ParsedAttributes attrs(AttrFactory);
61 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
64 case tok::objc_protocol: {
65 ParsedAttributes attrs(AttrFactory);
66 return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
68 case tok::objc_implementation:
69 return ParseObjCAtImplementationDeclaration(AtLoc);
71 return ParseObjCAtEndDeclaration(AtLoc);
72 case tok::objc_compatibility_alias:
73 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
75 case tok::objc_synthesize:
76 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
78 case tok::objc_dynamic:
79 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
81 case tok::objc_import:
82 if (getLangOpts().Modules || getLangOpts().DebuggerSupport)
83 return 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);
97 /// objc-class-declaration:
98 /// '@' 'class' identifier-list ';'
100 Parser::DeclGroupPtrTy
101 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
102 ConsumeToken(); // the identifier "class"
103 SmallVector<IdentifierInfo *, 8> ClassNames;
104 SmallVector<SourceLocation, 8> ClassLocs;
108 MaybeSkipAttributes(tok::objc_class);
109 if (Tok.isNot(tok::identifier)) {
110 Diag(Tok, diag::err_expected) << tok::identifier;
111 SkipUntil(tok::semi);
112 return Actions.ConvertDeclToDeclGroup(nullptr);
114 ClassNames.push_back(Tok.getIdentifierInfo());
115 ClassLocs.push_back(Tok.getLocation());
118 if (!TryConsumeToken(tok::comma))
123 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
124 return Actions.ConvertDeclToDeclGroup(nullptr);
126 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
131 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
133 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
134 if (ock == Sema::OCK_None)
137 Decl *Decl = Actions.getObjCDeclContext();
138 if (CurParsedObjCImpl) {
139 CurParsedObjCImpl->finish(AtLoc);
141 Actions.ActOnAtEnd(getCurScope(), AtLoc);
143 Diag(AtLoc, diag::err_objc_missing_end)
144 << FixItHint::CreateInsertion(AtLoc, "@end\n");
146 Diag(Decl->getLocStart(), diag::note_objc_container_start)
152 /// objc-class-interface-attributes[opt] objc-class-interface
153 /// objc-category-interface
155 /// objc-class-interface:
156 /// '@' 'interface' identifier objc-superclass[opt]
157 /// objc-protocol-refs[opt]
158 /// objc-class-instance-variables[opt]
159 /// objc-interface-decl-list
162 /// objc-category-interface:
163 /// '@' 'interface' identifier '(' identifier[opt] ')'
164 /// objc-protocol-refs[opt]
165 /// objc-interface-decl-list
171 /// objc-class-interface-attributes:
172 /// __attribute__((visibility("default")))
173 /// __attribute__((visibility("hidden")))
174 /// __attribute__((deprecated))
175 /// __attribute__((unavailable))
176 /// __attribute__((objc_exception)) - used by NSException on 64-bit
177 /// __attribute__((objc_root_class))
179 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
180 ParsedAttributes &attrs) {
181 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
182 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
183 CheckNestedObjCContexts(AtLoc);
184 ConsumeToken(); // the "interface" identifier
186 // Code completion after '@interface'.
187 if (Tok.is(tok::code_completion)) {
188 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
193 MaybeSkipAttributes(tok::objc_interface);
195 if (Tok.isNot(tok::identifier)) {
196 Diag(Tok, diag::err_expected)
197 << tok::identifier; // missing class or category name.
201 // We have a class or category name - consume it.
202 IdentifierInfo *nameId = Tok.getIdentifierInfo();
203 SourceLocation nameLoc = ConsumeToken();
204 if (Tok.is(tok::l_paren) &&
205 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
207 BalancedDelimiterTracker T(*this, tok::l_paren);
210 SourceLocation categoryLoc;
211 IdentifierInfo *categoryId = nullptr;
212 if (Tok.is(tok::code_completion)) {
213 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
218 // For ObjC2, the category name is optional (not an error).
219 if (Tok.is(tok::identifier)) {
220 categoryId = Tok.getIdentifierInfo();
221 categoryLoc = ConsumeToken();
223 else if (!getLangOpts().ObjC2) {
224 Diag(Tok, diag::err_expected)
225 << tok::identifier; // missing category name.
230 if (T.getCloseLocation().isInvalid())
233 if (!attrs.empty()) { // categories don't support attributes.
234 Diag(nameLoc, diag::err_objc_no_attributes_on_category);
238 // Next, we need to check for any protocol references.
239 SourceLocation LAngleLoc, EndProtoLoc;
240 SmallVector<Decl *, 8> ProtocolRefs;
241 SmallVector<SourceLocation, 8> ProtocolLocs;
242 if (Tok.is(tok::less) &&
243 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
244 LAngleLoc, EndProtoLoc))
248 Actions.ActOnStartCategoryInterface(AtLoc,
250 categoryId, categoryLoc,
256 if (Tok.is(tok::l_brace))
257 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
259 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
262 // Parse a class interface.
263 IdentifierInfo *superClassId = nullptr;
264 SourceLocation superClassLoc;
266 if (Tok.is(tok::colon)) { // a super class is specified.
269 // Code completion of superclass names.
270 if (Tok.is(tok::code_completion)) {
271 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
276 if (Tok.isNot(tok::identifier)) {
277 Diag(Tok, diag::err_expected)
278 << tok::identifier; // missing super class name.
281 superClassId = Tok.getIdentifierInfo();
282 superClassLoc = ConsumeToken();
284 // Next, we need to check for any protocol references.
285 SmallVector<Decl *, 8> ProtocolRefs;
286 SmallVector<SourceLocation, 8> ProtocolLocs;
287 SourceLocation LAngleLoc, EndProtoLoc;
288 if (Tok.is(tok::less) &&
289 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
290 LAngleLoc, EndProtoLoc))
293 if (Tok.isNot(tok::less))
294 Actions.ActOnTypedefedProtocols(ProtocolRefs, superClassId, superClassLoc);
297 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
298 superClassId, superClassLoc,
299 ProtocolRefs.data(), ProtocolRefs.size(),
301 EndProtoLoc, attrs.getList());
303 if (Tok.is(tok::l_brace))
304 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
306 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
310 /// objc-interface-decl-list:
312 /// objc-interface-decl-list objc-property-decl [OBJC2]
313 /// objc-interface-decl-list objc-method-requirement [OBJC2]
314 /// objc-interface-decl-list objc-method-proto ';'
315 /// objc-interface-decl-list declaration
316 /// objc-interface-decl-list ';'
318 /// objc-method-requirement: [OBJC2]
322 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
324 SmallVector<Decl *, 32> allMethods;
325 SmallVector<Decl *, 16> allProperties;
326 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
327 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
332 // If this is a method prototype, parse it.
333 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
334 if (Decl *methodPrototype =
335 ParseObjCMethodPrototype(MethodImplKind, false))
336 allMethods.push_back(methodPrototype);
337 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
338 // method definitions.
339 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
340 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
341 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
342 if (Tok.is(tok::semi))
347 if (Tok.is(tok::l_paren)) {
348 Diag(Tok, diag::err_expected_minus_or_plus);
349 ParseObjCMethodDecl(Tok.getLocation(),
351 MethodImplKind, false);
354 // Ignore excess semicolons.
355 if (Tok.is(tok::semi)) {
360 // If we got to the end of the file, exit the loop.
364 // Code completion within an Objective-C interface.
365 if (Tok.is(tok::code_completion)) {
366 Actions.CodeCompleteOrdinaryName(getCurScope(),
367 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
368 : Sema::PCC_ObjCInterface);
369 return cutOffParsing();
372 // If we don't have an @ directive, parse it as a function definition.
373 if (Tok.isNot(tok::at)) {
374 // The code below does not consume '}'s because it is afraid of eating the
375 // end of a namespace. Because of the way this code is structured, an
376 // erroneous r_brace would cause an infinite loop if not handled here.
377 if (Tok.is(tok::r_brace))
379 ParsedAttributesWithRange attrs(AttrFactory);
380 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
384 // Otherwise, we have an @ directive, eat the @.
385 SourceLocation AtLoc = ConsumeToken(); // the "@"
386 if (Tok.is(tok::code_completion)) {
387 Actions.CodeCompleteObjCAtDirective(getCurScope());
388 return cutOffParsing();
391 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
393 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
394 AtEnd.setBegin(AtLoc);
395 AtEnd.setEnd(Tok.getLocation());
397 } else if (DirectiveKind == tok::objc_not_keyword) {
398 Diag(Tok, diag::err_objc_unknown_at);
399 SkipUntil(tok::semi);
403 // Eat the identifier.
406 switch (DirectiveKind) {
408 // FIXME: If someone forgets an @end on a protocol, this loop will
409 // continue to eat up tons of stuff and spew lots of nonsense errors. It
410 // would probably be better to bail out if we saw an @class or @interface
411 // or something like that.
412 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
413 // Skip until we see an '@' or '}' or ';'.
414 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
417 case tok::objc_implementation:
418 case tok::objc_interface:
419 Diag(AtLoc, diag::err_objc_missing_end)
420 << FixItHint::CreateInsertion(AtLoc, "@end\n");
421 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
422 << (int) Actions.getObjCContainerKind();
426 case tok::objc_required:
427 case tok::objc_optional:
428 // This is only valid on protocols.
429 // FIXME: Should this check for ObjC2 being enabled?
430 if (contextKey != tok::objc_protocol)
431 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
433 MethodImplKind = DirectiveKind;
436 case tok::objc_property:
437 if (!getLangOpts().ObjC2)
438 Diag(AtLoc, diag::err_objc_properties_require_objc2);
441 SourceLocation LParenLoc;
442 // Parse property attribute list, if any.
443 if (Tok.is(tok::l_paren)) {
444 LParenLoc = Tok.getLocation();
445 ParseObjCPropertyAttribute(OCDS);
448 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
449 if (FD.D.getIdentifier() == nullptr) {
450 Diag(AtLoc, diag::err_objc_property_requires_field_name)
451 << FD.D.getSourceRange();
454 if (FD.BitfieldSize) {
455 Diag(AtLoc, diag::err_objc_property_bitfield)
456 << FD.D.getSourceRange();
460 // Install the property declarator into interfaceDecl.
461 IdentifierInfo *SelName =
462 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
464 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
465 IdentifierInfo *SetterName = OCDS.getSetterName();
468 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
470 SetterSel = SelectorTable::constructSetterSelector(
471 PP.getIdentifierTable(), PP.getSelectorTable(),
472 FD.D.getIdentifier());
473 bool isOverridingProperty = false;
474 Decl *Property = Actions.ActOnProperty(
475 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
476 &isOverridingProperty, MethodImplKind);
477 if (!isOverridingProperty)
478 allProperties.push_back(Property);
480 FD.complete(Property);
483 // Parse all the comma separated declarators.
484 ParsingDeclSpec DS(*this);
485 ParseStructDeclaration(DS, ObjCPropertyCallback);
487 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
492 // We break out of the big loop in two cases: when we see @end or when we see
493 // EOF. In the former case, eat the @end. In the later case, emit an error.
494 if (Tok.is(tok::code_completion)) {
495 Actions.CodeCompleteObjCAtDirective(getCurScope());
496 return cutOffParsing();
497 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
498 ConsumeToken(); // the "end" identifier
500 Diag(Tok, diag::err_objc_missing_end)
501 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
502 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
503 << (int) Actions.getObjCContainerKind();
504 AtEnd.setBegin(Tok.getLocation());
505 AtEnd.setEnd(Tok.getLocation());
508 // Insert collected methods declarations into the @interface object.
509 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
510 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
513 /// Parse property attribute declarations.
515 /// property-attr-decl: '(' property-attrlist ')'
516 /// property-attrlist:
517 /// property-attribute
518 /// property-attrlist ',' property-attribute
519 /// property-attribute:
520 /// getter '=' identifier
521 /// setter '=' identifier ':'
531 /// unsafe_unretained
533 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
534 assert(Tok.getKind() == tok::l_paren);
535 BalancedDelimiterTracker T(*this, tok::l_paren);
539 if (Tok.is(tok::code_completion)) {
540 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
541 return cutOffParsing();
543 const IdentifierInfo *II = Tok.getIdentifierInfo();
545 // If this is not an identifier at all, bail out early.
551 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
553 if (II->isStr("readonly"))
554 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
555 else if (II->isStr("assign"))
556 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
557 else if (II->isStr("unsafe_unretained"))
558 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
559 else if (II->isStr("readwrite"))
560 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
561 else if (II->isStr("retain"))
562 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
563 else if (II->isStr("strong"))
564 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
565 else if (II->isStr("copy"))
566 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
567 else if (II->isStr("nonatomic"))
568 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
569 else if (II->isStr("atomic"))
570 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
571 else if (II->isStr("weak"))
572 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
573 else if (II->isStr("getter") || II->isStr("setter")) {
574 bool IsSetter = II->getNameStart()[0] == 's';
576 // getter/setter require extra treatment.
577 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
578 diag::err_objc_expected_equal_for_getter;
580 if (ExpectAndConsume(tok::equal, DiagID)) {
581 SkipUntil(tok::r_paren, StopAtSemi);
585 if (Tok.is(tok::code_completion)) {
587 Actions.CodeCompleteObjCPropertySetter(getCurScope());
589 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
590 return cutOffParsing();
594 SourceLocation SelLoc;
595 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
598 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
600 SkipUntil(tok::r_paren, StopAtSemi);
605 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
606 DS.setSetterName(SelIdent);
608 if (ExpectAndConsume(tok::colon,
609 diag::err_expected_colon_after_setter_name)) {
610 SkipUntil(tok::r_paren, StopAtSemi);
614 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
615 DS.setGetterName(SelIdent);
618 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
619 SkipUntil(tok::r_paren, StopAtSemi);
623 if (Tok.isNot(tok::comma))
632 /// objc-method-proto:
633 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
634 /// objc-class-method objc-method-decl objc-method-attributes[opt]
636 /// objc-instance-method: '-'
637 /// objc-class-method: '+'
639 /// objc-method-attributes: [OBJC2]
640 /// __attribute__((deprecated))
642 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
643 bool MethodDefinition) {
644 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
646 tok::TokenKind methodType = Tok.getKind();
647 SourceLocation mLoc = ConsumeToken();
648 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
650 // Since this rule is used for both method declarations and definitions,
651 // the caller is (optionally) responsible for consuming the ';'.
658 /// enum struct union if else while do for switch case default
659 /// break continue return goto asm sizeof typeof __alignof
660 /// unsigned long const short volatile signed restrict _Complex
661 /// in out inout bycopy byref oneway int char float double void _Bool
663 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
665 switch (Tok.getKind()) {
674 case tok::exclaimequal:
678 case tok::caretequal: {
679 std::string ThisTok(PP.getSpelling(Tok));
680 if (isLetter(ThisTok[0])) {
681 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
682 Tok.setKind(tok::identifier);
683 SelectorLoc = ConsumeToken();
689 case tok::identifier:
699 case tok::kw_const_cast:
700 case tok::kw_continue:
701 case tok::kw_default:
705 case tok::kw_dynamic_cast:
708 case tok::kw_explicit:
720 case tok::kw_mutable:
721 case tok::kw_namespace:
723 case tok::kw_operator:
724 case tok::kw_private:
725 case tok::kw_protected:
727 case tok::kw_register:
728 case tok::kw_reinterpret_cast:
729 case tok::kw_restrict:
735 case tok::kw_static_cast:
738 case tok::kw_template:
743 case tok::kw_typedef:
745 case tok::kw_typename:
748 case tok::kw_unsigned:
750 case tok::kw_virtual:
752 case tok::kw_volatile:
753 case tok::kw_wchar_t:
756 case tok::kw__Complex:
757 case tok::kw___alignof:
758 IdentifierInfo *II = Tok.getIdentifierInfo();
759 SelectorLoc = ConsumeToken();
764 /// objc-for-collection-in: 'in'
766 bool Parser::isTokIdentifier_in() const {
767 // FIXME: May have to do additional look-ahead to only allow for
768 // valid tokens following an 'in'; such as an identifier, unary operators,
770 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
771 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
774 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
775 /// qualifier list and builds their bitmask representation in the input
778 /// objc-type-qualifiers:
779 /// objc-type-qualifier
780 /// objc-type-qualifiers objc-type-qualifier
782 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
783 Declarator::TheContext Context) {
784 assert(Context == Declarator::ObjCParameterContext ||
785 Context == Declarator::ObjCResultContext);
788 if (Tok.is(tok::code_completion)) {
789 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
790 Context == Declarator::ObjCParameterContext);
791 return cutOffParsing();
794 if (Tok.isNot(tok::identifier))
797 const IdentifierInfo *II = Tok.getIdentifierInfo();
798 for (unsigned i = 0; i != objc_NumQuals; ++i) {
799 if (II != ObjCTypeQuals[i])
802 ObjCDeclSpec::ObjCDeclQualifier Qual;
804 default: llvm_unreachable("Unknown decl qualifier");
805 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
806 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
807 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
808 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
809 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
810 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
812 DS.setObjCDeclQualifier(Qual);
818 // If this wasn't a recognized qualifier, bail out.
823 /// Take all the decl attributes out of the given list and add
824 /// them to the given attribute set.
825 static void takeDeclAttributes(ParsedAttributes &attrs,
826 AttributeList *list) {
828 AttributeList *cur = list;
829 list = cur->getNext();
831 if (!cur->isUsedAsTypeAttr()) {
832 // Clear out the next pointer. We're really completely
833 // destroying the internal invariants of the declarator here,
834 // but it doesn't matter because we're done with it.
835 cur->setNext(nullptr);
841 /// takeDeclAttributes - Take all the decl attributes from the given
842 /// declarator and add them to the given list.
843 static void takeDeclAttributes(ParsedAttributes &attrs,
845 // First, take ownership of all attributes.
846 attrs.getPool().takeAllFrom(D.getAttributePool());
847 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
849 // Now actually move the attributes over.
850 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
851 takeDeclAttributes(attrs, D.getAttributes());
852 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
853 takeDeclAttributes(attrs,
854 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
858 /// '(' objc-type-qualifiers[opt] type-name ')'
859 /// '(' objc-type-qualifiers[opt] ')'
861 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
862 Declarator::TheContext context,
863 ParsedAttributes *paramAttrs) {
864 assert(context == Declarator::ObjCParameterContext ||
865 context == Declarator::ObjCResultContext);
866 assert((paramAttrs != nullptr) ==
867 (context == Declarator::ObjCParameterContext));
869 assert(Tok.is(tok::l_paren) && "expected (");
871 BalancedDelimiterTracker T(*this, tok::l_paren);
874 SourceLocation TypeStartLoc = Tok.getLocation();
875 ObjCDeclContextSwitch ObjCDC(*this);
877 // Parse type qualifiers, in, inout, etc.
878 ParseObjCTypeQualifierList(DS, context);
881 if (isTypeSpecifierQualifier()) {
882 // Parse an abstract declarator.
883 DeclSpec declSpec(AttrFactory);
884 declSpec.setObjCQualifiers(&DS);
885 ParseSpecifierQualifierList(declSpec);
886 declSpec.SetRangeEnd(Tok.getLocation());
887 Declarator declarator(declSpec, context);
888 ParseDeclarator(declarator);
890 // If that's not invalid, extract a type.
891 if (!declarator.isInvalidType()) {
892 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
893 if (!type.isInvalid())
896 // If we're parsing a parameter, steal all the decl attributes
897 // and add them to the decl spec.
898 if (context == Declarator::ObjCParameterContext)
899 takeDeclAttributes(*paramAttrs, declarator);
901 } else if (context == Declarator::ObjCResultContext &&
902 Tok.is(tok::identifier)) {
903 if (!Ident_instancetype)
904 Ident_instancetype = PP.getIdentifierInfo("instancetype");
906 if (Tok.getIdentifierInfo() == Ident_instancetype) {
907 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
912 if (Tok.is(tok::r_paren))
914 else if (Tok.getLocation() == TypeStartLoc) {
915 // If we didn't eat any tokens, then this isn't a type.
916 Diag(Tok, diag::err_expected_type);
917 SkipUntil(tok::r_paren, StopAtSemi);
919 // Otherwise, we found *something*, but didn't get a ')' in the right
920 // place. Emit an error then return what we have as the type.
926 /// objc-method-decl:
928 /// objc-keyword-selector objc-parmlist[opt]
929 /// objc-type-name objc-selector
930 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
932 /// objc-keyword-selector:
933 /// objc-keyword-decl
934 /// objc-keyword-selector objc-keyword-decl
936 /// objc-keyword-decl:
937 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
938 /// objc-selector ':' objc-keyword-attributes[opt] identifier
939 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
940 /// ':' objc-keyword-attributes[opt] identifier
943 /// objc-parms objc-ellipsis[opt]
946 /// objc-parms , parameter-declaration
951 /// objc-keyword-attributes: [OBJC2]
952 /// __attribute__((unused))
954 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
955 tok::TokenKind mType,
956 tok::ObjCKeywordKind MethodImplKind,
957 bool MethodDefinition) {
958 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
960 if (Tok.is(tok::code_completion)) {
961 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
962 /*ReturnType=*/ ParsedType());
967 // Parse the return type if present.
968 ParsedType ReturnType;
970 if (Tok.is(tok::l_paren))
971 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
974 // If attributes exist before the method, parse them.
975 ParsedAttributes methodAttrs(AttrFactory);
976 if (getLangOpts().ObjC2)
977 MaybeParseGNUAttributes(methodAttrs);
979 if (Tok.is(tok::code_completion)) {
980 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
986 // Now parse the selector.
987 SourceLocation selLoc;
988 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
990 // An unnamed colon is valid.
991 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
992 Diag(Tok, diag::err_expected_selector_for_method)
993 << SourceRange(mLoc, Tok.getLocation());
994 // Skip until we get a ; or @.
995 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
999 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1000 if (Tok.isNot(tok::colon)) {
1001 // If attributes exist after the method, parse them.
1002 if (getLangOpts().ObjC2)
1003 MaybeParseGNUAttributes(methodAttrs);
1005 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1007 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1008 mType, DSRet, ReturnType,
1009 selLoc, Sel, nullptr,
1010 CParamInfo.data(), CParamInfo.size(),
1011 methodAttrs.getList(), MethodImplKind,
1012 false, MethodDefinition);
1013 PD.complete(Result);
1017 SmallVector<IdentifierInfo *, 12> KeyIdents;
1018 SmallVector<SourceLocation, 12> KeyLocs;
1019 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1020 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1021 Scope::FunctionDeclarationScope | Scope::DeclScope);
1023 AttributePool allParamAttrs(AttrFactory);
1025 ParsedAttributes paramAttrs(AttrFactory);
1026 Sema::ObjCArgInfo ArgInfo;
1028 // Each iteration parses a single keyword argument.
1029 if (ExpectAndConsume(tok::colon))
1032 ArgInfo.Type = ParsedType();
1033 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1034 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1035 Declarator::ObjCParameterContext,
1038 // If attributes exist before the argument name, parse them.
1039 // Regardless, collect all the attributes we've parsed so far.
1040 ArgInfo.ArgAttrs = nullptr;
1041 if (getLangOpts().ObjC2) {
1042 MaybeParseGNUAttributes(paramAttrs);
1043 ArgInfo.ArgAttrs = paramAttrs.getList();
1046 // Code completion for the next piece of the selector.
1047 if (Tok.is(tok::code_completion)) {
1048 KeyIdents.push_back(SelIdent);
1049 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1050 mType == tok::minus,
1051 /*AtParameterName=*/true,
1052 ReturnType, KeyIdents);
1057 if (Tok.isNot(tok::identifier)) {
1058 Diag(Tok, diag::err_expected)
1059 << tok::identifier; // missing argument name.
1063 ArgInfo.Name = Tok.getIdentifierInfo();
1064 ArgInfo.NameLoc = Tok.getLocation();
1065 ConsumeToken(); // Eat the identifier.
1067 ArgInfos.push_back(ArgInfo);
1068 KeyIdents.push_back(SelIdent);
1069 KeyLocs.push_back(selLoc);
1071 // Make sure the attributes persist.
1072 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1074 // Code completion for the next piece of the selector.
1075 if (Tok.is(tok::code_completion)) {
1076 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1077 mType == tok::minus,
1078 /*AtParameterName=*/false,
1079 ReturnType, KeyIdents);
1084 // Check for another keyword selector.
1085 SelIdent = ParseObjCSelectorPiece(selLoc);
1086 if (!SelIdent && Tok.isNot(tok::colon))
1089 SourceLocation ColonLoc = Tok.getLocation();
1090 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1091 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1092 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1093 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1096 // We have a selector or a colon, continue parsing.
1099 bool isVariadic = false;
1100 bool cStyleParamWarned = false;
1101 // Parse the (optional) parameter list.
1102 while (Tok.is(tok::comma)) {
1104 if (Tok.is(tok::ellipsis)) {
1109 if (!cStyleParamWarned) {
1110 Diag(Tok, diag::warn_cstyle_param);
1111 cStyleParamWarned = true;
1113 DeclSpec DS(AttrFactory);
1114 ParseDeclarationSpecifiers(DS);
1115 // Parse the declarator.
1116 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1117 ParseDeclarator(ParmDecl);
1118 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1119 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1120 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1121 ParmDecl.getIdentifierLoc(),
1126 // FIXME: Add support for optional parameter list...
1127 // If attributes exist after the method, parse them.
1128 if (getLangOpts().ObjC2)
1129 MaybeParseGNUAttributes(methodAttrs);
1131 if (KeyIdents.size() == 0)
1134 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1137 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1138 mType, DSRet, ReturnType,
1139 KeyLocs, Sel, &ArgInfos[0],
1140 CParamInfo.data(), CParamInfo.size(),
1141 methodAttrs.getList(),
1142 MethodImplKind, isVariadic, MethodDefinition);
1144 PD.complete(Result);
1148 /// objc-protocol-refs:
1149 /// '<' identifier-list '>'
1152 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1153 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1154 bool WarnOnDeclarations,
1155 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1156 assert(Tok.is(tok::less) && "expected <");
1158 LAngleLoc = ConsumeToken(); // the "<"
1160 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1163 if (Tok.is(tok::code_completion)) {
1164 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1165 ProtocolIdents.size());
1170 if (Tok.isNot(tok::identifier)) {
1171 Diag(Tok, diag::err_expected) << tok::identifier;
1172 SkipUntil(tok::greater, StopAtSemi);
1175 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1176 Tok.getLocation()));
1177 ProtocolLocs.push_back(Tok.getLocation());
1180 if (!TryConsumeToken(tok::comma))
1185 if (ParseGreaterThanInTemplateList(EndLoc, /*ConsumeLastToken=*/true))
1188 // Convert the list of protocols identifiers into a list of protocol decls.
1189 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1190 &ProtocolIdents[0], ProtocolIdents.size(),
1195 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1196 /// in a decl-specifier-seq, starting at the '<'.
1197 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1198 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1199 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1200 SourceLocation LAngleLoc, EndProtoLoc;
1201 SmallVector<Decl *, 8> ProtocolDecl;
1202 SmallVector<SourceLocation, 8> ProtocolLocs;
1203 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1204 LAngleLoc, EndProtoLoc);
1205 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1206 ProtocolLocs.data(), LAngleLoc);
1207 if (EndProtoLoc.isValid())
1208 DS.SetRangeEnd(EndProtoLoc);
1212 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1213 BalancedDelimiterTracker &T,
1214 SmallVectorImpl<Decl *> &AllIvarDecls,
1215 bool RBraceMissing) {
1219 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1220 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1221 Actions.ActOnObjCContainerFinishDefinition();
1222 // Call ActOnFields() even if we don't have any decls. This is useful
1223 // for code rewriting tools that need to be aware of the empty list.
1224 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1226 T.getOpenLocation(), T.getCloseLocation(), nullptr);
1229 /// objc-class-instance-variables:
1230 /// '{' objc-instance-variable-decl-list[opt] '}'
1232 /// objc-instance-variable-decl-list:
1233 /// objc-visibility-spec
1234 /// objc-instance-variable-decl ';'
1236 /// objc-instance-variable-decl-list objc-visibility-spec
1237 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1238 /// objc-instance-variable-decl-list ';'
1240 /// objc-visibility-spec:
1244 /// @package [OBJC2]
1246 /// objc-instance-variable-decl:
1247 /// struct-declaration
1249 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1250 tok::ObjCKeywordKind visibility,
1251 SourceLocation atLoc) {
1252 assert(Tok.is(tok::l_brace) && "expected {");
1253 SmallVector<Decl *, 32> AllIvarDecls;
1255 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1256 ObjCDeclContextSwitch ObjCDC(*this);
1258 BalancedDelimiterTracker T(*this, tok::l_brace);
1260 // While we still have something to read, read the instance variables.
1261 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1262 // Each iteration of this loop reads one objc-instance-variable-decl.
1264 // Check for extraneous top-level semicolon.
1265 if (Tok.is(tok::semi)) {
1266 ConsumeExtraSemi(InstanceVariableList);
1270 // Set the default visibility to private.
1271 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1272 if (Tok.is(tok::code_completion)) {
1273 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1274 return cutOffParsing();
1277 switch (Tok.getObjCKeywordID()) {
1278 case tok::objc_private:
1279 case tok::objc_public:
1280 case tok::objc_protected:
1281 case tok::objc_package:
1282 visibility = Tok.getObjCKeywordID();
1287 Diag(Tok, diag::err_objc_unexpected_atend);
1288 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1289 Tok.setKind(tok::at);
1292 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1293 T, AllIvarDecls, true);
1297 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1302 if (Tok.is(tok::code_completion)) {
1303 Actions.CodeCompleteOrdinaryName(getCurScope(),
1304 Sema::PCC_ObjCInstanceVariableList);
1305 return cutOffParsing();
1308 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1309 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1310 // Install the declarator into the interface decl.
1311 Decl *Field = Actions.ActOnIvar(
1312 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1313 FD.BitfieldSize, visibility);
1314 Actions.ActOnObjCContainerFinishDefinition();
1316 AllIvarDecls.push_back(Field);
1320 // Parse all the comma separated declarators.
1321 ParsingDeclSpec DS(*this);
1322 ParseStructDeclaration(DS, ObjCIvarCallback);
1324 if (Tok.is(tok::semi)) {
1327 Diag(Tok, diag::err_expected_semi_decl_list);
1328 // Skip to end of block or statement
1329 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1332 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1333 T, AllIvarDecls, false);
1337 /// objc-protocol-declaration:
1338 /// objc-protocol-definition
1339 /// objc-protocol-forward-reference
1341 /// objc-protocol-definition:
1342 /// \@protocol identifier
1343 /// objc-protocol-refs[opt]
1344 /// objc-interface-decl-list
1347 /// objc-protocol-forward-reference:
1348 /// \@protocol identifier-list ';'
1350 /// "\@protocol identifier ;" should be resolved as "\@protocol
1351 /// identifier-list ;": objc-interface-decl-list may not start with a
1352 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1353 Parser::DeclGroupPtrTy
1354 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1355 ParsedAttributes &attrs) {
1356 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1357 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1358 ConsumeToken(); // the "protocol" identifier
1360 if (Tok.is(tok::code_completion)) {
1361 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1363 return DeclGroupPtrTy();
1366 MaybeSkipAttributes(tok::objc_protocol);
1368 if (Tok.isNot(tok::identifier)) {
1369 Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name.
1370 return DeclGroupPtrTy();
1372 // Save the protocol name, then consume it.
1373 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1374 SourceLocation nameLoc = ConsumeToken();
1376 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
1377 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1378 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1382 CheckNestedObjCContexts(AtLoc);
1384 if (Tok.is(tok::comma)) { // list of forward declarations.
1385 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1386 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1388 // Parse the list of forward declarations.
1390 ConsumeToken(); // the ','
1391 if (Tok.isNot(tok::identifier)) {
1392 Diag(Tok, diag::err_expected) << tok::identifier;
1393 SkipUntil(tok::semi);
1394 return DeclGroupPtrTy();
1396 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1397 Tok.getLocation()));
1398 ConsumeToken(); // the identifier
1400 if (Tok.isNot(tok::comma))
1404 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
1405 return DeclGroupPtrTy();
1407 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1409 ProtocolRefs.size(),
1413 // Last, and definitely not least, parse a protocol declaration.
1414 SourceLocation LAngleLoc, EndProtoLoc;
1416 SmallVector<Decl *, 8> ProtocolRefs;
1417 SmallVector<SourceLocation, 8> ProtocolLocs;
1418 if (Tok.is(tok::less) &&
1419 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1420 LAngleLoc, EndProtoLoc))
1421 return DeclGroupPtrTy();
1424 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1425 ProtocolRefs.data(),
1426 ProtocolRefs.size(),
1427 ProtocolLocs.data(),
1428 EndProtoLoc, attrs.getList());
1430 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1431 return Actions.ConvertDeclToDeclGroup(ProtoType);
1434 /// objc-implementation:
1435 /// objc-class-implementation-prologue
1436 /// objc-category-implementation-prologue
1438 /// objc-class-implementation-prologue:
1439 /// @implementation identifier objc-superclass[opt]
1440 /// objc-class-instance-variables[opt]
1442 /// objc-category-implementation-prologue:
1443 /// @implementation identifier ( identifier )
1444 Parser::DeclGroupPtrTy
1445 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1446 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1447 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1448 CheckNestedObjCContexts(AtLoc);
1449 ConsumeToken(); // the "implementation" identifier
1451 // Code completion after '@implementation'.
1452 if (Tok.is(tok::code_completion)) {
1453 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1455 return DeclGroupPtrTy();
1458 MaybeSkipAttributes(tok::objc_implementation);
1460 if (Tok.isNot(tok::identifier)) {
1461 Diag(Tok, diag::err_expected)
1462 << tok::identifier; // missing class or category name.
1463 return DeclGroupPtrTy();
1465 // We have a class or category name - consume it.
1466 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1467 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1468 Decl *ObjCImpDecl = nullptr;
1470 if (Tok.is(tok::l_paren)) {
1471 // we have a category implementation.
1473 SourceLocation categoryLoc, rparenLoc;
1474 IdentifierInfo *categoryId = nullptr;
1476 if (Tok.is(tok::code_completion)) {
1477 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1479 return DeclGroupPtrTy();
1482 if (Tok.is(tok::identifier)) {
1483 categoryId = Tok.getIdentifierInfo();
1484 categoryLoc = ConsumeToken();
1486 Diag(Tok, diag::err_expected)
1487 << tok::identifier; // missing category name.
1488 return DeclGroupPtrTy();
1490 if (Tok.isNot(tok::r_paren)) {
1491 Diag(Tok, diag::err_expected) << tok::r_paren;
1492 SkipUntil(tok::r_paren); // don't stop at ';'
1493 return DeclGroupPtrTy();
1495 rparenLoc = ConsumeParen();
1496 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1497 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1498 AttributeFactory attr;
1500 (void)ParseObjCProtocolQualifiers(DS);
1502 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1503 AtLoc, nameId, nameLoc, categoryId,
1507 // We have a class implementation
1508 SourceLocation superClassLoc;
1509 IdentifierInfo *superClassId = nullptr;
1510 if (TryConsumeToken(tok::colon)) {
1511 // We have a super class
1512 if (Tok.isNot(tok::identifier)) {
1513 Diag(Tok, diag::err_expected)
1514 << tok::identifier; // missing super class name.
1515 return DeclGroupPtrTy();
1517 superClassId = Tok.getIdentifierInfo();
1518 superClassLoc = ConsumeToken(); // Consume super class name
1520 ObjCImpDecl = Actions.ActOnStartClassImplementation(
1521 AtLoc, nameId, nameLoc,
1522 superClassId, superClassLoc);
1524 if (Tok.is(tok::l_brace)) // we have ivars
1525 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
1526 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1527 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1529 AttributeFactory attr;
1531 (void)ParseObjCProtocolQualifiers(DS);
1534 assert(ObjCImpDecl);
1536 SmallVector<Decl *, 8> DeclsInGroup;
1539 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1540 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
1541 ParsedAttributesWithRange attrs(AttrFactory);
1542 MaybeParseCXX11Attributes(attrs);
1543 MaybeParseMicrosoftAttributes(attrs);
1544 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1545 DeclGroupRef DG = DGP.get();
1546 DeclsInGroup.append(DG.begin(), DG.end());
1551 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1554 Parser::DeclGroupPtrTy
1555 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1556 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1557 "ParseObjCAtEndDeclaration(): Expected @end");
1558 ConsumeToken(); // the "end" identifier
1559 if (CurParsedObjCImpl)
1560 CurParsedObjCImpl->finish(atEnd);
1562 // missing @implementation
1563 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1564 return DeclGroupPtrTy();
1567 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1569 finish(P.Tok.getLocation());
1570 if (P.isEofOrEom()) {
1571 P.Diag(P.Tok, diag::err_objc_missing_end)
1572 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1573 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1574 << Sema::OCK_Implementation;
1577 P.CurParsedObjCImpl = nullptr;
1578 assert(LateParsedObjCMethods.empty());
1581 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1583 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1584 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1585 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1588 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1591 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1592 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1593 false/*c-functions*/);
1595 /// \brief Clear and free the cached objc methods.
1596 for (LateParsedObjCMethodContainer::iterator
1597 I = LateParsedObjCMethods.begin(),
1598 E = LateParsedObjCMethods.end(); I != E; ++I)
1600 LateParsedObjCMethods.clear();
1605 /// compatibility-alias-decl:
1606 /// @compatibility_alias alias-name class-name ';'
1608 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1609 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1610 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1611 ConsumeToken(); // consume compatibility_alias
1612 if (Tok.isNot(tok::identifier)) {
1613 Diag(Tok, diag::err_expected) << tok::identifier;
1616 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1617 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1618 if (Tok.isNot(tok::identifier)) {
1619 Diag(Tok, diag::err_expected) << tok::identifier;
1622 IdentifierInfo *classId = Tok.getIdentifierInfo();
1623 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1624 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
1625 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1629 /// property-synthesis:
1630 /// @synthesize property-ivar-list ';'
1632 /// property-ivar-list:
1634 /// property-ivar-list ',' property-ivar
1638 /// identifier '=' identifier
1640 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1641 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1642 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
1643 ConsumeToken(); // consume synthesize
1646 if (Tok.is(tok::code_completion)) {
1647 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1652 if (Tok.isNot(tok::identifier)) {
1653 Diag(Tok, diag::err_synthesized_property_name);
1654 SkipUntil(tok::semi);
1658 IdentifierInfo *propertyIvar = nullptr;
1659 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1660 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1661 SourceLocation propertyIvarLoc;
1662 if (TryConsumeToken(tok::equal)) {
1663 // property '=' ivar-name
1664 if (Tok.is(tok::code_completion)) {
1665 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1670 if (Tok.isNot(tok::identifier)) {
1671 Diag(Tok, diag::err_expected) << tok::identifier;
1674 propertyIvar = Tok.getIdentifierInfo();
1675 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1677 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1678 propertyId, propertyIvar, propertyIvarLoc);
1679 if (Tok.isNot(tok::comma))
1681 ConsumeToken(); // consume ','
1683 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
1687 /// property-dynamic:
1688 /// @dynamic property-list
1692 /// property-list ',' identifier
1694 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1695 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1696 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1697 ConsumeToken(); // consume dynamic
1699 if (Tok.is(tok::code_completion)) {
1700 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1705 if (Tok.isNot(tok::identifier)) {
1706 Diag(Tok, diag::err_expected) << tok::identifier;
1707 SkipUntil(tok::semi);
1711 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1712 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1713 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1714 propertyId, nullptr, SourceLocation());
1716 if (Tok.isNot(tok::comma))
1718 ConsumeToken(); // consume ','
1720 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
1724 /// objc-throw-statement:
1725 /// throw expression[opt];
1727 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1729 ConsumeToken(); // consume throw
1730 if (Tok.isNot(tok::semi)) {
1731 Res = ParseExpression();
1732 if (Res.isInvalid()) {
1733 SkipUntil(tok::semi);
1738 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
1739 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
1742 /// objc-synchronized-statement:
1743 /// @synchronized '(' expression ')' compound-statement
1746 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1747 ConsumeToken(); // consume synchronized
1748 if (Tok.isNot(tok::l_paren)) {
1749 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1753 // The operand is surrounded with parentheses.
1754 ConsumeParen(); // '('
1755 ExprResult operand(ParseExpression());
1757 if (Tok.is(tok::r_paren)) {
1758 ConsumeParen(); // ')'
1760 if (!operand.isInvalid())
1761 Diag(Tok, diag::err_expected) << tok::r_paren;
1763 // Skip forward until we see a left brace, but don't consume it.
1764 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1767 // Require a compound statement.
1768 if (Tok.isNot(tok::l_brace)) {
1769 if (!operand.isInvalid())
1770 Diag(Tok, diag::err_expected) << tok::l_brace;
1774 // Check the @synchronized operand now.
1775 if (!operand.isInvalid())
1776 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
1778 // Parse the compound statement within a new scope.
1779 ParseScope bodyScope(this, Scope::DeclScope);
1780 StmtResult body(ParseCompoundStatementBody());
1783 // If there was a semantic or parse error earlier with the
1784 // operand, fail now.
1785 if (operand.isInvalid())
1788 if (body.isInvalid())
1789 body = Actions.ActOnNullStmt(Tok.getLocation());
1791 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1794 /// objc-try-catch-statement:
1795 /// @try compound-statement objc-catch-list[opt]
1796 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1798 /// objc-catch-list:
1799 /// @catch ( parameter-declaration ) compound-statement
1800 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1801 /// catch-parameter-declaration:
1802 /// parameter-declaration
1805 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1806 bool catch_or_finally_seen = false;
1808 ConsumeToken(); // consume try
1809 if (Tok.isNot(tok::l_brace)) {
1810 Diag(Tok, diag::err_expected) << tok::l_brace;
1813 StmtVector CatchStmts;
1814 StmtResult FinallyStmt;
1815 ParseScope TryScope(this, Scope::DeclScope);
1816 StmtResult TryBody(ParseCompoundStatementBody());
1818 if (TryBody.isInvalid())
1819 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1821 while (Tok.is(tok::at)) {
1822 // At this point, we need to lookahead to determine if this @ is the start
1823 // of an @catch or @finally. We don't want to consume the @ token if this
1824 // is an @try or @encode or something else.
1825 Token AfterAt = GetLookAheadToken(1);
1826 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1827 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1830 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1831 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1832 Decl *FirstPart = nullptr;
1833 ConsumeToken(); // consume catch
1834 if (Tok.is(tok::l_paren)) {
1836 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1837 if (Tok.isNot(tok::ellipsis)) {
1838 DeclSpec DS(AttrFactory);
1839 ParseDeclarationSpecifiers(DS);
1840 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1841 ParseDeclarator(ParmDecl);
1843 // Inform the actions module about the declarator, so it
1844 // gets added to the current scope.
1845 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1847 ConsumeToken(); // consume '...'
1849 SourceLocation RParenLoc;
1851 if (Tok.is(tok::r_paren))
1852 RParenLoc = ConsumeParen();
1853 else // Skip over garbage, until we get to ')'. Eat the ')'.
1854 SkipUntil(tok::r_paren, StopAtSemi);
1856 StmtResult CatchBody(true);
1857 if (Tok.is(tok::l_brace))
1858 CatchBody = ParseCompoundStatementBody();
1860 Diag(Tok, diag::err_expected) << tok::l_brace;
1861 if (CatchBody.isInvalid())
1862 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1864 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1868 if (!Catch.isInvalid())
1869 CatchStmts.push_back(Catch.get());
1872 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1876 catch_or_finally_seen = true;
1878 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1879 ConsumeToken(); // consume finally
1880 ParseScope FinallyScope(this, Scope::DeclScope);
1882 StmtResult FinallyBody(true);
1883 if (Tok.is(tok::l_brace))
1884 FinallyBody = ParseCompoundStatementBody();
1886 Diag(Tok, diag::err_expected) << tok::l_brace;
1887 if (FinallyBody.isInvalid())
1888 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1889 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1891 catch_or_finally_seen = true;
1895 if (!catch_or_finally_seen) {
1896 Diag(atLoc, diag::err_missing_catch_finally);
1900 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
1905 /// objc-autoreleasepool-statement:
1906 /// @autoreleasepool compound-statement
1909 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1910 ConsumeToken(); // consume autoreleasepool
1911 if (Tok.isNot(tok::l_brace)) {
1912 Diag(Tok, diag::err_expected) << tok::l_brace;
1915 // Enter a scope to hold everything within the compound stmt. Compound
1916 // statements can always hold declarations.
1917 ParseScope BodyScope(this, Scope::DeclScope);
1919 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1922 if (AutoreleasePoolBody.isInvalid())
1923 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1924 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1925 AutoreleasePoolBody.get());
1928 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1929 /// for later parsing.
1930 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1931 LexedMethod* LM = new LexedMethod(this, MDecl);
1932 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1933 CachedTokens &Toks = LM->Toks;
1934 // Begin by storing the '{' or 'try' or ':' token.
1935 Toks.push_back(Tok);
1936 if (Tok.is(tok::kw_try)) {
1938 if (Tok.is(tok::colon)) {
1939 Toks.push_back(Tok);
1941 while (Tok.isNot(tok::l_brace)) {
1942 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1943 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1946 Toks.push_back(Tok); // also store '{'
1948 else if (Tok.is(tok::colon)) {
1950 while (Tok.isNot(tok::l_brace)) {
1951 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1952 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1954 Toks.push_back(Tok); // also store '{'
1957 // Consume everything up to (and including) the matching right brace.
1958 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1959 while (Tok.is(tok::kw_catch)) {
1960 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1961 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1965 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1967 Decl *Parser::ParseObjCMethodDefinition() {
1968 Decl *MDecl = ParseObjCMethodPrototype();
1970 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1971 "parsing Objective-C method");
1973 // parse optional ';'
1974 if (Tok.is(tok::semi)) {
1975 if (CurParsedObjCImpl) {
1976 Diag(Tok, diag::warn_semicolon_before_method_body)
1977 << FixItHint::CreateRemoval(Tok.getLocation());
1982 // We should have an opening brace now.
1983 if (Tok.isNot(tok::l_brace)) {
1984 Diag(Tok, diag::err_expected_method_body);
1986 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1987 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1989 // If we didn't find the '{', bail out.
1990 if (Tok.isNot(tok::l_brace))
1996 SkipUntil(tok::r_brace);
2000 // Allow the rest of sema to find private method decl implementations.
2001 Actions.AddAnyMethodToGlobalPool(MDecl);
2002 assert (CurParsedObjCImpl
2003 && "ParseObjCMethodDefinition - Method out of @implementation");
2004 // Consume the tokens and store them for later parsing.
2005 StashAwayMethodOrFunctionBodyTokens(MDecl);
2009 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2010 if (Tok.is(tok::code_completion)) {
2011 Actions.CodeCompleteObjCAtStatement(getCurScope());
2016 if (Tok.isObjCAtKeyword(tok::objc_try))
2017 return ParseObjCTryStmt(AtLoc);
2019 if (Tok.isObjCAtKeyword(tok::objc_throw))
2020 return ParseObjCThrowStmt(AtLoc);
2022 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2023 return ParseObjCSynchronizedStmt(AtLoc);
2025 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2026 return ParseObjCAutoreleasePoolStmt(AtLoc);
2028 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2029 getLangOpts().DebuggerSupport) {
2030 SkipUntil(tok::semi);
2031 return Actions.ActOnNullStmt(Tok.getLocation());
2034 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2035 if (Res.isInvalid()) {
2036 // If the expression is invalid, skip ahead to the next semicolon. Not
2037 // doing this opens us up to the possibility of infinite loops if
2038 // ParseExpression does not consume any tokens.
2039 SkipUntil(tok::semi);
2043 // Otherwise, eat the semicolon.
2044 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2045 return Actions.ActOnExprStmt(Res);
2048 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2049 switch (Tok.getKind()) {
2050 case tok::code_completion:
2051 Actions.CodeCompleteObjCAtExpression(getCurScope());
2057 tok::TokenKind Kind = Tok.getKind();
2058 SourceLocation OpLoc = ConsumeToken();
2060 if (!Tok.is(tok::numeric_constant)) {
2061 const char *Symbol = nullptr;
2063 case tok::minus: Symbol = "-"; break;
2064 case tok::plus: Symbol = "+"; break;
2065 default: llvm_unreachable("missing unary operator case");
2067 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2072 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2073 if (Lit.isInvalid()) {
2076 ConsumeToken(); // Consume the literal token.
2078 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2079 if (Lit.isInvalid())
2082 return ParsePostfixExpressionSuffix(
2083 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2086 case tok::string_literal: // primary-expression: string-literal
2087 case tok::wide_string_literal:
2088 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2090 case tok::char_constant:
2091 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2093 case tok::numeric_constant:
2094 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2096 case tok::kw_true: // Objective-C++, etc.
2097 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2098 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2099 case tok::kw_false: // Objective-C++, etc.
2100 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2101 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2104 // Objective-C array literal
2105 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2108 // Objective-C dictionary literal
2109 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2112 // Objective-C boxed expression
2113 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2116 if (Tok.getIdentifierInfo() == nullptr)
2117 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2119 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2120 case tok::objc_encode:
2121 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2122 case tok::objc_protocol:
2123 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2124 case tok::objc_selector:
2125 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2127 const char *str = nullptr;
2128 if (GetLookAheadToken(1).is(tok::l_brace)) {
2129 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2132 : (ch == 'f' ? "finally"
2133 : (ch == 'a' ? "autoreleasepool" : nullptr));
2136 SourceLocation kwLoc = Tok.getLocation();
2137 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2138 FixItHint::CreateReplacement(kwLoc, str));
2141 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2147 /// \brief Parse the receiver of an Objective-C++ message send.
2149 /// This routine parses the receiver of a message send in
2150 /// Objective-C++ either as a type or as an expression. Note that this
2151 /// routine must not be called to parse a send to 'super', since it
2152 /// has no way to return such a result.
2154 /// \param IsExpr Whether the receiver was parsed as an expression.
2156 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2157 /// IsExpr is true), the parsed expression. If the receiver was parsed
2158 /// as a type (\c IsExpr is false), the parsed type.
2160 /// \returns True if an error occurred during parsing or semantic
2161 /// analysis, in which case the arguments do not have valid
2162 /// values. Otherwise, returns false for a successful parse.
2164 /// objc-receiver: [C++]
2165 /// 'super' [not parsed here]
2167 /// simple-type-specifier
2168 /// typename-specifier
2169 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2170 InMessageExpressionRAIIObject InMessage(*this, true);
2172 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2173 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2174 TryAnnotateTypeOrScopeToken();
2176 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2179 // Make sure any typos in the receiver are corrected or diagnosed, so that
2180 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2181 // only the things that are valid ObjC receivers?
2182 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2183 if (Receiver.isInvalid())
2187 TypeOrExpr = Receiver.get();
2192 // typename-specifier
2193 // simple-type-specifier
2194 // expression (that starts with one of the above)
2195 DeclSpec DS(AttrFactory);
2196 ParseCXXSimpleTypeSpecifier(DS);
2198 if (Tok.is(tok::l_paren)) {
2199 // If we see an opening parentheses at this point, we are
2200 // actually parsing an expression that starts with a
2201 // function-style cast, e.g.,
2203 // postfix-expression:
2204 // simple-type-specifier ( expression-list [opt] )
2205 // typename-specifier ( expression-list [opt] )
2207 // Parse the remainder of this case, then the (optional)
2208 // postfix-expression suffix, followed by the (optional)
2209 // right-hand side of the binary expression. We have an
2211 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2212 if (!Receiver.isInvalid())
2213 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2214 if (!Receiver.isInvalid())
2215 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2216 if (Receiver.isInvalid())
2220 TypeOrExpr = Receiver.get();
2224 // We have a class message. Turn the simple-type-specifier or
2225 // typename-specifier we parsed into a type and parse the
2226 // remainder of the class message.
2227 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2228 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2229 if (Type.isInvalid())
2233 TypeOrExpr = Type.get().getAsOpaquePtr();
2237 /// \brief Determine whether the parser is currently referring to a an
2238 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2240 /// This routine will only return true for a subset of valid message-send
2242 bool Parser::isSimpleObjCMessageExpression() {
2243 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2244 "Incorrect start for isSimpleObjCMessageExpression");
2245 return GetLookAheadToken(1).is(tok::identifier) &&
2246 GetLookAheadToken(2).is(tok::identifier);
2249 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2250 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2251 InMessageExpression)
2257 if (Tok.is(tok::annot_typename))
2258 Type = getTypeAnnotation(Tok);
2259 else if (Tok.is(tok::identifier))
2260 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2265 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2266 const Token &AfterNext = GetLookAheadToken(2);
2267 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2268 if (Tok.is(tok::identifier))
2269 TryAnnotateTypeOrScopeToken();
2271 return Tok.is(tok::annot_typename);
2278 /// objc-message-expr:
2279 /// '[' objc-receiver objc-message-args ']'
2281 /// objc-receiver: [C]
2287 ExprResult Parser::ParseObjCMessageExpression() {
2288 assert(Tok.is(tok::l_square) && "'[' expected");
2289 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2291 if (Tok.is(tok::code_completion)) {
2292 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2297 InMessageExpressionRAIIObject InMessage(*this, true);
2299 if (getLangOpts().CPlusPlus) {
2300 // We completely separate the C and C++ cases because C++ requires
2301 // more complicated (read: slower) parsing.
2303 // Handle send to super.
2304 // FIXME: This doesn't benefit from the same typo-correction we
2305 // get in Objective-C.
2306 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2307 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2308 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2309 ParsedType(), nullptr);
2311 // Parse the receiver, which is either a type or an expression.
2313 void *TypeOrExpr = nullptr;
2314 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2315 SkipUntil(tok::r_square, StopAtSemi);
2320 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2322 static_cast<Expr*>(TypeOrExpr));
2324 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2325 ParsedType::getFromOpaquePtr(TypeOrExpr),
2329 if (Tok.is(tok::identifier)) {
2330 IdentifierInfo *Name = Tok.getIdentifierInfo();
2331 SourceLocation NameLoc = Tok.getLocation();
2332 ParsedType ReceiverType;
2333 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2334 Name == Ident_super,
2335 NextToken().is(tok::period),
2337 case Sema::ObjCSuperMessage:
2338 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2339 ParsedType(), nullptr);
2341 case Sema::ObjCClassMessage:
2342 if (!ReceiverType) {
2343 SkipUntil(tok::r_square, StopAtSemi);
2347 ConsumeToken(); // the type name
2349 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2350 ReceiverType, nullptr);
2352 case Sema::ObjCInstanceMessage:
2353 // Fall through to parse an expression.
2358 // Otherwise, an arbitrary expression can be the receiver of a send.
2359 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2360 if (Res.isInvalid()) {
2361 SkipUntil(tok::r_square, StopAtSemi);
2365 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2366 ParsedType(), Res.get());
2369 /// \brief Parse the remainder of an Objective-C message following the
2370 /// '[' objc-receiver.
2372 /// This routine handles sends to super, class messages (sent to a
2373 /// class name), and instance messages (sent to an object), and the
2374 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2375 /// ReceiverExpr, respectively. Only one of these parameters may have
2378 /// \param LBracLoc The location of the opening '['.
2380 /// \param SuperLoc If this is a send to 'super', the location of the
2381 /// 'super' keyword that indicates a send to the superclass.
2383 /// \param ReceiverType If this is a class message, the type of the
2384 /// class we are sending a message to.
2386 /// \param ReceiverExpr If this is an instance message, the expression
2387 /// used to compute the receiver object.
2389 /// objc-message-args:
2391 /// objc-keywordarg-list
2393 /// objc-keywordarg-list:
2395 /// objc-keywordarg-list objc-keywordarg
2397 /// objc-keywordarg:
2398 /// selector-name[opt] ':' objc-keywordexpr
2400 /// objc-keywordexpr:
2401 /// nonempty-expr-list
2403 /// nonempty-expr-list:
2404 /// assignment-expression
2405 /// nonempty-expr-list , assignment-expression
2408 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2409 SourceLocation SuperLoc,
2410 ParsedType ReceiverType,
2411 Expr *ReceiverExpr) {
2412 InMessageExpressionRAIIObject InMessage(*this, true);
2414 if (Tok.is(tok::code_completion)) {
2415 if (SuperLoc.isValid())
2416 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
2418 else if (ReceiverType)
2419 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
2422 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2428 // Parse objc-selector
2430 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2432 SmallVector<IdentifierInfo *, 12> KeyIdents;
2433 SmallVector<SourceLocation, 12> KeyLocs;
2434 ExprVector KeyExprs;
2436 if (Tok.is(tok::colon)) {
2438 // Each iteration parses a single keyword argument.
2439 KeyIdents.push_back(selIdent);
2440 KeyLocs.push_back(Loc);
2442 if (ExpectAndConsume(tok::colon)) {
2443 // We must manually skip to a ']', otherwise the expression skipper will
2444 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2445 // the enclosing expression.
2446 SkipUntil(tok::r_square, StopAtSemi);
2450 /// Parse the expression after ':'
2452 if (Tok.is(tok::code_completion)) {
2453 if (SuperLoc.isValid())
2454 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2456 /*AtArgumentEpression=*/true);
2457 else if (ReceiverType)
2458 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2460 /*AtArgumentEpression=*/true);
2462 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2464 /*AtArgumentEpression=*/true);
2471 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2472 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2473 Expr = ParseBraceInitializer();
2475 Expr = ParseAssignmentExpression();
2477 ExprResult Res(Expr);
2478 if (Res.isInvalid()) {
2479 // We must manually skip to a ']', otherwise the expression skipper will
2480 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2481 // the enclosing expression.
2482 SkipUntil(tok::r_square, StopAtSemi);
2486 // We have a valid expression.
2487 KeyExprs.push_back(Res.get());
2489 // Code completion after each argument.
2490 if (Tok.is(tok::code_completion)) {
2491 if (SuperLoc.isValid())
2492 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2494 /*AtArgumentEpression=*/false);
2495 else if (ReceiverType)
2496 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2498 /*AtArgumentEpression=*/false);
2500 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2502 /*AtArgumentEpression=*/false);
2507 // Check for another keyword selector.
2508 selIdent = ParseObjCSelectorPiece(Loc);
2509 if (!selIdent && Tok.isNot(tok::colon))
2511 // We have a selector or a colon, continue parsing.
2513 // Parse the, optional, argument list, comma separated.
2514 while (Tok.is(tok::comma)) {
2515 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2516 /// Parse the expression after ','
2517 ExprResult Res(ParseAssignmentExpression());
2518 if (Tok.is(tok::colon))
2519 Res = Actions.CorrectDelayedTyposInExpr(Res);
2520 if (Res.isInvalid()) {
2521 if (Tok.is(tok::colon)) {
2522 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2523 FixItHint::CreateRemoval(commaLoc);
2525 // We must manually skip to a ']', otherwise the expression skipper will
2526 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2527 // the enclosing expression.
2528 SkipUntil(tok::r_square, StopAtSemi);
2532 // We have a valid expression.
2533 KeyExprs.push_back(Res.get());
2535 } else if (!selIdent) {
2536 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
2538 // We must manually skip to a ']', otherwise the expression skipper will
2539 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2540 // the enclosing expression.
2541 SkipUntil(tok::r_square, StopAtSemi);
2545 if (Tok.isNot(tok::r_square)) {
2546 Diag(Tok, diag::err_expected)
2547 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
2548 // We must manually skip to a ']', otherwise the expression skipper will
2549 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2550 // the enclosing expression.
2551 SkipUntil(tok::r_square, StopAtSemi);
2555 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2557 unsigned nKeys = KeyIdents.size();
2559 KeyIdents.push_back(selIdent);
2560 KeyLocs.push_back(Loc);
2562 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2564 if (SuperLoc.isValid())
2565 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2566 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2567 else if (ReceiverType)
2568 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2569 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2570 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2571 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2574 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2575 ExprResult Res(ParseStringLiteralExpression());
2576 if (Res.isInvalid()) return Res;
2578 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2579 // expressions. At this point, we know that the only valid thing that starts
2580 // with '@' is an @"".
2581 SmallVector<SourceLocation, 4> AtLocs;
2582 ExprVector AtStrings;
2583 AtLocs.push_back(AtLoc);
2584 AtStrings.push_back(Res.get());
2586 while (Tok.is(tok::at)) {
2587 AtLocs.push_back(ConsumeToken()); // eat the @.
2589 // Invalid unless there is a string literal.
2590 if (!isTokenStringLiteral())
2591 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2593 ExprResult Lit(ParseStringLiteralExpression());
2594 if (Lit.isInvalid())
2597 AtStrings.push_back(Lit.get());
2600 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2604 /// ParseObjCBooleanLiteral -
2605 /// objc-scalar-literal : '@' boolean-keyword
2607 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2609 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2611 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2612 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2615 /// ParseObjCCharacterLiteral -
2616 /// objc-scalar-literal : '@' character-literal
2618 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2619 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2620 if (Lit.isInvalid()) {
2623 ConsumeToken(); // Consume the literal token.
2624 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
2627 /// ParseObjCNumericLiteral -
2628 /// objc-scalar-literal : '@' scalar-literal
2630 /// scalar-literal : | numeric-constant /* any numeric constant. */
2632 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2633 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2634 if (Lit.isInvalid()) {
2637 ConsumeToken(); // Consume the literal token.
2638 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
2641 /// ParseObjCBoxedExpr -
2642 /// objc-box-expression:
2643 /// @( assignment-expression )
2645 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2646 if (Tok.isNot(tok::l_paren))
2647 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2649 BalancedDelimiterTracker T(*this, tok::l_paren);
2651 ExprResult ValueExpr(ParseAssignmentExpression());
2652 if (T.consumeClose())
2655 if (ValueExpr.isInvalid())
2658 // Wrap the sub-expression in a parenthesized expression, to distinguish
2659 // a boxed expression from a literal.
2660 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2661 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
2662 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2666 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2667 ExprVector ElementExprs; // array elements.
2668 ConsumeBracket(); // consume the l_square.
2670 while (Tok.isNot(tok::r_square)) {
2671 // Parse list of array element expressions (all must be id types).
2672 ExprResult Res(ParseAssignmentExpression());
2673 if (Res.isInvalid()) {
2674 // We must manually skip to a ']', otherwise the expression skipper will
2675 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2676 // the enclosing expression.
2677 SkipUntil(tok::r_square, StopAtSemi);
2681 // Parse the ellipsis that indicates a pack expansion.
2682 if (Tok.is(tok::ellipsis))
2683 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2684 if (Res.isInvalid())
2687 ElementExprs.push_back(Res.get());
2689 if (Tok.is(tok::comma))
2690 ConsumeToken(); // Eat the ','.
2691 else if (Tok.isNot(tok::r_square))
2692 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
2695 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2696 MultiExprArg Args(ElementExprs);
2697 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
2700 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2701 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2702 ConsumeBrace(); // consume the l_square.
2703 while (Tok.isNot(tok::r_brace)) {
2704 // Parse the comma separated key : value expressions.
2707 ColonProtectionRAIIObject X(*this);
2708 KeyExpr = ParseAssignmentExpression();
2709 if (KeyExpr.isInvalid()) {
2710 // We must manually skip to a '}', otherwise the expression skipper will
2711 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2712 // the enclosing expression.
2713 SkipUntil(tok::r_brace, StopAtSemi);
2718 if (ExpectAndConsume(tok::colon)) {
2719 SkipUntil(tok::r_brace, StopAtSemi);
2723 ExprResult ValueExpr(ParseAssignmentExpression());
2724 if (ValueExpr.isInvalid()) {
2725 // We must manually skip to a '}', otherwise the expression skipper will
2726 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2727 // the enclosing expression.
2728 SkipUntil(tok::r_brace, StopAtSemi);
2732 // Parse the ellipsis that designates this as a pack expansion.
2733 SourceLocation EllipsisLoc;
2734 if (getLangOpts().CPlusPlus)
2735 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2737 // We have a valid expression. Collect it in a vector so we can
2738 // build the argument list.
2739 ObjCDictionaryElement Element = {
2740 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
2742 Elements.push_back(Element);
2744 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
2745 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
2748 SourceLocation EndLoc = ConsumeBrace();
2750 // Create the ObjCDictionaryLiteral.
2751 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2752 Elements.data(), Elements.size());
2755 /// objc-encode-expression:
2756 /// \@encode ( type-name )
2758 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2759 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2761 SourceLocation EncLoc = ConsumeToken();
2763 if (Tok.isNot(tok::l_paren))
2764 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2766 BalancedDelimiterTracker T(*this, tok::l_paren);
2769 TypeResult Ty = ParseTypeName();
2776 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
2777 Ty.get(), T.getCloseLocation());
2780 /// objc-protocol-expression
2781 /// \@protocol ( protocol-name )
2783 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2784 SourceLocation ProtoLoc = ConsumeToken();
2786 if (Tok.isNot(tok::l_paren))
2787 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2789 BalancedDelimiterTracker T(*this, tok::l_paren);
2792 if (Tok.isNot(tok::identifier))
2793 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
2795 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2796 SourceLocation ProtoIdLoc = ConsumeToken();
2800 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2801 T.getOpenLocation(), ProtoIdLoc,
2802 T.getCloseLocation());
2805 /// objc-selector-expression
2806 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
2807 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2808 SourceLocation SelectorLoc = ConsumeToken();
2810 if (Tok.isNot(tok::l_paren))
2811 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2813 SmallVector<IdentifierInfo *, 12> KeyIdents;
2814 SourceLocation sLoc;
2816 BalancedDelimiterTracker T(*this, tok::l_paren);
2818 bool HasOptionalParen = Tok.is(tok::l_paren);
2819 if (HasOptionalParen)
2822 if (Tok.is(tok::code_completion)) {
2823 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2828 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2829 if (!SelIdent && // missing selector name.
2830 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2831 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
2833 KeyIdents.push_back(SelIdent);
2835 unsigned nColons = 0;
2836 if (Tok.isNot(tok::r_paren)) {
2838 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
2840 KeyIdents.push_back(nullptr);
2841 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
2845 if (Tok.is(tok::r_paren))
2848 if (Tok.is(tok::code_completion)) {
2849 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2854 // Check for another keyword selector.
2856 SelIdent = ParseObjCSelectorPiece(Loc);
2857 KeyIdents.push_back(SelIdent);
2858 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2862 if (HasOptionalParen && Tok.is(tok::r_paren))
2863 ConsumeParen(); // ')'
2865 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2866 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2867 T.getOpenLocation(),
2868 T.getCloseLocation(),
2872 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2873 // MCDecl might be null due to error in method or c-function prototype, etc.
2874 Decl *MCDecl = LM.D;
2875 bool skip = MCDecl &&
2876 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2877 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2881 // Save the current token position.
2882 SourceLocation OrigLoc = Tok.getLocation();
2884 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2885 // Append the current token at the end of the new token stream so that it
2886 // doesn't get lost.
2887 LM.Toks.push_back(Tok);
2888 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2890 // Consume the previously pushed token.
2891 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
2893 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2894 Tok.is(tok::colon)) &&
2895 "Inline objective-c method not starting with '{' or 'try' or ':'");
2896 // Enter a scope for the method or c-function body.
2897 ParseScope BodyScope(this,
2899 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2900 : Scope::FnScope|Scope::DeclScope);
2902 // Tell the actions module that we have entered a method or c-function definition
2903 // with the specified Declarator for the method/function.
2905 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2907 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2908 if (Tok.is(tok::kw_try))
2909 ParseFunctionTryBlock(MCDecl, BodyScope);
2911 if (Tok.is(tok::colon))
2912 ParseConstructorInitializer(MCDecl);
2913 ParseFunctionStatementBody(MCDecl, BodyScope);
2916 if (Tok.getLocation() != OrigLoc) {
2917 // Due to parsing error, we either went over the cached tokens or
2918 // there are still cached tokens left. If it's the latter case skip the
2920 // Since this is an uncommon situation that should be avoided, use the
2921 // expensive isBeforeInTranslationUnit call.
2922 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2924 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))