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/ParseDiagnostic.h"
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/PrettyDeclStackTrace.h"
19 #include "clang/Sema/Scope.h"
20 #include "llvm/ADT/SmallVector.h"
21 using namespace clang;
24 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
25 /// external-declaration: [C99 6.9]
26 /// [OBJC] objc-class-definition
27 /// [OBJC] objc-class-declaration
28 /// [OBJC] objc-alias-declaration
29 /// [OBJC] objc-protocol-definition
30 /// [OBJC] objc-method-definition
32 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() {
33 SourceLocation AtLoc = ConsumeToken(); // the "@"
35 if (Tok.is(tok::code_completion)) {
36 Actions.CodeCompleteObjCAtDirective(getCurScope());
38 return DeclGroupPtrTy();
42 switch (Tok.getObjCKeywordID()) {
44 return ParseObjCAtClassDeclaration(AtLoc);
46 case tok::objc_interface: {
47 ParsedAttributes attrs(AttrFactory);
48 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
51 case tok::objc_protocol: {
52 ParsedAttributes attrs(AttrFactory);
53 SingleDecl = ParseObjCAtProtocolDeclaration(AtLoc, attrs);
56 case tok::objc_implementation:
57 SingleDecl = ParseObjCAtImplementationDeclaration(AtLoc);
60 return ParseObjCAtEndDeclaration(AtLoc);
62 case tok::objc_compatibility_alias:
63 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
65 case tok::objc_synthesize:
66 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
68 case tok::objc_dynamic:
69 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
72 Diag(AtLoc, diag::err_unexpected_at);
77 return Actions.ConvertDeclToDeclGroup(SingleDecl);
81 /// objc-class-declaration:
82 /// '@' 'class' identifier-list ';'
84 Parser::DeclGroupPtrTy
85 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
86 ConsumeToken(); // the identifier "class"
87 SmallVector<IdentifierInfo *, 8> ClassNames;
88 SmallVector<SourceLocation, 8> ClassLocs;
92 if (Tok.isNot(tok::identifier)) {
93 Diag(Tok, diag::err_expected_ident);
95 return Actions.ConvertDeclToDeclGroup(0);
97 ClassNames.push_back(Tok.getIdentifierInfo());
98 ClassLocs.push_back(Tok.getLocation());
101 if (Tok.isNot(tok::comma))
108 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
109 return Actions.ConvertDeclToDeclGroup(0);
111 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
118 /// objc-class-interface-attributes[opt] objc-class-interface
119 /// objc-category-interface
121 /// objc-class-interface:
122 /// '@' 'interface' identifier objc-superclass[opt]
123 /// objc-protocol-refs[opt]
124 /// objc-class-instance-variables[opt]
125 /// objc-interface-decl-list
128 /// objc-category-interface:
129 /// '@' 'interface' identifier '(' identifier[opt] ')'
130 /// objc-protocol-refs[opt]
131 /// objc-interface-decl-list
137 /// objc-class-interface-attributes:
138 /// __attribute__((visibility("default")))
139 /// __attribute__((visibility("hidden")))
140 /// __attribute__((deprecated))
141 /// __attribute__((unavailable))
142 /// __attribute__((objc_exception)) - used by NSException on 64-bit
144 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
145 ParsedAttributes &attrs) {
146 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
147 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
148 ConsumeToken(); // the "interface" identifier
150 // Code completion after '@interface'.
151 if (Tok.is(tok::code_completion)) {
152 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
157 if (Tok.isNot(tok::identifier)) {
158 Diag(Tok, diag::err_expected_ident); // missing class or category name.
162 // We have a class or category name - consume it.
163 IdentifierInfo *nameId = Tok.getIdentifierInfo();
164 SourceLocation nameLoc = ConsumeToken();
165 if (Tok.is(tok::l_paren) &&
166 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
168 BalancedDelimiterTracker T(*this, tok::l_paren);
171 SourceLocation categoryLoc;
172 IdentifierInfo *categoryId = 0;
173 if (Tok.is(tok::code_completion)) {
174 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
179 // For ObjC2, the category name is optional (not an error).
180 if (Tok.is(tok::identifier)) {
181 categoryId = Tok.getIdentifierInfo();
182 categoryLoc = ConsumeToken();
184 else if (!getLang().ObjC2) {
185 Diag(Tok, diag::err_expected_ident); // missing category name.
190 if (T.getCloseLocation().isInvalid())
193 if (!attrs.empty()) { // categories don't support attributes.
194 Diag(nameLoc, diag::err_objc_no_attributes_on_category);
198 // Next, we need to check for any protocol references.
199 SourceLocation LAngleLoc, EndProtoLoc;
200 SmallVector<Decl *, 8> ProtocolRefs;
201 SmallVector<SourceLocation, 8> ProtocolLocs;
202 if (Tok.is(tok::less) &&
203 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
204 LAngleLoc, EndProtoLoc))
208 Actions.ActOnStartCategoryInterface(atLoc,
210 categoryId, categoryLoc,
216 if (Tok.is(tok::l_brace))
217 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, atLoc);
219 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
222 // Parse a class interface.
223 IdentifierInfo *superClassId = 0;
224 SourceLocation superClassLoc;
226 if (Tok.is(tok::colon)) { // a super class is specified.
229 // Code completion of superclass names.
230 if (Tok.is(tok::code_completion)) {
231 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
236 if (Tok.isNot(tok::identifier)) {
237 Diag(Tok, diag::err_expected_ident); // missing super class name.
240 superClassId = Tok.getIdentifierInfo();
241 superClassLoc = ConsumeToken();
243 // Next, we need to check for any protocol references.
244 SmallVector<Decl *, 8> ProtocolRefs;
245 SmallVector<SourceLocation, 8> ProtocolLocs;
246 SourceLocation LAngleLoc, EndProtoLoc;
247 if (Tok.is(tok::less) &&
248 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
249 LAngleLoc, EndProtoLoc))
253 Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc,
254 superClassId, superClassLoc,
255 ProtocolRefs.data(), ProtocolRefs.size(),
257 EndProtoLoc, attrs.getList());
259 if (Tok.is(tok::l_brace))
260 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, atLoc);
262 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
266 /// The Objective-C property callback. This should be defined where
267 /// it's used, but instead it's been lifted to here to support VS2005.
268 struct Parser::ObjCPropertyCallback : FieldCallback {
270 SmallVectorImpl<Decl *> &Props;
272 SourceLocation AtLoc;
273 tok::ObjCKeywordKind MethodImplKind;
275 ObjCPropertyCallback(Parser &P,
276 SmallVectorImpl<Decl *> &Props,
277 ObjCDeclSpec &OCDS, SourceLocation AtLoc,
278 tok::ObjCKeywordKind MethodImplKind) :
279 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc),
280 MethodImplKind(MethodImplKind) {
283 Decl *invoke(FieldDeclarator &FD) {
284 if (FD.D.getIdentifier() == 0) {
285 P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
286 << FD.D.getSourceRange();
289 if (FD.BitfieldSize) {
290 P.Diag(AtLoc, diag::err_objc_property_bitfield)
291 << FD.D.getSourceRange();
295 // Install the property declarator into interfaceDecl.
296 IdentifierInfo *SelName =
297 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
300 P.PP.getSelectorTable().getNullarySelector(SelName);
301 IdentifierInfo *SetterName = OCDS.getSetterName();
304 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
306 SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
307 P.PP.getSelectorTable(),
308 FD.D.getIdentifier());
309 bool isOverridingProperty = false;
311 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, FD, OCDS,
312 GetterSel, SetterSel,
313 &isOverridingProperty,
315 if (!isOverridingProperty)
316 Props.push_back(Property);
322 /// objc-interface-decl-list:
324 /// objc-interface-decl-list objc-property-decl [OBJC2]
325 /// objc-interface-decl-list objc-method-requirement [OBJC2]
326 /// objc-interface-decl-list objc-method-proto ';'
327 /// objc-interface-decl-list declaration
328 /// objc-interface-decl-list ';'
330 /// objc-method-requirement: [OBJC2]
334 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
336 SmallVector<Decl *, 32> allMethods;
337 SmallVector<Decl *, 16> allProperties;
338 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
339 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
344 // If this is a method prototype, parse it.
345 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
346 Decl *methodPrototype =
347 ParseObjCMethodPrototype(MethodImplKind, false);
348 allMethods.push_back(methodPrototype);
349 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
350 // method definitions.
351 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_method_proto,
355 if (Tok.is(tok::l_paren)) {
356 Diag(Tok, diag::err_expected_minus_or_plus);
357 ParseObjCMethodDecl(Tok.getLocation(),
359 MethodImplKind, false);
362 // Ignore excess semicolons.
363 if (Tok.is(tok::semi)) {
368 // If we got to the end of the file, exit the loop.
369 if (Tok.is(tok::eof))
372 // Code completion within an Objective-C interface.
373 if (Tok.is(tok::code_completion)) {
374 Actions.CodeCompleteOrdinaryName(getCurScope(),
375 ObjCImpDecl? Sema::PCC_ObjCImplementation
376 : Sema::PCC_ObjCInterface);
377 return cutOffParsing();
380 // If we don't have an @ directive, parse it as a function definition.
381 if (Tok.isNot(tok::at)) {
382 // The code below does not consume '}'s because it is afraid of eating the
383 // end of a namespace. Because of the way this code is structured, an
384 // erroneous r_brace would cause an infinite loop if not handled here.
385 if (Tok.is(tok::r_brace))
387 ParsedAttributes attrs(AttrFactory);
388 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
392 // Otherwise, we have an @ directive, eat the @.
393 SourceLocation AtLoc = ConsumeToken(); // the "@"
394 if (Tok.is(tok::code_completion)) {
395 Actions.CodeCompleteObjCAtDirective(getCurScope());
396 return cutOffParsing();
400 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
402 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
403 AtEnd.setBegin(AtLoc);
404 AtEnd.setEnd(Tok.getLocation());
406 } else if (DirectiveKind == tok::objc_not_keyword) {
407 Diag(Tok, diag::err_objc_unknown_at);
408 SkipUntil(tok::semi);
412 // Eat the identifier.
415 switch (DirectiveKind) {
417 // FIXME: If someone forgets an @end on a protocol, this loop will
418 // continue to eat up tons of stuff and spew lots of nonsense errors. It
419 // would probably be better to bail out if we saw an @class or @interface
420 // or something like that.
421 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
422 // Skip until we see an '@' or '}' or ';'.
423 SkipUntil(tok::r_brace, tok::at);
426 case tok::objc_implementation:
427 case tok::objc_interface:
428 Diag(Tok, diag::err_objc_missing_end);
432 case tok::objc_required:
433 case tok::objc_optional:
434 // This is only valid on protocols.
435 // FIXME: Should this check for ObjC2 being enabled?
436 if (contextKey != tok::objc_protocol)
437 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
439 MethodImplKind = DirectiveKind;
442 case tok::objc_property:
443 if (!getLang().ObjC2)
444 Diag(AtLoc, diag::err_objc_properties_require_objc2);
447 // Parse property attribute list, if any.
448 if (Tok.is(tok::l_paren))
449 ParseObjCPropertyAttribute(OCDS);
451 ObjCPropertyCallback Callback(*this, allProperties,
452 OCDS, AtLoc, MethodImplKind);
454 // Parse all the comma separated declarators.
455 DeclSpec DS(AttrFactory);
456 ParseStructDeclaration(DS, Callback);
458 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
463 // We break out of the big loop in two cases: when we see @end or when we see
464 // EOF. In the former case, eat the @end. In the later case, emit an error.
465 if (Tok.is(tok::code_completion)) {
466 Actions.CodeCompleteObjCAtDirective(getCurScope());
467 return cutOffParsing();
468 } else if (Tok.isObjCAtKeyword(tok::objc_end))
469 ConsumeToken(); // the "end" identifier
471 Diag(Tok, diag::err_objc_missing_end);
473 // Insert collected methods declarations into the @interface object.
474 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
475 Actions.ActOnAtEnd(getCurScope(), AtEnd,
476 allMethods.data(), allMethods.size(),
477 allProperties.data(), allProperties.size(),
478 allTUVariables.data(), allTUVariables.size());
481 /// Parse property attribute declarations.
483 /// property-attr-decl: '(' property-attrlist ')'
484 /// property-attrlist:
485 /// property-attribute
486 /// property-attrlist ',' property-attribute
487 /// property-attribute:
488 /// getter '=' identifier
489 /// setter '=' identifier ':'
499 /// unsafe_unretained
501 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
502 assert(Tok.getKind() == tok::l_paren);
503 BalancedDelimiterTracker T(*this, tok::l_paren);
507 if (Tok.is(tok::code_completion)) {
508 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
509 return cutOffParsing();
511 const IdentifierInfo *II = Tok.getIdentifierInfo();
513 // If this is not an identifier at all, bail out early.
519 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
521 if (II->isStr("readonly"))
522 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
523 else if (II->isStr("assign"))
524 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
525 else if (II->isStr("unsafe_unretained"))
526 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
527 else if (II->isStr("readwrite"))
528 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
529 else if (II->isStr("retain"))
530 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
531 else if (II->isStr("strong"))
532 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
533 else if (II->isStr("copy"))
534 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
535 else if (II->isStr("nonatomic"))
536 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
537 else if (II->isStr("atomic"))
538 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
539 else if (II->isStr("weak"))
540 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
541 else if (II->isStr("getter") || II->isStr("setter")) {
542 bool IsSetter = II->getNameStart()[0] == 's';
544 // getter/setter require extra treatment.
545 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
546 diag::err_objc_expected_equal_for_getter;
548 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
551 if (Tok.is(tok::code_completion)) {
553 Actions.CodeCompleteObjCPropertySetter(getCurScope());
555 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
556 return cutOffParsing();
560 SourceLocation SelLoc;
561 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
564 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
566 SkipUntil(tok::r_paren);
571 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
572 DS.setSetterName(SelIdent);
574 if (ExpectAndConsume(tok::colon,
575 diag::err_expected_colon_after_setter_name, "",
579 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
580 DS.setGetterName(SelIdent);
583 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
584 SkipUntil(tok::r_paren);
588 if (Tok.isNot(tok::comma))
597 /// objc-method-proto:
598 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
599 /// objc-class-method objc-method-decl objc-method-attributes[opt]
601 /// objc-instance-method: '-'
602 /// objc-class-method: '+'
604 /// objc-method-attributes: [OBJC2]
605 /// __attribute__((deprecated))
607 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
608 bool MethodDefinition) {
609 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
611 tok::TokenKind methodType = Tok.getKind();
612 SourceLocation mLoc = ConsumeToken();
613 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
615 // Since this rule is used for both method declarations and definitions,
616 // the caller is (optionally) responsible for consuming the ';'.
623 /// enum struct union if else while do for switch case default
624 /// break continue return goto asm sizeof typeof __alignof
625 /// unsigned long const short volatile signed restrict _Complex
626 /// in out inout bycopy byref oneway int char float double void _Bool
628 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
630 switch (Tok.getKind()) {
639 case tok::exclaimequal:
643 case tok::caretequal: {
644 std::string ThisTok(PP.getSpelling(Tok));
645 if (isalpha(ThisTok[0])) {
646 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
647 Tok.setKind(tok::identifier);
648 SelectorLoc = ConsumeToken();
654 case tok::identifier:
664 case tok::kw_const_cast:
665 case tok::kw_continue:
666 case tok::kw_default:
670 case tok::kw_dynamic_cast:
673 case tok::kw_explicit:
685 case tok::kw_mutable:
686 case tok::kw_namespace:
688 case tok::kw_operator:
689 case tok::kw_private:
690 case tok::kw_protected:
692 case tok::kw_register:
693 case tok::kw_reinterpret_cast:
694 case tok::kw_restrict:
700 case tok::kw_static_cast:
703 case tok::kw_template:
708 case tok::kw_typedef:
710 case tok::kw_typename:
713 case tok::kw_unsigned:
715 case tok::kw_virtual:
717 case tok::kw_volatile:
718 case tok::kw_wchar_t:
721 case tok::kw__Complex:
722 case tok::kw___alignof:
723 IdentifierInfo *II = Tok.getIdentifierInfo();
724 SelectorLoc = ConsumeToken();
729 /// objc-for-collection-in: 'in'
731 bool Parser::isTokIdentifier_in() const {
732 // FIXME: May have to do additional look-ahead to only allow for
733 // valid tokens following an 'in'; such as an identifier, unary operators,
735 return (getLang().ObjC2 && Tok.is(tok::identifier) &&
736 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
739 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
740 /// qualifier list and builds their bitmask representation in the input
743 /// objc-type-qualifiers:
744 /// objc-type-qualifier
745 /// objc-type-qualifiers objc-type-qualifier
747 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
748 Declarator::TheContext Context) {
749 assert(Context == Declarator::ObjCParameterContext ||
750 Context == Declarator::ObjCResultContext);
753 if (Tok.is(tok::code_completion)) {
754 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
755 Context == Declarator::ObjCParameterContext);
756 return cutOffParsing();
759 if (Tok.isNot(tok::identifier))
762 const IdentifierInfo *II = Tok.getIdentifierInfo();
763 for (unsigned i = 0; i != objc_NumQuals; ++i) {
764 if (II != ObjCTypeQuals[i])
767 ObjCDeclSpec::ObjCDeclQualifier Qual;
769 default: llvm_unreachable("Unknown decl qualifier");
770 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
771 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
772 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
773 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
774 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
775 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
777 DS.setObjCDeclQualifier(Qual);
783 // If this wasn't a recognized qualifier, bail out.
788 /// Take all the decl attributes out of the given list and add
789 /// them to the given attribute set.
790 static void takeDeclAttributes(ParsedAttributes &attrs,
791 AttributeList *list) {
793 AttributeList *cur = list;
794 list = cur->getNext();
796 if (!cur->isUsedAsTypeAttr()) {
797 // Clear out the next pointer. We're really completely
798 // destroying the internal invariants of the declarator here,
799 // but it doesn't matter because we're done with it.
806 /// takeDeclAttributes - Take all the decl attributes from the given
807 /// declarator and add them to the given list.
808 static void takeDeclAttributes(ParsedAttributes &attrs,
810 // First, take ownership of all attributes.
811 attrs.getPool().takeAllFrom(D.getAttributePool());
812 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
814 // Now actually move the attributes over.
815 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
816 takeDeclAttributes(attrs, D.getAttributes());
817 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
818 takeDeclAttributes(attrs,
819 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
823 /// '(' objc-type-qualifiers[opt] type-name ')'
824 /// '(' objc-type-qualifiers[opt] ')'
826 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
827 Declarator::TheContext context,
828 ParsedAttributes *paramAttrs) {
829 assert(context == Declarator::ObjCParameterContext ||
830 context == Declarator::ObjCResultContext);
831 assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
833 assert(Tok.is(tok::l_paren) && "expected (");
835 BalancedDelimiterTracker T(*this, tok::l_paren);
838 SourceLocation TypeStartLoc = Tok.getLocation();
839 ObjCDeclContextSwitch ObjCDC(*this);
841 // Parse type qualifiers, in, inout, etc.
842 ParseObjCTypeQualifierList(DS, context);
845 if (isTypeSpecifierQualifier()) {
846 // Parse an abstract declarator.
847 DeclSpec declSpec(AttrFactory);
848 declSpec.setObjCQualifiers(&DS);
849 ParseSpecifierQualifierList(declSpec);
850 Declarator declarator(declSpec, context);
851 ParseDeclarator(declarator);
853 // If that's not invalid, extract a type.
854 if (!declarator.isInvalidType()) {
855 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
856 if (!type.isInvalid())
859 // If we're parsing a parameter, steal all the decl attributes
860 // and add them to the decl spec.
861 if (context == Declarator::ObjCParameterContext)
862 takeDeclAttributes(*paramAttrs, declarator);
864 } else if (context == Declarator::ObjCResultContext &&
865 Tok.is(tok::identifier)) {
866 if (!Ident_instancetype)
867 Ident_instancetype = PP.getIdentifierInfo("instancetype");
869 if (Tok.getIdentifierInfo() == Ident_instancetype) {
870 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
875 if (Tok.is(tok::r_paren))
877 else if (Tok.getLocation() == TypeStartLoc) {
878 // If we didn't eat any tokens, then this isn't a type.
879 Diag(Tok, diag::err_expected_type);
880 SkipUntil(tok::r_paren);
882 // Otherwise, we found *something*, but didn't get a ')' in the right
883 // place. Emit an error then return what we have as the type.
889 /// objc-method-decl:
891 /// objc-keyword-selector objc-parmlist[opt]
892 /// objc-type-name objc-selector
893 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
895 /// objc-keyword-selector:
896 /// objc-keyword-decl
897 /// objc-keyword-selector objc-keyword-decl
899 /// objc-keyword-decl:
900 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
901 /// objc-selector ':' objc-keyword-attributes[opt] identifier
902 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
903 /// ':' objc-keyword-attributes[opt] identifier
906 /// objc-parms objc-ellipsis[opt]
909 /// objc-parms , parameter-declaration
914 /// objc-keyword-attributes: [OBJC2]
915 /// __attribute__((unused))
917 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
918 tok::TokenKind mType,
919 tok::ObjCKeywordKind MethodImplKind,
920 bool MethodDefinition) {
921 ParsingDeclRAIIObject PD(*this);
923 if (Tok.is(tok::code_completion)) {
924 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
925 /*ReturnType=*/ ParsedType());
930 // Parse the return type if present.
931 ParsedType ReturnType;
933 if (Tok.is(tok::l_paren))
934 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
936 // If attributes exist before the method, parse them.
937 ParsedAttributes methodAttrs(AttrFactory);
939 MaybeParseGNUAttributes(methodAttrs);
941 if (Tok.is(tok::code_completion)) {
942 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
948 // Now parse the selector.
949 SourceLocation selLoc;
950 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
952 // An unnamed colon is valid.
953 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
954 Diag(Tok, diag::err_expected_selector_for_method)
955 << SourceRange(mLoc, Tok.getLocation());
956 // Skip until we get a ; or {}.
957 SkipUntil(tok::r_brace);
961 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
962 if (Tok.isNot(tok::colon)) {
963 // If attributes exist after the method, parse them.
965 MaybeParseGNUAttributes(methodAttrs);
967 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
969 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
970 mType, DSRet, ReturnType,
972 CParamInfo.data(), CParamInfo.size(),
973 methodAttrs.getList(), MethodImplKind,
974 false, MethodDefinition);
979 SmallVector<IdentifierInfo *, 12> KeyIdents;
980 SmallVector<SourceLocation, 12> KeyLocs;
981 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
982 ParseScope PrototypeScope(this,
983 Scope::FunctionPrototypeScope|Scope::DeclScope);
985 AttributePool allParamAttrs(AttrFactory);
988 ParsedAttributes paramAttrs(AttrFactory);
989 Sema::ObjCArgInfo ArgInfo;
991 // Each iteration parses a single keyword argument.
992 if (Tok.isNot(tok::colon)) {
993 Diag(Tok, diag::err_expected_colon);
996 ConsumeToken(); // Eat the ':'.
998 ArgInfo.Type = ParsedType();
999 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1000 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1001 Declarator::ObjCParameterContext,
1004 // If attributes exist before the argument name, parse them.
1005 // Regardless, collect all the attributes we've parsed so far.
1006 ArgInfo.ArgAttrs = 0;
1007 if (getLang().ObjC2) {
1008 MaybeParseGNUAttributes(paramAttrs);
1009 ArgInfo.ArgAttrs = paramAttrs.getList();
1012 // Code completion for the next piece of the selector.
1013 if (Tok.is(tok::code_completion)) {
1014 KeyIdents.push_back(SelIdent);
1015 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1016 mType == tok::minus,
1017 /*AtParameterName=*/true,
1025 if (Tok.isNot(tok::identifier)) {
1026 Diag(Tok, diag::err_expected_ident); // missing argument name.
1030 ArgInfo.Name = Tok.getIdentifierInfo();
1031 ArgInfo.NameLoc = Tok.getLocation();
1032 ConsumeToken(); // Eat the identifier.
1034 ArgInfos.push_back(ArgInfo);
1035 KeyIdents.push_back(SelIdent);
1036 KeyLocs.push_back(selLoc);
1038 // Make sure the attributes persist.
1039 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1041 // Code completion for the next piece of the selector.
1042 if (Tok.is(tok::code_completion)) {
1043 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1044 mType == tok::minus,
1045 /*AtParameterName=*/false,
1053 // Check for another keyword selector.
1054 SelIdent = ParseObjCSelectorPiece(selLoc);
1055 if (!SelIdent && Tok.isNot(tok::colon))
1057 // We have a selector or a colon, continue parsing.
1060 bool isVariadic = false;
1062 // Parse the (optional) parameter list.
1063 while (Tok.is(tok::comma)) {
1065 if (Tok.is(tok::ellipsis)) {
1070 DeclSpec DS(AttrFactory);
1071 ParseDeclarationSpecifiers(DS);
1072 // Parse the declarator.
1073 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1074 ParseDeclarator(ParmDecl);
1075 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1076 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1077 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1078 ParmDecl.getIdentifierLoc(),
1084 // FIXME: Add support for optional parameter list...
1085 // If attributes exist after the method, parse them.
1086 if (getLang().ObjC2)
1087 MaybeParseGNUAttributes(methodAttrs);
1089 if (KeyIdents.size() == 0)
1092 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1095 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1096 mType, DSRet, ReturnType,
1097 KeyLocs, Sel, &ArgInfos[0],
1098 CParamInfo.data(), CParamInfo.size(),
1099 methodAttrs.getList(),
1100 MethodImplKind, isVariadic, MethodDefinition);
1102 PD.complete(Result);
1106 /// objc-protocol-refs:
1107 /// '<' identifier-list '>'
1110 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1111 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1112 bool WarnOnDeclarations,
1113 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1114 assert(Tok.is(tok::less) && "expected <");
1116 LAngleLoc = ConsumeToken(); // the "<"
1118 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1121 if (Tok.is(tok::code_completion)) {
1122 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1123 ProtocolIdents.size());
1128 if (Tok.isNot(tok::identifier)) {
1129 Diag(Tok, diag::err_expected_ident);
1130 SkipUntil(tok::greater);
1133 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1134 Tok.getLocation()));
1135 ProtocolLocs.push_back(Tok.getLocation());
1138 if (Tok.isNot(tok::comma))
1144 if (Tok.isNot(tok::greater)) {
1145 Diag(Tok, diag::err_expected_greater);
1149 EndLoc = ConsumeAnyToken();
1151 // Convert the list of protocols identifiers into a list of protocol decls.
1152 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1153 &ProtocolIdents[0], ProtocolIdents.size(),
1158 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1159 /// in a decl-specifier-seq, starting at the '<'.
1160 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1161 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1162 assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1163 SourceLocation LAngleLoc, EndProtoLoc;
1164 SmallVector<Decl *, 8> ProtocolDecl;
1165 SmallVector<SourceLocation, 8> ProtocolLocs;
1166 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1167 LAngleLoc, EndProtoLoc);
1168 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1169 ProtocolLocs.data(), LAngleLoc);
1170 if (EndProtoLoc.isValid())
1171 DS.SetRangeEnd(EndProtoLoc);
1176 /// objc-class-instance-variables:
1177 /// '{' objc-instance-variable-decl-list[opt] '}'
1179 /// objc-instance-variable-decl-list:
1180 /// objc-visibility-spec
1181 /// objc-instance-variable-decl ';'
1183 /// objc-instance-variable-decl-list objc-visibility-spec
1184 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1185 /// objc-instance-variable-decl-list ';'
1187 /// objc-visibility-spec:
1191 /// @package [OBJC2]
1193 /// objc-instance-variable-decl:
1194 /// struct-declaration
1196 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1197 tok::ObjCKeywordKind visibility,
1198 SourceLocation atLoc) {
1199 assert(Tok.is(tok::l_brace) && "expected {");
1200 SmallVector<Decl *, 32> AllIvarDecls;
1202 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1203 ObjCDeclContextSwitch ObjCDC(*this);
1205 BalancedDelimiterTracker T(*this, tok::l_brace);
1208 // While we still have something to read, read the instance variables.
1209 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1210 // Each iteration of this loop reads one objc-instance-variable-decl.
1212 // Check for extraneous top-level semicolon.
1213 if (Tok.is(tok::semi)) {
1214 Diag(Tok, diag::ext_extra_ivar_semi)
1215 << FixItHint::CreateRemoval(Tok.getLocation());
1220 // Set the default visibility to private.
1221 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1222 ConsumeToken(); // eat the @ sign
1224 if (Tok.is(tok::code_completion)) {
1225 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1226 return cutOffParsing();
1229 switch (Tok.getObjCKeywordID()) {
1230 case tok::objc_private:
1231 case tok::objc_public:
1232 case tok::objc_protected:
1233 case tok::objc_package:
1234 visibility = Tok.getObjCKeywordID();
1238 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1243 if (Tok.is(tok::code_completion)) {
1244 Actions.CodeCompleteOrdinaryName(getCurScope(),
1245 Sema::PCC_ObjCInstanceVariableList);
1246 return cutOffParsing();
1249 struct ObjCIvarCallback : FieldCallback {
1252 tok::ObjCKeywordKind visibility;
1253 SmallVectorImpl<Decl *> &AllIvarDecls;
1255 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1256 SmallVectorImpl<Decl *> &AllIvarDecls) :
1257 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1260 Decl *invoke(FieldDeclarator &FD) {
1261 P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1262 // Install the declarator into the interface decl.
1264 = P.Actions.ActOnIvar(P.getCurScope(),
1265 FD.D.getDeclSpec().getSourceRange().getBegin(),
1266 FD.D, FD.BitfieldSize, visibility);
1267 P.Actions.ActOnObjCContainerFinishDefinition();
1269 AllIvarDecls.push_back(Field);
1272 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1274 // Parse all the comma separated declarators.
1275 DeclSpec DS(AttrFactory);
1276 ParseStructDeclaration(DS, Callback);
1278 if (Tok.is(tok::semi)) {
1281 Diag(Tok, diag::err_expected_semi_decl_list);
1282 // Skip to end of block or statement
1283 SkipUntil(tok::r_brace, true, true);
1288 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1289 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1290 Actions.ActOnObjCContainerFinishDefinition();
1291 // Call ActOnFields() even if we don't have any decls. This is useful
1292 // for code rewriting tools that need to be aware of the empty list.
1293 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1295 T.getOpenLocation(), T.getCloseLocation(), 0);
1299 /// objc-protocol-declaration:
1300 /// objc-protocol-definition
1301 /// objc-protocol-forward-reference
1303 /// objc-protocol-definition:
1304 /// @protocol identifier
1305 /// objc-protocol-refs[opt]
1306 /// objc-interface-decl-list
1309 /// objc-protocol-forward-reference:
1310 /// @protocol identifier-list ';'
1312 /// "@protocol identifier ;" should be resolved as "@protocol
1313 /// identifier-list ;": objc-interface-decl-list may not start with a
1314 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1315 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1316 ParsedAttributes &attrs) {
1317 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1318 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1319 ConsumeToken(); // the "protocol" identifier
1321 if (Tok.is(tok::code_completion)) {
1322 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1327 if (Tok.isNot(tok::identifier)) {
1328 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1331 // Save the protocol name, then consume it.
1332 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1333 SourceLocation nameLoc = ConsumeToken();
1335 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1336 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1338 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1342 if (Tok.is(tok::comma)) { // list of forward declarations.
1343 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1344 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1346 // Parse the list of forward declarations.
1348 ConsumeToken(); // the ','
1349 if (Tok.isNot(tok::identifier)) {
1350 Diag(Tok, diag::err_expected_ident);
1351 SkipUntil(tok::semi);
1354 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1355 Tok.getLocation()));
1356 ConsumeToken(); // the identifier
1358 if (Tok.isNot(tok::comma))
1362 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1365 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1367 ProtocolRefs.size(),
1371 // Last, and definitely not least, parse a protocol declaration.
1372 SourceLocation LAngleLoc, EndProtoLoc;
1374 SmallVector<Decl *, 8> ProtocolRefs;
1375 SmallVector<SourceLocation, 8> ProtocolLocs;
1376 if (Tok.is(tok::less) &&
1377 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1378 LAngleLoc, EndProtoLoc))
1382 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1383 ProtocolRefs.data(),
1384 ProtocolRefs.size(),
1385 ProtocolLocs.data(),
1386 EndProtoLoc, attrs.getList());
1388 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1392 /// objc-implementation:
1393 /// objc-class-implementation-prologue
1394 /// objc-category-implementation-prologue
1396 /// objc-class-implementation-prologue:
1397 /// @implementation identifier objc-superclass[opt]
1398 /// objc-class-instance-variables[opt]
1400 /// objc-category-implementation-prologue:
1401 /// @implementation identifier ( identifier )
1402 Decl *Parser::ParseObjCAtImplementationDeclaration(
1403 SourceLocation atLoc) {
1404 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1405 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1406 ConsumeToken(); // the "implementation" identifier
1408 // Code completion after '@implementation'.
1409 if (Tok.is(tok::code_completion)) {
1410 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1415 if (Tok.isNot(tok::identifier)) {
1416 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1419 // We have a class or category name - consume it.
1420 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1421 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1423 if (Tok.is(tok::l_paren)) {
1424 // we have a category implementation.
1426 SourceLocation categoryLoc, rparenLoc;
1427 IdentifierInfo *categoryId = 0;
1429 if (Tok.is(tok::code_completion)) {
1430 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1435 if (Tok.is(tok::identifier)) {
1436 categoryId = Tok.getIdentifierInfo();
1437 categoryLoc = ConsumeToken();
1439 Diag(Tok, diag::err_expected_ident); // missing category name.
1442 if (Tok.isNot(tok::r_paren)) {
1443 Diag(Tok, diag::err_expected_rparen);
1444 SkipUntil(tok::r_paren, false); // don't stop at ';'
1447 rparenLoc = ConsumeParen();
1448 Decl *ImplCatType = Actions.ActOnStartCategoryImplementation(
1449 atLoc, nameId, nameLoc, categoryId,
1452 ObjCImpDecl = ImplCatType;
1453 PendingObjCImpDecl.push_back(ObjCImpDecl);
1456 // We have a class implementation
1457 SourceLocation superClassLoc;
1458 IdentifierInfo *superClassId = 0;
1459 if (Tok.is(tok::colon)) {
1460 // We have a super class
1462 if (Tok.isNot(tok::identifier)) {
1463 Diag(Tok, diag::err_expected_ident); // missing super class name.
1466 superClassId = Tok.getIdentifierInfo();
1467 superClassLoc = ConsumeToken(); // Consume super class name
1469 Decl *ImplClsType = Actions.ActOnStartClassImplementation(
1470 atLoc, nameId, nameLoc,
1471 superClassId, superClassLoc);
1473 if (Tok.is(tok::l_brace)) // we have ivars
1474 ParseObjCClassInstanceVariables(ImplClsType, tok::objc_private, atLoc);
1476 ObjCImpDecl = ImplClsType;
1477 PendingObjCImpDecl.push_back(ObjCImpDecl);
1481 Parser::DeclGroupPtrTy
1482 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1483 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1484 "ParseObjCAtEndDeclaration(): Expected @end");
1485 ConsumeToken(); // the "end" identifier
1486 SmallVector<Decl *, 8> DeclsInGroup;
1487 Actions.DefaultSynthesizeProperties(getCurScope(), ObjCImpDecl);
1488 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) {
1489 Decl *D = ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i]);
1490 DeclsInGroup.push_back(D);
1492 DeclsInGroup.push_back(ObjCImpDecl);
1495 Actions.ActOnAtEnd(getCurScope(), atEnd);
1496 PendingObjCImpDecl.pop_back();
1499 // missing @implementation
1500 Diag(atEnd.getBegin(), diag::err_expected_implementation);
1502 LateParsedObjCMethods.clear();
1504 return Actions.BuildDeclaratorGroup(
1505 DeclsInGroup.data(), DeclsInGroup.size(), false);
1508 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
1509 Actions.DiagnoseUseOfUnimplementedSelectors();
1510 if (PendingObjCImpDecl.empty())
1511 return Actions.ConvertDeclToDeclGroup(0);
1512 Decl *ImpDecl = PendingObjCImpDecl.pop_back_val();
1513 Actions.ActOnAtEnd(getCurScope(), SourceRange());
1514 return Actions.ConvertDeclToDeclGroup(ImpDecl);
1517 /// compatibility-alias-decl:
1518 /// @compatibility_alias alias-name class-name ';'
1520 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1521 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1522 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1523 ConsumeToken(); // consume compatibility_alias
1524 if (Tok.isNot(tok::identifier)) {
1525 Diag(Tok, diag::err_expected_ident);
1528 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1529 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1530 if (Tok.isNot(tok::identifier)) {
1531 Diag(Tok, diag::err_expected_ident);
1534 IdentifierInfo *classId = Tok.getIdentifierInfo();
1535 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1536 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1537 "@compatibility_alias");
1538 return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
1542 /// property-synthesis:
1543 /// @synthesize property-ivar-list ';'
1545 /// property-ivar-list:
1547 /// property-ivar-list ',' property-ivar
1551 /// identifier '=' identifier
1553 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1554 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1555 "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1556 ConsumeToken(); // consume synthesize
1559 if (Tok.is(tok::code_completion)) {
1560 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1565 if (Tok.isNot(tok::identifier)) {
1566 Diag(Tok, diag::err_synthesized_property_name);
1567 SkipUntil(tok::semi);
1571 IdentifierInfo *propertyIvar = 0;
1572 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1573 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1574 SourceLocation propertyIvarLoc;
1575 if (Tok.is(tok::equal)) {
1576 // property '=' ivar-name
1577 ConsumeToken(); // consume '='
1579 if (Tok.is(tok::code_completion)) {
1580 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1585 if (Tok.isNot(tok::identifier)) {
1586 Diag(Tok, diag::err_expected_ident);
1589 propertyIvar = Tok.getIdentifierInfo();
1590 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1592 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1593 propertyId, propertyIvar, propertyIvarLoc);
1594 if (Tok.isNot(tok::comma))
1596 ConsumeToken(); // consume ','
1598 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1602 /// property-dynamic:
1603 /// @dynamic property-list
1607 /// property-list ',' identifier
1609 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1610 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1611 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1612 ConsumeToken(); // consume dynamic
1614 if (Tok.is(tok::code_completion)) {
1615 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1620 if (Tok.isNot(tok::identifier)) {
1621 Diag(Tok, diag::err_expected_ident);
1622 SkipUntil(tok::semi);
1626 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1627 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1628 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1629 propertyId, 0, SourceLocation());
1631 if (Tok.isNot(tok::comma))
1633 ConsumeToken(); // consume ','
1635 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1639 /// objc-throw-statement:
1640 /// throw expression[opt];
1642 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1644 ConsumeToken(); // consume throw
1645 if (Tok.isNot(tok::semi)) {
1646 Res = ParseExpression();
1647 if (Res.isInvalid()) {
1648 SkipUntil(tok::semi);
1653 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1654 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1657 /// objc-synchronized-statement:
1658 /// @synchronized '(' expression ')' compound-statement
1661 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1662 ConsumeToken(); // consume synchronized
1663 if (Tok.isNot(tok::l_paren)) {
1664 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1668 // The operand is surrounded with parentheses.
1669 ConsumeParen(); // '('
1670 ExprResult operand(ParseExpression());
1672 if (Tok.is(tok::r_paren)) {
1673 ConsumeParen(); // ')'
1675 if (!operand.isInvalid())
1676 Diag(Tok, diag::err_expected_rparen);
1678 // Skip forward until we see a left brace, but don't consume it.
1679 SkipUntil(tok::l_brace, true, true);
1682 // Require a compound statement.
1683 if (Tok.isNot(tok::l_brace)) {
1684 if (!operand.isInvalid())
1685 Diag(Tok, diag::err_expected_lbrace);
1689 // Check the @synchronized operand now.
1690 if (!operand.isInvalid())
1691 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1693 // Parse the compound statement within a new scope.
1694 ParseScope bodyScope(this, Scope::DeclScope);
1695 StmtResult body(ParseCompoundStatementBody());
1698 // If there was a semantic or parse error earlier with the
1699 // operand, fail now.
1700 if (operand.isInvalid())
1703 if (body.isInvalid())
1704 body = Actions.ActOnNullStmt(Tok.getLocation());
1706 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1709 /// objc-try-catch-statement:
1710 /// @try compound-statement objc-catch-list[opt]
1711 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1713 /// objc-catch-list:
1714 /// @catch ( parameter-declaration ) compound-statement
1715 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1716 /// catch-parameter-declaration:
1717 /// parameter-declaration
1720 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1721 bool catch_or_finally_seen = false;
1723 ConsumeToken(); // consume try
1724 if (Tok.isNot(tok::l_brace)) {
1725 Diag(Tok, diag::err_expected_lbrace);
1728 StmtVector CatchStmts(Actions);
1729 StmtResult FinallyStmt;
1730 ParseScope TryScope(this, Scope::DeclScope);
1731 StmtResult TryBody(ParseCompoundStatementBody());
1733 if (TryBody.isInvalid())
1734 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1736 while (Tok.is(tok::at)) {
1737 // At this point, we need to lookahead to determine if this @ is the start
1738 // of an @catch or @finally. We don't want to consume the @ token if this
1739 // is an @try or @encode or something else.
1740 Token AfterAt = GetLookAheadToken(1);
1741 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1742 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1745 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1746 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1747 Decl *FirstPart = 0;
1748 ConsumeToken(); // consume catch
1749 if (Tok.is(tok::l_paren)) {
1751 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1752 if (Tok.isNot(tok::ellipsis)) {
1753 DeclSpec DS(AttrFactory);
1754 ParseDeclarationSpecifiers(DS);
1755 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1756 ParseDeclarator(ParmDecl);
1758 // Inform the actions module about the declarator, so it
1759 // gets added to the current scope.
1760 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1762 ConsumeToken(); // consume '...'
1764 SourceLocation RParenLoc;
1766 if (Tok.is(tok::r_paren))
1767 RParenLoc = ConsumeParen();
1768 else // Skip over garbage, until we get to ')'. Eat the ')'.
1769 SkipUntil(tok::r_paren, true, false);
1771 StmtResult CatchBody(true);
1772 if (Tok.is(tok::l_brace))
1773 CatchBody = ParseCompoundStatementBody();
1775 Diag(Tok, diag::err_expected_lbrace);
1776 if (CatchBody.isInvalid())
1777 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1779 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1783 if (!Catch.isInvalid())
1784 CatchStmts.push_back(Catch.release());
1787 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1791 catch_or_finally_seen = true;
1793 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1794 ConsumeToken(); // consume finally
1795 ParseScope FinallyScope(this, Scope::DeclScope);
1797 StmtResult FinallyBody(true);
1798 if (Tok.is(tok::l_brace))
1799 FinallyBody = ParseCompoundStatementBody();
1801 Diag(Tok, diag::err_expected_lbrace);
1802 if (FinallyBody.isInvalid())
1803 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1804 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1805 FinallyBody.take());
1806 catch_or_finally_seen = true;
1810 if (!catch_or_finally_seen) {
1811 Diag(atLoc, diag::err_missing_catch_finally);
1815 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1816 move_arg(CatchStmts),
1817 FinallyStmt.take());
1820 /// objc-autoreleasepool-statement:
1821 /// @autoreleasepool compound-statement
1824 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1825 ConsumeToken(); // consume autoreleasepool
1826 if (Tok.isNot(tok::l_brace)) {
1827 Diag(Tok, diag::err_expected_lbrace);
1830 // Enter a scope to hold everything within the compound stmt. Compound
1831 // statements can always hold declarations.
1832 ParseScope BodyScope(this, Scope::DeclScope);
1834 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1837 if (AutoreleasePoolBody.isInvalid())
1838 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1839 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1840 AutoreleasePoolBody.take());
1843 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1845 Decl *Parser::ParseObjCMethodDefinition() {
1846 Decl *MDecl = ParseObjCMethodPrototype();
1848 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1849 "parsing Objective-C method");
1851 // parse optional ';'
1852 if (Tok.is(tok::semi)) {
1854 Diag(Tok, diag::warn_semicolon_before_method_body)
1855 << FixItHint::CreateRemoval(Tok.getLocation());
1860 // We should have an opening brace now.
1861 if (Tok.isNot(tok::l_brace)) {
1862 Diag(Tok, diag::err_expected_method_body);
1864 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1865 SkipUntil(tok::l_brace, true, true);
1867 // If we didn't find the '{', bail out.
1868 if (Tok.isNot(tok::l_brace))
1871 // Allow the rest of sema to find private method decl implementations.
1873 Actions.AddAnyMethodToGlobalPool(MDecl);
1875 // Consume the tokens and store them for later parsing.
1876 LexedMethod* LM = new LexedMethod(this, MDecl);
1877 LateParsedObjCMethods.push_back(LM);
1878 CachedTokens &Toks = LM->Toks;
1879 // Begin by storing the '{' token.
1880 Toks.push_back(Tok);
1882 // Consume everything up to (and including) the matching right brace.
1883 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1887 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1888 if (Tok.is(tok::code_completion)) {
1889 Actions.CodeCompleteObjCAtStatement(getCurScope());
1894 if (Tok.isObjCAtKeyword(tok::objc_try))
1895 return ParseObjCTryStmt(AtLoc);
1897 if (Tok.isObjCAtKeyword(tok::objc_throw))
1898 return ParseObjCThrowStmt(AtLoc);
1900 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1901 return ParseObjCSynchronizedStmt(AtLoc);
1903 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
1904 return ParseObjCAutoreleasePoolStmt(AtLoc);
1906 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
1907 if (Res.isInvalid()) {
1908 // If the expression is invalid, skip ahead to the next semicolon. Not
1909 // doing this opens us up to the possibility of infinite loops if
1910 // ParseExpression does not consume any tokens.
1911 SkipUntil(tok::semi);
1915 // Otherwise, eat the semicolon.
1916 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1917 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
1920 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1921 switch (Tok.getKind()) {
1922 case tok::code_completion:
1923 Actions.CodeCompleteObjCAtExpression(getCurScope());
1927 case tok::string_literal: // primary-expression: string-literal
1928 case tok::wide_string_literal:
1929 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1931 if (Tok.getIdentifierInfo() == 0)
1932 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1934 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1935 case tok::objc_encode:
1936 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1937 case tok::objc_protocol:
1938 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1939 case tok::objc_selector:
1940 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1942 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1947 /// \brirg Parse the receiver of an Objective-C++ message send.
1949 /// This routine parses the receiver of a message send in
1950 /// Objective-C++ either as a type or as an expression. Note that this
1951 /// routine must not be called to parse a send to 'super', since it
1952 /// has no way to return such a result.
1954 /// \param IsExpr Whether the receiver was parsed as an expression.
1956 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
1957 /// IsExpr is true), the parsed expression. If the receiver was parsed
1958 /// as a type (\c IsExpr is false), the parsed type.
1960 /// \returns True if an error occurred during parsing or semantic
1961 /// analysis, in which case the arguments do not have valid
1962 /// values. Otherwise, returns false for a successful parse.
1964 /// objc-receiver: [C++]
1965 /// 'super' [not parsed here]
1967 /// simple-type-specifier
1968 /// typename-specifier
1969 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
1970 InMessageExpressionRAIIObject InMessage(*this, true);
1972 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1973 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
1974 TryAnnotateTypeOrScopeToken();
1976 if (!isCXXSimpleTypeSpecifier()) {
1979 ExprResult Receiver = ParseExpression();
1980 if (Receiver.isInvalid())
1984 TypeOrExpr = Receiver.take();
1989 // typename-specifier
1990 // simple-type-specifier
1991 // expression (that starts with one of the above)
1992 DeclSpec DS(AttrFactory);
1993 ParseCXXSimpleTypeSpecifier(DS);
1995 if (Tok.is(tok::l_paren)) {
1996 // If we see an opening parentheses at this point, we are
1997 // actually parsing an expression that starts with a
1998 // function-style cast, e.g.,
2000 // postfix-expression:
2001 // simple-type-specifier ( expression-list [opt] )
2002 // typename-specifier ( expression-list [opt] )
2004 // Parse the remainder of this case, then the (optional)
2005 // postfix-expression suffix, followed by the (optional)
2006 // right-hand side of the binary expression. We have an
2008 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2009 if (!Receiver.isInvalid())
2010 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
2011 if (!Receiver.isInvalid())
2012 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
2013 if (Receiver.isInvalid())
2017 TypeOrExpr = Receiver.take();
2021 // We have a class message. Turn the simple-type-specifier or
2022 // typename-specifier we parsed into a type and parse the
2023 // remainder of the class message.
2024 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2025 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2026 if (Type.isInvalid())
2030 TypeOrExpr = Type.get().getAsOpaquePtr();
2034 /// \brief Determine whether the parser is currently referring to a an
2035 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2037 /// This routine will only return true for a subset of valid message-send
2039 bool Parser::isSimpleObjCMessageExpression() {
2040 assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
2041 "Incorrect start for isSimpleObjCMessageExpression");
2042 return GetLookAheadToken(1).is(tok::identifier) &&
2043 GetLookAheadToken(2).is(tok::identifier);
2046 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2047 if (!getLang().ObjC1 || !NextToken().is(tok::identifier) ||
2048 InMessageExpression)
2054 if (Tok.is(tok::annot_typename))
2055 Type = getTypeAnnotation(Tok);
2056 else if (Tok.is(tok::identifier))
2057 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2062 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2063 const Token &AfterNext = GetLookAheadToken(2);
2064 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2065 if (Tok.is(tok::identifier))
2066 TryAnnotateTypeOrScopeToken();
2068 return Tok.is(tok::annot_typename);
2075 /// objc-message-expr:
2076 /// '[' objc-receiver objc-message-args ']'
2078 /// objc-receiver: [C]
2084 ExprResult Parser::ParseObjCMessageExpression() {
2085 assert(Tok.is(tok::l_square) && "'[' expected");
2086 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2088 if (Tok.is(tok::code_completion)) {
2089 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2094 InMessageExpressionRAIIObject InMessage(*this, true);
2096 if (getLang().CPlusPlus) {
2097 // We completely separate the C and C++ cases because C++ requires
2098 // more complicated (read: slower) parsing.
2100 // Handle send to super.
2101 // FIXME: This doesn't benefit from the same typo-correction we
2102 // get in Objective-C.
2103 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2104 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2105 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2108 // Parse the receiver, which is either a type or an expression.
2110 void *TypeOrExpr = NULL;
2111 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2112 SkipUntil(tok::r_square);
2117 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2119 static_cast<Expr*>(TypeOrExpr));
2121 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2122 ParsedType::getFromOpaquePtr(TypeOrExpr),
2126 if (Tok.is(tok::identifier)) {
2127 IdentifierInfo *Name = Tok.getIdentifierInfo();
2128 SourceLocation NameLoc = Tok.getLocation();
2129 ParsedType ReceiverType;
2130 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2131 Name == Ident_super,
2132 NextToken().is(tok::period),
2134 case Sema::ObjCSuperMessage:
2135 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2138 case Sema::ObjCClassMessage:
2139 if (!ReceiverType) {
2140 SkipUntil(tok::r_square);
2144 ConsumeToken(); // the type name
2146 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2149 case Sema::ObjCInstanceMessage:
2150 // Fall through to parse an expression.
2155 // Otherwise, an arbitrary expression can be the receiver of a send.
2156 ExprResult Res(ParseExpression());
2157 if (Res.isInvalid()) {
2158 SkipUntil(tok::r_square);
2162 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2163 ParsedType(), Res.take());
2166 /// \brief Parse the remainder of an Objective-C message following the
2167 /// '[' objc-receiver.
2169 /// This routine handles sends to super, class messages (sent to a
2170 /// class name), and instance messages (sent to an object), and the
2171 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2172 /// ReceiverExpr, respectively. Only one of these parameters may have
2175 /// \param LBracLoc The location of the opening '['.
2177 /// \param SuperLoc If this is a send to 'super', the location of the
2178 /// 'super' keyword that indicates a send to the superclass.
2180 /// \param ReceiverType If this is a class message, the type of the
2181 /// class we are sending a message to.
2183 /// \param ReceiverExpr If this is an instance message, the expression
2184 /// used to compute the receiver object.
2186 /// objc-message-args:
2188 /// objc-keywordarg-list
2190 /// objc-keywordarg-list:
2192 /// objc-keywordarg-list objc-keywordarg
2194 /// objc-keywordarg:
2195 /// selector-name[opt] ':' objc-keywordexpr
2197 /// objc-keywordexpr:
2198 /// nonempty-expr-list
2200 /// nonempty-expr-list:
2201 /// assignment-expression
2202 /// nonempty-expr-list , assignment-expression
2205 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2206 SourceLocation SuperLoc,
2207 ParsedType ReceiverType,
2208 ExprArg ReceiverExpr) {
2209 InMessageExpressionRAIIObject InMessage(*this, true);
2211 if (Tok.is(tok::code_completion)) {
2212 if (SuperLoc.isValid())
2213 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2215 else if (ReceiverType)
2216 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2219 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2225 // Parse objc-selector
2227 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2229 SmallVector<IdentifierInfo *, 12> KeyIdents;
2230 SmallVector<SourceLocation, 12> KeyLocs;
2231 ExprVector KeyExprs(Actions);
2233 if (Tok.is(tok::colon)) {
2235 // Each iteration parses a single keyword argument.
2236 KeyIdents.push_back(selIdent);
2237 KeyLocs.push_back(Loc);
2239 if (Tok.isNot(tok::colon)) {
2240 Diag(Tok, diag::err_expected_colon);
2241 // We must manually skip to a ']', otherwise the expression skipper will
2242 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2243 // the enclosing expression.
2244 SkipUntil(tok::r_square);
2248 ConsumeToken(); // Eat the ':'.
2249 /// Parse the expression after ':'
2251 if (Tok.is(tok::code_completion)) {
2252 if (SuperLoc.isValid())
2253 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2256 /*AtArgumentEpression=*/true);
2257 else if (ReceiverType)
2258 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2261 /*AtArgumentEpression=*/true);
2263 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2266 /*AtArgumentEpression=*/true);
2272 ExprResult Res(ParseAssignmentExpression());
2273 if (Res.isInvalid()) {
2274 // We must manually skip to a ']', otherwise the expression skipper will
2275 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2276 // the enclosing expression.
2277 SkipUntil(tok::r_square);
2281 // We have a valid expression.
2282 KeyExprs.push_back(Res.release());
2284 // Code completion after each argument.
2285 if (Tok.is(tok::code_completion)) {
2286 if (SuperLoc.isValid())
2287 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2290 /*AtArgumentEpression=*/false);
2291 else if (ReceiverType)
2292 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2295 /*AtArgumentEpression=*/false);
2297 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2300 /*AtArgumentEpression=*/false);
2305 // Check for another keyword selector.
2306 selIdent = ParseObjCSelectorPiece(Loc);
2307 if (!selIdent && Tok.isNot(tok::colon))
2309 // We have a selector or a colon, continue parsing.
2311 // Parse the, optional, argument list, comma separated.
2312 while (Tok.is(tok::comma)) {
2313 ConsumeToken(); // Eat the ','.
2314 /// Parse the expression after ','
2315 ExprResult Res(ParseAssignmentExpression());
2316 if (Res.isInvalid()) {
2317 // We must manually skip to a ']', otherwise the expression skipper will
2318 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2319 // the enclosing expression.
2320 SkipUntil(tok::r_square);
2324 // We have a valid expression.
2325 KeyExprs.push_back(Res.release());
2327 } else if (!selIdent) {
2328 Diag(Tok, diag::err_expected_ident); // missing selector name.
2330 // We must manually skip to a ']', otherwise the expression skipper will
2331 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2332 // the enclosing expression.
2333 SkipUntil(tok::r_square);
2337 if (Tok.isNot(tok::r_square)) {
2338 if (Tok.is(tok::identifier))
2339 Diag(Tok, diag::err_expected_colon);
2341 Diag(Tok, diag::err_expected_rsquare);
2342 // We must manually skip to a ']', otherwise the expression skipper will
2343 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2344 // the enclosing expression.
2345 SkipUntil(tok::r_square);
2349 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2351 unsigned nKeys = KeyIdents.size();
2353 KeyIdents.push_back(selIdent);
2354 KeyLocs.push_back(Loc);
2356 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2358 if (SuperLoc.isValid())
2359 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2360 LBracLoc, KeyLocs, RBracLoc,
2361 MultiExprArg(Actions,
2364 else if (ReceiverType)
2365 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2366 LBracLoc, KeyLocs, RBracLoc,
2367 MultiExprArg(Actions,
2370 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2371 LBracLoc, KeyLocs, RBracLoc,
2372 MultiExprArg(Actions,
2377 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2378 ExprResult Res(ParseStringLiteralExpression());
2379 if (Res.isInvalid()) return move(Res);
2381 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2382 // expressions. At this point, we know that the only valid thing that starts
2383 // with '@' is an @"".
2384 SmallVector<SourceLocation, 4> AtLocs;
2385 ExprVector AtStrings(Actions);
2386 AtLocs.push_back(AtLoc);
2387 AtStrings.push_back(Res.release());
2389 while (Tok.is(tok::at)) {
2390 AtLocs.push_back(ConsumeToken()); // eat the @.
2392 // Invalid unless there is a string literal.
2393 if (!isTokenStringLiteral())
2394 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2396 ExprResult Lit(ParseStringLiteralExpression());
2397 if (Lit.isInvalid())
2400 AtStrings.push_back(Lit.release());
2403 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2407 /// objc-encode-expression:
2408 /// @encode ( type-name )
2410 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2411 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2413 SourceLocation EncLoc = ConsumeToken();
2415 if (Tok.isNot(tok::l_paren))
2416 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2418 BalancedDelimiterTracker T(*this, tok::l_paren);
2421 TypeResult Ty = ParseTypeName();
2428 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc,
2429 T.getOpenLocation(), Ty.get(),
2430 T.getCloseLocation()));
2433 /// objc-protocol-expression
2434 /// @protocol ( protocol-name )
2436 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2437 SourceLocation ProtoLoc = ConsumeToken();
2439 if (Tok.isNot(tok::l_paren))
2440 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2442 BalancedDelimiterTracker T(*this, tok::l_paren);
2445 if (Tok.isNot(tok::identifier))
2446 return ExprError(Diag(Tok, diag::err_expected_ident));
2448 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2453 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2454 T.getOpenLocation(),
2455 T.getCloseLocation()));
2458 /// objc-selector-expression
2459 /// @selector '(' objc-keyword-selector ')'
2460 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2461 SourceLocation SelectorLoc = ConsumeToken();
2463 if (Tok.isNot(tok::l_paren))
2464 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2466 SmallVector<IdentifierInfo *, 12> KeyIdents;
2467 SourceLocation sLoc;
2469 BalancedDelimiterTracker T(*this, tok::l_paren);
2472 if (Tok.is(tok::code_completion)) {
2473 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2479 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2480 if (!SelIdent && // missing selector name.
2481 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2482 return ExprError(Diag(Tok, diag::err_expected_ident));
2484 KeyIdents.push_back(SelIdent);
2485 unsigned nColons = 0;
2486 if (Tok.isNot(tok::r_paren)) {
2488 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2490 KeyIdents.push_back(0);
2491 } else if (Tok.isNot(tok::colon))
2492 return ExprError(Diag(Tok, diag::err_expected_colon));
2495 ConsumeToken(); // Eat the ':' or '::'.
2496 if (Tok.is(tok::r_paren))
2499 if (Tok.is(tok::code_completion)) {
2500 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2506 // Check for another keyword selector.
2508 SelIdent = ParseObjCSelectorPiece(Loc);
2509 KeyIdents.push_back(SelIdent);
2510 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2515 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2516 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2517 T.getOpenLocation(),
2518 T.getCloseLocation()));
2521 Decl *Parser::ParseLexedObjCMethodDefs(LexedMethod &LM) {
2523 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2524 // Append the current token at the end of the new token stream so that it
2525 // doesn't get lost.
2526 LM.Toks.push_back(Tok);
2527 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2529 // MDecl might be null due to error in method prototype, etc.
2531 // Consume the previously pushed token.
2534 assert(Tok.is(tok::l_brace) && "Inline objective-c method not starting with '{'");
2535 SourceLocation BraceLoc = Tok.getLocation();
2536 // Enter a scope for the method body.
2537 ParseScope BodyScope(this,
2538 Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
2540 // Tell the actions module that we have entered a method definition with the
2541 // specified Declarator for the method.
2542 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
2544 if (PP.isCodeCompletionEnabled()) {
2545 if (trySkippingFunctionBodyForCodeCompletion()) {
2547 return Actions.ActOnFinishFunctionBody(MDecl, 0);
2551 StmtResult FnBody(ParseCompoundStatementBody());
2553 // If the function body could not be parsed, make a bogus compoundstmt.
2554 if (FnBody.isInvalid())
2555 FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
2556 MultiStmtArg(Actions), false);
2558 // Leave the function body scope.
2561 return Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());