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);
45 case tok::objc_interface: {
46 ParsedAttributes attrs(AttrFactory);
47 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
50 case tok::objc_protocol: {
51 ParsedAttributes attrs(AttrFactory);
52 return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
54 case tok::objc_implementation:
55 return ParseObjCAtImplementationDeclaration(AtLoc);
57 return ParseObjCAtEndDeclaration(AtLoc);
58 case tok::objc_compatibility_alias:
59 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
61 case tok::objc_synthesize:
62 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
64 case tok::objc_dynamic:
65 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
67 case tok::objc___experimental_modules_import:
68 if (getLangOpts().Modules)
69 return ParseModuleImport(AtLoc);
74 Diag(AtLoc, diag::err_unexpected_at);
79 return Actions.ConvertDeclToDeclGroup(SingleDecl);
83 /// objc-class-declaration:
84 /// '@' 'class' identifier-list ';'
86 Parser::DeclGroupPtrTy
87 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
88 ConsumeToken(); // the identifier "class"
89 SmallVector<IdentifierInfo *, 8> ClassNames;
90 SmallVector<SourceLocation, 8> ClassLocs;
94 if (Tok.isNot(tok::identifier)) {
95 Diag(Tok, diag::err_expected_ident);
97 return Actions.ConvertDeclToDeclGroup(0);
99 ClassNames.push_back(Tok.getIdentifierInfo());
100 ClassLocs.push_back(Tok.getLocation());
103 if (Tok.isNot(tok::comma))
110 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
111 return Actions.ConvertDeclToDeclGroup(0);
113 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
118 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
120 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
121 if (ock == Sema::OCK_None)
124 Decl *Decl = Actions.getObjCDeclContext();
125 if (CurParsedObjCImpl) {
126 CurParsedObjCImpl->finish(AtLoc);
128 Actions.ActOnAtEnd(getCurScope(), AtLoc);
130 Diag(AtLoc, diag::err_objc_missing_end)
131 << FixItHint::CreateInsertion(AtLoc, "@end\n");
133 Diag(Decl->getLocStart(), diag::note_objc_container_start)
139 /// objc-class-interface-attributes[opt] objc-class-interface
140 /// objc-category-interface
142 /// objc-class-interface:
143 /// '@' 'interface' identifier objc-superclass[opt]
144 /// objc-protocol-refs[opt]
145 /// objc-class-instance-variables[opt]
146 /// objc-interface-decl-list
149 /// objc-category-interface:
150 /// '@' 'interface' identifier '(' identifier[opt] ')'
151 /// objc-protocol-refs[opt]
152 /// objc-interface-decl-list
158 /// objc-class-interface-attributes:
159 /// __attribute__((visibility("default")))
160 /// __attribute__((visibility("hidden")))
161 /// __attribute__((deprecated))
162 /// __attribute__((unavailable))
163 /// __attribute__((objc_exception)) - used by NSException on 64-bit
164 /// __attribute__((objc_root_class))
166 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
167 ParsedAttributes &attrs) {
168 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
169 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
170 CheckNestedObjCContexts(AtLoc);
171 ConsumeToken(); // the "interface" identifier
173 // Code completion after '@interface'.
174 if (Tok.is(tok::code_completion)) {
175 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
180 if (Tok.isNot(tok::identifier)) {
181 Diag(Tok, diag::err_expected_ident); // missing class or category name.
185 // We have a class or category name - consume it.
186 IdentifierInfo *nameId = Tok.getIdentifierInfo();
187 SourceLocation nameLoc = ConsumeToken();
188 if (Tok.is(tok::l_paren) &&
189 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
191 BalancedDelimiterTracker T(*this, tok::l_paren);
194 SourceLocation categoryLoc;
195 IdentifierInfo *categoryId = 0;
196 if (Tok.is(tok::code_completion)) {
197 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
202 // For ObjC2, the category name is optional (not an error).
203 if (Tok.is(tok::identifier)) {
204 categoryId = Tok.getIdentifierInfo();
205 categoryLoc = ConsumeToken();
207 else if (!getLangOpts().ObjC2) {
208 Diag(Tok, diag::err_expected_ident); // missing category name.
213 if (T.getCloseLocation().isInvalid())
216 if (!attrs.empty()) { // categories don't support attributes.
217 Diag(nameLoc, diag::err_objc_no_attributes_on_category);
221 // Next, we need to check for any protocol references.
222 SourceLocation LAngleLoc, EndProtoLoc;
223 SmallVector<Decl *, 8> ProtocolRefs;
224 SmallVector<SourceLocation, 8> ProtocolLocs;
225 if (Tok.is(tok::less) &&
226 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
227 LAngleLoc, EndProtoLoc))
231 Actions.ActOnStartCategoryInterface(AtLoc,
233 categoryId, categoryLoc,
239 if (Tok.is(tok::l_brace))
240 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
242 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
245 // Parse a class interface.
246 IdentifierInfo *superClassId = 0;
247 SourceLocation superClassLoc;
249 if (Tok.is(tok::colon)) { // a super class is specified.
252 // Code completion of superclass names.
253 if (Tok.is(tok::code_completion)) {
254 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
259 if (Tok.isNot(tok::identifier)) {
260 Diag(Tok, diag::err_expected_ident); // missing super class name.
263 superClassId = Tok.getIdentifierInfo();
264 superClassLoc = ConsumeToken();
266 // Next, we need to check for any protocol references.
267 SmallVector<Decl *, 8> ProtocolRefs;
268 SmallVector<SourceLocation, 8> ProtocolLocs;
269 SourceLocation LAngleLoc, EndProtoLoc;
270 if (Tok.is(tok::less) &&
271 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
272 LAngleLoc, EndProtoLoc))
276 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
277 superClassId, superClassLoc,
278 ProtocolRefs.data(), ProtocolRefs.size(),
280 EndProtoLoc, attrs.getList());
282 if (Tok.is(tok::l_brace))
283 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
285 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
289 /// The Objective-C property callback. This should be defined where
290 /// it's used, but instead it's been lifted to here to support VS2005.
291 struct Parser::ObjCPropertyCallback : FieldCallback {
293 virtual void anchor();
296 SmallVectorImpl<Decl *> &Props;
298 SourceLocation AtLoc;
299 SourceLocation LParenLoc;
300 tok::ObjCKeywordKind MethodImplKind;
302 ObjCPropertyCallback(Parser &P,
303 SmallVectorImpl<Decl *> &Props,
304 ObjCDeclSpec &OCDS, SourceLocation AtLoc,
305 SourceLocation LParenLoc,
306 tok::ObjCKeywordKind MethodImplKind) :
307 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
308 MethodImplKind(MethodImplKind) {
311 void invoke(ParsingFieldDeclarator &FD) {
312 if (FD.D.getIdentifier() == 0) {
313 P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
314 << FD.D.getSourceRange();
317 if (FD.BitfieldSize) {
318 P.Diag(AtLoc, diag::err_objc_property_bitfield)
319 << FD.D.getSourceRange();
323 // Install the property declarator into interfaceDecl.
324 IdentifierInfo *SelName =
325 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
328 P.PP.getSelectorTable().getNullarySelector(SelName);
329 IdentifierInfo *SetterName = OCDS.getSetterName();
332 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
334 SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
335 P.PP.getSelectorTable(),
336 FD.D.getIdentifier());
337 bool isOverridingProperty = false;
339 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
341 GetterSel, SetterSel,
342 &isOverridingProperty,
344 if (!isOverridingProperty)
345 Props.push_back(Property);
347 FD.complete(Property);
351 void Parser::ObjCPropertyCallback::anchor() {
354 /// objc-interface-decl-list:
356 /// objc-interface-decl-list objc-property-decl [OBJC2]
357 /// objc-interface-decl-list objc-method-requirement [OBJC2]
358 /// objc-interface-decl-list objc-method-proto ';'
359 /// objc-interface-decl-list declaration
360 /// objc-interface-decl-list ';'
362 /// objc-method-requirement: [OBJC2]
366 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
368 SmallVector<Decl *, 32> allMethods;
369 SmallVector<Decl *, 16> allProperties;
370 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
371 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
376 // If this is a method prototype, parse it.
377 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
378 if (Decl *methodPrototype =
379 ParseObjCMethodPrototype(MethodImplKind, false))
380 allMethods.push_back(methodPrototype);
381 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
382 // method definitions.
383 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
384 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
385 SkipUntil(tok::at, /*StopAtSemi=*/true, /*DontConsume=*/true);
386 if (Tok.is(tok::semi))
391 if (Tok.is(tok::l_paren)) {
392 Diag(Tok, diag::err_expected_minus_or_plus);
393 ParseObjCMethodDecl(Tok.getLocation(),
395 MethodImplKind, false);
398 // Ignore excess semicolons.
399 if (Tok.is(tok::semi)) {
404 // If we got to the end of the file, exit the loop.
405 if (Tok.is(tok::eof))
408 // Code completion within an Objective-C interface.
409 if (Tok.is(tok::code_completion)) {
410 Actions.CodeCompleteOrdinaryName(getCurScope(),
411 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
412 : Sema::PCC_ObjCInterface);
413 return cutOffParsing();
416 // If we don't have an @ directive, parse it as a function definition.
417 if (Tok.isNot(tok::at)) {
418 // The code below does not consume '}'s because it is afraid of eating the
419 // end of a namespace. Because of the way this code is structured, an
420 // erroneous r_brace would cause an infinite loop if not handled here.
421 if (Tok.is(tok::r_brace))
423 ParsedAttributesWithRange attrs(AttrFactory);
424 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
428 // Otherwise, we have an @ directive, eat the @.
429 SourceLocation AtLoc = ConsumeToken(); // the "@"
430 if (Tok.is(tok::code_completion)) {
431 Actions.CodeCompleteObjCAtDirective(getCurScope());
432 return cutOffParsing();
435 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
437 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
438 AtEnd.setBegin(AtLoc);
439 AtEnd.setEnd(Tok.getLocation());
441 } else if (DirectiveKind == tok::objc_not_keyword) {
442 Diag(Tok, diag::err_objc_unknown_at);
443 SkipUntil(tok::semi);
447 // Eat the identifier.
450 switch (DirectiveKind) {
452 // FIXME: If someone forgets an @end on a protocol, this loop will
453 // continue to eat up tons of stuff and spew lots of nonsense errors. It
454 // would probably be better to bail out if we saw an @class or @interface
455 // or something like that.
456 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
457 // Skip until we see an '@' or '}' or ';'.
458 SkipUntil(tok::r_brace, tok::at);
461 case tok::objc_implementation:
462 case tok::objc_interface:
463 Diag(AtLoc, diag::err_objc_missing_end)
464 << FixItHint::CreateInsertion(AtLoc, "@end\n");
465 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
466 << (int) Actions.getObjCContainerKind();
470 case tok::objc_required:
471 case tok::objc_optional:
472 // This is only valid on protocols.
473 // FIXME: Should this check for ObjC2 being enabled?
474 if (contextKey != tok::objc_protocol)
475 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
477 MethodImplKind = DirectiveKind;
480 case tok::objc_property:
481 if (!getLangOpts().ObjC2)
482 Diag(AtLoc, diag::err_objc_properties_require_objc2);
485 SourceLocation LParenLoc;
486 // Parse property attribute list, if any.
487 if (Tok.is(tok::l_paren)) {
488 LParenLoc = Tok.getLocation();
489 ParseObjCPropertyAttribute(OCDS);
492 ObjCPropertyCallback Callback(*this, allProperties,
493 OCDS, AtLoc, LParenLoc, MethodImplKind);
495 // Parse all the comma separated declarators.
496 ParsingDeclSpec DS(*this);
497 ParseStructDeclaration(DS, Callback);
499 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
504 // We break out of the big loop in two cases: when we see @end or when we see
505 // EOF. In the former case, eat the @end. In the later case, emit an error.
506 if (Tok.is(tok::code_completion)) {
507 Actions.CodeCompleteObjCAtDirective(getCurScope());
508 return cutOffParsing();
509 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
510 ConsumeToken(); // the "end" identifier
512 Diag(Tok, diag::err_objc_missing_end)
513 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
514 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
515 << (int) Actions.getObjCContainerKind();
516 AtEnd.setBegin(Tok.getLocation());
517 AtEnd.setEnd(Tok.getLocation());
520 // Insert collected methods declarations into the @interface object.
521 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
522 Actions.ActOnAtEnd(getCurScope(), AtEnd,
523 allMethods.data(), allMethods.size(),
524 allProperties.data(), allProperties.size(),
525 allTUVariables.data(), allTUVariables.size());
528 /// Parse property attribute declarations.
530 /// property-attr-decl: '(' property-attrlist ')'
531 /// property-attrlist:
532 /// property-attribute
533 /// property-attrlist ',' property-attribute
534 /// property-attribute:
535 /// getter '=' identifier
536 /// setter '=' identifier ':'
546 /// unsafe_unretained
548 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
549 assert(Tok.getKind() == tok::l_paren);
550 BalancedDelimiterTracker T(*this, tok::l_paren);
554 if (Tok.is(tok::code_completion)) {
555 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
556 return cutOffParsing();
558 const IdentifierInfo *II = Tok.getIdentifierInfo();
560 // If this is not an identifier at all, bail out early.
566 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
568 if (II->isStr("readonly"))
569 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
570 else if (II->isStr("assign"))
571 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
572 else if (II->isStr("unsafe_unretained"))
573 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
574 else if (II->isStr("readwrite"))
575 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
576 else if (II->isStr("retain"))
577 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
578 else if (II->isStr("strong"))
579 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
580 else if (II->isStr("copy"))
581 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
582 else if (II->isStr("nonatomic"))
583 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
584 else if (II->isStr("atomic"))
585 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
586 else if (II->isStr("weak"))
587 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
588 else if (II->isStr("getter") || II->isStr("setter")) {
589 bool IsSetter = II->getNameStart()[0] == 's';
591 // getter/setter require extra treatment.
592 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
593 diag::err_objc_expected_equal_for_getter;
595 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
598 if (Tok.is(tok::code_completion)) {
600 Actions.CodeCompleteObjCPropertySetter(getCurScope());
602 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
603 return cutOffParsing();
607 SourceLocation SelLoc;
608 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
611 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
613 SkipUntil(tok::r_paren);
618 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
619 DS.setSetterName(SelIdent);
621 if (ExpectAndConsume(tok::colon,
622 diag::err_expected_colon_after_setter_name, "",
626 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
627 DS.setGetterName(SelIdent);
630 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
631 SkipUntil(tok::r_paren);
635 if (Tok.isNot(tok::comma))
644 /// objc-method-proto:
645 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
646 /// objc-class-method objc-method-decl objc-method-attributes[opt]
648 /// objc-instance-method: '-'
649 /// objc-class-method: '+'
651 /// objc-method-attributes: [OBJC2]
652 /// __attribute__((deprecated))
654 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
655 bool MethodDefinition) {
656 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
658 tok::TokenKind methodType = Tok.getKind();
659 SourceLocation mLoc = ConsumeToken();
660 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
662 // Since this rule is used for both method declarations and definitions,
663 // the caller is (optionally) responsible for consuming the ';'.
670 /// enum struct union if else while do for switch case default
671 /// break continue return goto asm sizeof typeof __alignof
672 /// unsigned long const short volatile signed restrict _Complex
673 /// in out inout bycopy byref oneway int char float double void _Bool
675 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
677 switch (Tok.getKind()) {
686 case tok::exclaimequal:
690 case tok::caretequal: {
691 std::string ThisTok(PP.getSpelling(Tok));
692 if (isalpha(ThisTok[0])) {
693 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
694 Tok.setKind(tok::identifier);
695 SelectorLoc = ConsumeToken();
701 case tok::identifier:
711 case tok::kw_const_cast:
712 case tok::kw_continue:
713 case tok::kw_default:
717 case tok::kw_dynamic_cast:
720 case tok::kw_explicit:
732 case tok::kw_mutable:
733 case tok::kw_namespace:
735 case tok::kw_operator:
736 case tok::kw_private:
737 case tok::kw_protected:
739 case tok::kw_register:
740 case tok::kw_reinterpret_cast:
741 case tok::kw_restrict:
747 case tok::kw_static_cast:
750 case tok::kw_template:
755 case tok::kw_typedef:
757 case tok::kw_typename:
760 case tok::kw_unsigned:
762 case tok::kw_virtual:
764 case tok::kw_volatile:
765 case tok::kw_wchar_t:
768 case tok::kw__Complex:
769 case tok::kw___alignof:
770 IdentifierInfo *II = Tok.getIdentifierInfo();
771 SelectorLoc = ConsumeToken();
776 /// objc-for-collection-in: 'in'
778 bool Parser::isTokIdentifier_in() const {
779 // FIXME: May have to do additional look-ahead to only allow for
780 // valid tokens following an 'in'; such as an identifier, unary operators,
782 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
783 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
786 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
787 /// qualifier list and builds their bitmask representation in the input
790 /// objc-type-qualifiers:
791 /// objc-type-qualifier
792 /// objc-type-qualifiers objc-type-qualifier
794 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
795 Declarator::TheContext Context) {
796 assert(Context == Declarator::ObjCParameterContext ||
797 Context == Declarator::ObjCResultContext);
800 if (Tok.is(tok::code_completion)) {
801 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
802 Context == Declarator::ObjCParameterContext);
803 return cutOffParsing();
806 if (Tok.isNot(tok::identifier))
809 const IdentifierInfo *II = Tok.getIdentifierInfo();
810 for (unsigned i = 0; i != objc_NumQuals; ++i) {
811 if (II != ObjCTypeQuals[i])
814 ObjCDeclSpec::ObjCDeclQualifier Qual;
816 default: llvm_unreachable("Unknown decl qualifier");
817 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
818 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
819 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
820 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
821 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
822 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
824 DS.setObjCDeclQualifier(Qual);
830 // If this wasn't a recognized qualifier, bail out.
835 /// Take all the decl attributes out of the given list and add
836 /// them to the given attribute set.
837 static void takeDeclAttributes(ParsedAttributes &attrs,
838 AttributeList *list) {
840 AttributeList *cur = list;
841 list = cur->getNext();
843 if (!cur->isUsedAsTypeAttr()) {
844 // Clear out the next pointer. We're really completely
845 // destroying the internal invariants of the declarator here,
846 // but it doesn't matter because we're done with it.
853 /// takeDeclAttributes - Take all the decl attributes from the given
854 /// declarator and add them to the given list.
855 static void takeDeclAttributes(ParsedAttributes &attrs,
857 // First, take ownership of all attributes.
858 attrs.getPool().takeAllFrom(D.getAttributePool());
859 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
861 // Now actually move the attributes over.
862 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
863 takeDeclAttributes(attrs, D.getAttributes());
864 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
865 takeDeclAttributes(attrs,
866 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
870 /// '(' objc-type-qualifiers[opt] type-name ')'
871 /// '(' objc-type-qualifiers[opt] ')'
873 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
874 Declarator::TheContext context,
875 ParsedAttributes *paramAttrs) {
876 assert(context == Declarator::ObjCParameterContext ||
877 context == Declarator::ObjCResultContext);
878 assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
880 assert(Tok.is(tok::l_paren) && "expected (");
882 BalancedDelimiterTracker T(*this, tok::l_paren);
885 SourceLocation TypeStartLoc = Tok.getLocation();
886 ObjCDeclContextSwitch ObjCDC(*this);
888 // Parse type qualifiers, in, inout, etc.
889 ParseObjCTypeQualifierList(DS, context);
892 if (isTypeSpecifierQualifier()) {
893 // Parse an abstract declarator.
894 DeclSpec declSpec(AttrFactory);
895 declSpec.setObjCQualifiers(&DS);
896 ParseSpecifierQualifierList(declSpec);
897 declSpec.SetRangeEnd(Tok.getLocation());
898 Declarator declarator(declSpec, context);
899 ParseDeclarator(declarator);
901 // If that's not invalid, extract a type.
902 if (!declarator.isInvalidType()) {
903 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
904 if (!type.isInvalid())
907 // If we're parsing a parameter, steal all the decl attributes
908 // and add them to the decl spec.
909 if (context == Declarator::ObjCParameterContext)
910 takeDeclAttributes(*paramAttrs, declarator);
912 } else if (context == Declarator::ObjCResultContext &&
913 Tok.is(tok::identifier)) {
914 if (!Ident_instancetype)
915 Ident_instancetype = PP.getIdentifierInfo("instancetype");
917 if (Tok.getIdentifierInfo() == Ident_instancetype) {
918 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
923 if (Tok.is(tok::r_paren))
925 else if (Tok.getLocation() == TypeStartLoc) {
926 // If we didn't eat any tokens, then this isn't a type.
927 Diag(Tok, diag::err_expected_type);
928 SkipUntil(tok::r_paren);
930 // Otherwise, we found *something*, but didn't get a ')' in the right
931 // place. Emit an error then return what we have as the type.
937 /// objc-method-decl:
939 /// objc-keyword-selector objc-parmlist[opt]
940 /// objc-type-name objc-selector
941 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
943 /// objc-keyword-selector:
944 /// objc-keyword-decl
945 /// objc-keyword-selector objc-keyword-decl
947 /// objc-keyword-decl:
948 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
949 /// objc-selector ':' objc-keyword-attributes[opt] identifier
950 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
951 /// ':' objc-keyword-attributes[opt] identifier
954 /// objc-parms objc-ellipsis[opt]
957 /// objc-parms , parameter-declaration
962 /// objc-keyword-attributes: [OBJC2]
963 /// __attribute__((unused))
965 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
966 tok::TokenKind mType,
967 tok::ObjCKeywordKind MethodImplKind,
968 bool MethodDefinition) {
969 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
971 if (Tok.is(tok::code_completion)) {
972 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
973 /*ReturnType=*/ ParsedType());
978 // Parse the return type if present.
979 ParsedType ReturnType;
981 if (Tok.is(tok::l_paren))
982 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
984 // If attributes exist before the method, parse them.
985 ParsedAttributes methodAttrs(AttrFactory);
986 if (getLangOpts().ObjC2)
987 MaybeParseGNUAttributes(methodAttrs);
989 if (Tok.is(tok::code_completion)) {
990 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
996 // Now parse the selector.
997 SourceLocation selLoc;
998 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1000 // An unnamed colon is valid.
1001 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1002 Diag(Tok, diag::err_expected_selector_for_method)
1003 << SourceRange(mLoc, Tok.getLocation());
1004 // Skip until we get a ; or @.
1005 SkipUntil(tok::at, true /*StopAtSemi*/, true /*don't consume*/);
1009 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1010 if (Tok.isNot(tok::colon)) {
1011 // If attributes exist after the method, parse them.
1012 if (getLangOpts().ObjC2)
1013 MaybeParseGNUAttributes(methodAttrs);
1015 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1017 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1018 mType, DSRet, ReturnType,
1020 CParamInfo.data(), CParamInfo.size(),
1021 methodAttrs.getList(), MethodImplKind,
1022 false, MethodDefinition);
1023 PD.complete(Result);
1027 SmallVector<IdentifierInfo *, 12> KeyIdents;
1028 SmallVector<SourceLocation, 12> KeyLocs;
1029 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1030 ParseScope PrototypeScope(this,
1031 Scope::FunctionPrototypeScope|Scope::DeclScope);
1033 AttributePool allParamAttrs(AttrFactory);
1036 ParsedAttributes paramAttrs(AttrFactory);
1037 Sema::ObjCArgInfo ArgInfo;
1039 // Each iteration parses a single keyword argument.
1040 if (Tok.isNot(tok::colon)) {
1041 Diag(Tok, diag::err_expected_colon);
1044 ConsumeToken(); // Eat the ':'.
1046 ArgInfo.Type = ParsedType();
1047 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1048 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1049 Declarator::ObjCParameterContext,
1052 // If attributes exist before the argument name, parse them.
1053 // Regardless, collect all the attributes we've parsed so far.
1054 ArgInfo.ArgAttrs = 0;
1055 if (getLangOpts().ObjC2) {
1056 MaybeParseGNUAttributes(paramAttrs);
1057 ArgInfo.ArgAttrs = paramAttrs.getList();
1060 // Code completion for the next piece of the selector.
1061 if (Tok.is(tok::code_completion)) {
1062 KeyIdents.push_back(SelIdent);
1063 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1064 mType == tok::minus,
1065 /*AtParameterName=*/true,
1073 if (Tok.isNot(tok::identifier)) {
1074 Diag(Tok, diag::err_expected_ident); // missing argument name.
1078 ArgInfo.Name = Tok.getIdentifierInfo();
1079 ArgInfo.NameLoc = Tok.getLocation();
1080 ConsumeToken(); // Eat the identifier.
1082 ArgInfos.push_back(ArgInfo);
1083 KeyIdents.push_back(SelIdent);
1084 KeyLocs.push_back(selLoc);
1086 // Make sure the attributes persist.
1087 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1089 // Code completion for the next piece of the selector.
1090 if (Tok.is(tok::code_completion)) {
1091 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1092 mType == tok::minus,
1093 /*AtParameterName=*/false,
1101 // Check for another keyword selector.
1102 SelIdent = ParseObjCSelectorPiece(selLoc);
1103 if (!SelIdent && Tok.isNot(tok::colon))
1105 // We have a selector or a colon, continue parsing.
1108 bool isVariadic = false;
1109 bool cStyleParamWarned = false;
1110 // Parse the (optional) parameter list.
1111 while (Tok.is(tok::comma)) {
1113 if (Tok.is(tok::ellipsis)) {
1118 if (!cStyleParamWarned) {
1119 Diag(Tok, diag::warn_cstyle_param);
1120 cStyleParamWarned = true;
1122 DeclSpec DS(AttrFactory);
1123 ParseDeclarationSpecifiers(DS);
1124 // Parse the declarator.
1125 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1126 ParseDeclarator(ParmDecl);
1127 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1128 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1129 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1130 ParmDecl.getIdentifierLoc(),
1135 // FIXME: Add support for optional parameter list...
1136 // If attributes exist after the method, parse them.
1137 if (getLangOpts().ObjC2)
1138 MaybeParseGNUAttributes(methodAttrs);
1140 if (KeyIdents.size() == 0)
1143 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1146 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1147 mType, DSRet, ReturnType,
1148 KeyLocs, Sel, &ArgInfos[0],
1149 CParamInfo.data(), CParamInfo.size(),
1150 methodAttrs.getList(),
1151 MethodImplKind, isVariadic, MethodDefinition);
1153 PD.complete(Result);
1157 /// objc-protocol-refs:
1158 /// '<' identifier-list '>'
1161 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1162 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1163 bool WarnOnDeclarations,
1164 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1165 assert(Tok.is(tok::less) && "expected <");
1167 LAngleLoc = ConsumeToken(); // the "<"
1169 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1172 if (Tok.is(tok::code_completion)) {
1173 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1174 ProtocolIdents.size());
1179 if (Tok.isNot(tok::identifier)) {
1180 Diag(Tok, diag::err_expected_ident);
1181 SkipUntil(tok::greater);
1184 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1185 Tok.getLocation()));
1186 ProtocolLocs.push_back(Tok.getLocation());
1189 if (Tok.isNot(tok::comma))
1195 if (Tok.isNot(tok::greater)) {
1196 Diag(Tok, diag::err_expected_greater);
1200 EndLoc = ConsumeToken();
1202 // Convert the list of protocols identifiers into a list of protocol decls.
1203 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1204 &ProtocolIdents[0], ProtocolIdents.size(),
1209 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1210 /// in a decl-specifier-seq, starting at the '<'.
1211 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1212 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1213 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1214 SourceLocation LAngleLoc, EndProtoLoc;
1215 SmallVector<Decl *, 8> ProtocolDecl;
1216 SmallVector<SourceLocation, 8> ProtocolLocs;
1217 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1218 LAngleLoc, EndProtoLoc);
1219 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1220 ProtocolLocs.data(), LAngleLoc);
1221 if (EndProtoLoc.isValid())
1222 DS.SetRangeEnd(EndProtoLoc);
1227 /// objc-class-instance-variables:
1228 /// '{' objc-instance-variable-decl-list[opt] '}'
1230 /// objc-instance-variable-decl-list:
1231 /// objc-visibility-spec
1232 /// objc-instance-variable-decl ';'
1234 /// objc-instance-variable-decl-list objc-visibility-spec
1235 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1236 /// objc-instance-variable-decl-list ';'
1238 /// objc-visibility-spec:
1242 /// @package [OBJC2]
1244 /// objc-instance-variable-decl:
1245 /// struct-declaration
1247 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1248 tok::ObjCKeywordKind visibility,
1249 SourceLocation atLoc) {
1250 assert(Tok.is(tok::l_brace) && "expected {");
1251 SmallVector<Decl *, 32> AllIvarDecls;
1253 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1254 ObjCDeclContextSwitch ObjCDC(*this);
1256 BalancedDelimiterTracker T(*this, tok::l_brace);
1259 // While we still have something to read, read the instance variables.
1260 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1261 // Each iteration of this loop reads one objc-instance-variable-decl.
1263 // Check for extraneous top-level semicolon.
1264 if (Tok.is(tok::semi)) {
1265 ConsumeExtraSemi(InstanceVariableList);
1269 // Set the default visibility to private.
1270 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1271 ConsumeToken(); // eat the @ sign
1273 if (Tok.is(tok::code_completion)) {
1274 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1275 return cutOffParsing();
1278 switch (Tok.getObjCKeywordID()) {
1279 case tok::objc_private:
1280 case tok::objc_public:
1281 case tok::objc_protected:
1282 case tok::objc_package:
1283 visibility = Tok.getObjCKeywordID();
1287 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1292 if (Tok.is(tok::code_completion)) {
1293 Actions.CodeCompleteOrdinaryName(getCurScope(),
1294 Sema::PCC_ObjCInstanceVariableList);
1295 return cutOffParsing();
1298 struct ObjCIvarCallback : FieldCallback {
1301 tok::ObjCKeywordKind visibility;
1302 SmallVectorImpl<Decl *> &AllIvarDecls;
1304 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1305 SmallVectorImpl<Decl *> &AllIvarDecls) :
1306 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1309 void invoke(ParsingFieldDeclarator &FD) {
1310 P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1311 // Install the declarator into the interface decl.
1313 = P.Actions.ActOnIvar(P.getCurScope(),
1314 FD.D.getDeclSpec().getSourceRange().getBegin(),
1315 FD.D, FD.BitfieldSize, visibility);
1316 P.Actions.ActOnObjCContainerFinishDefinition();
1318 AllIvarDecls.push_back(Field);
1321 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1323 // Parse all the comma separated declarators.
1324 ParsingDeclSpec DS(*this);
1325 ParseStructDeclaration(DS, Callback);
1327 if (Tok.is(tok::semi)) {
1330 Diag(Tok, diag::err_expected_semi_decl_list);
1331 // Skip to end of block or statement
1332 SkipUntil(tok::r_brace, true, true);
1337 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1338 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1339 Actions.ActOnObjCContainerFinishDefinition();
1340 // Call ActOnFields() even if we don't have any decls. This is useful
1341 // for code rewriting tools that need to be aware of the empty list.
1342 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1344 T.getOpenLocation(), T.getCloseLocation(), 0);
1348 /// objc-protocol-declaration:
1349 /// objc-protocol-definition
1350 /// objc-protocol-forward-reference
1352 /// objc-protocol-definition:
1353 /// \@protocol identifier
1354 /// objc-protocol-refs[opt]
1355 /// objc-interface-decl-list
1358 /// objc-protocol-forward-reference:
1359 /// \@protocol identifier-list ';'
1361 /// "\@protocol identifier ;" should be resolved as "\@protocol
1362 /// identifier-list ;": objc-interface-decl-list may not start with a
1363 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1364 Parser::DeclGroupPtrTy
1365 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1366 ParsedAttributes &attrs) {
1367 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1368 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1369 ConsumeToken(); // the "protocol" identifier
1371 if (Tok.is(tok::code_completion)) {
1372 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1374 return DeclGroupPtrTy();
1377 if (Tok.isNot(tok::identifier)) {
1378 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1379 return DeclGroupPtrTy();
1381 // Save the protocol name, then consume it.
1382 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1383 SourceLocation nameLoc = ConsumeToken();
1385 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1386 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1388 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1392 CheckNestedObjCContexts(AtLoc);
1394 if (Tok.is(tok::comma)) { // list of forward declarations.
1395 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1396 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1398 // Parse the list of forward declarations.
1400 ConsumeToken(); // the ','
1401 if (Tok.isNot(tok::identifier)) {
1402 Diag(Tok, diag::err_expected_ident);
1403 SkipUntil(tok::semi);
1404 return DeclGroupPtrTy();
1406 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1407 Tok.getLocation()));
1408 ConsumeToken(); // the identifier
1410 if (Tok.isNot(tok::comma))
1414 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1415 return DeclGroupPtrTy();
1417 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1419 ProtocolRefs.size(),
1423 // Last, and definitely not least, parse a protocol declaration.
1424 SourceLocation LAngleLoc, EndProtoLoc;
1426 SmallVector<Decl *, 8> ProtocolRefs;
1427 SmallVector<SourceLocation, 8> ProtocolLocs;
1428 if (Tok.is(tok::less) &&
1429 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1430 LAngleLoc, EndProtoLoc))
1431 return DeclGroupPtrTy();
1434 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1435 ProtocolRefs.data(),
1436 ProtocolRefs.size(),
1437 ProtocolLocs.data(),
1438 EndProtoLoc, attrs.getList());
1440 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1441 return Actions.ConvertDeclToDeclGroup(ProtoType);
1444 /// objc-implementation:
1445 /// objc-class-implementation-prologue
1446 /// objc-category-implementation-prologue
1448 /// objc-class-implementation-prologue:
1449 /// @implementation identifier objc-superclass[opt]
1450 /// objc-class-instance-variables[opt]
1452 /// objc-category-implementation-prologue:
1453 /// @implementation identifier ( identifier )
1454 Parser::DeclGroupPtrTy
1455 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1456 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1457 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1458 CheckNestedObjCContexts(AtLoc);
1459 ConsumeToken(); // the "implementation" identifier
1461 // Code completion after '@implementation'.
1462 if (Tok.is(tok::code_completion)) {
1463 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1465 return DeclGroupPtrTy();
1468 if (Tok.isNot(tok::identifier)) {
1469 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1470 return DeclGroupPtrTy();
1472 // We have a class or category name - consume it.
1473 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1474 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1475 Decl *ObjCImpDecl = 0;
1477 if (Tok.is(tok::l_paren)) {
1478 // we have a category implementation.
1480 SourceLocation categoryLoc, rparenLoc;
1481 IdentifierInfo *categoryId = 0;
1483 if (Tok.is(tok::code_completion)) {
1484 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1486 return DeclGroupPtrTy();
1489 if (Tok.is(tok::identifier)) {
1490 categoryId = Tok.getIdentifierInfo();
1491 categoryLoc = ConsumeToken();
1493 Diag(Tok, diag::err_expected_ident); // missing category name.
1494 return DeclGroupPtrTy();
1496 if (Tok.isNot(tok::r_paren)) {
1497 Diag(Tok, diag::err_expected_rparen);
1498 SkipUntil(tok::r_paren, false); // don't stop at ';'
1499 return DeclGroupPtrTy();
1501 rparenLoc = ConsumeParen();
1502 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1503 AtLoc, nameId, nameLoc, categoryId,
1507 // We have a class implementation
1508 SourceLocation superClassLoc;
1509 IdentifierInfo *superClassId = 0;
1510 if (Tok.is(tok::colon)) {
1511 // We have a super class
1513 if (Tok.isNot(tok::identifier)) {
1514 Diag(Tok, diag::err_expected_ident); // 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);
1527 assert(ObjCImpDecl);
1529 SmallVector<Decl *, 8> DeclsInGroup;
1532 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1533 while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
1534 ParsedAttributesWithRange attrs(AttrFactory);
1535 MaybeParseCXX0XAttributes(attrs);
1536 MaybeParseMicrosoftAttributes(attrs);
1537 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1538 DeclGroupRef DG = DGP.get();
1539 DeclsInGroup.append(DG.begin(), DG.end());
1544 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1547 Parser::DeclGroupPtrTy
1548 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1549 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1550 "ParseObjCAtEndDeclaration(): Expected @end");
1551 ConsumeToken(); // the "end" identifier
1552 if (CurParsedObjCImpl)
1553 CurParsedObjCImpl->finish(atEnd);
1555 // missing @implementation
1556 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1557 return DeclGroupPtrTy();
1560 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1562 finish(P.Tok.getLocation());
1563 if (P.Tok.is(tok::eof)) {
1564 P.Diag(P.Tok, diag::err_objc_missing_end)
1565 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1566 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1567 << Sema::OCK_Implementation;
1570 P.CurParsedObjCImpl = 0;
1571 assert(LateParsedObjCMethods.empty());
1574 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1576 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1577 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1578 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1581 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1584 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1585 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1586 false/*c-functions*/);
1588 /// \brief Clear and free the cached objc methods.
1589 for (LateParsedObjCMethodContainer::iterator
1590 I = LateParsedObjCMethods.begin(),
1591 E = LateParsedObjCMethods.end(); I != E; ++I)
1593 LateParsedObjCMethods.clear();
1598 /// compatibility-alias-decl:
1599 /// @compatibility_alias alias-name class-name ';'
1601 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1602 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1603 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1604 ConsumeToken(); // consume compatibility_alias
1605 if (Tok.isNot(tok::identifier)) {
1606 Diag(Tok, diag::err_expected_ident);
1609 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1610 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1611 if (Tok.isNot(tok::identifier)) {
1612 Diag(Tok, diag::err_expected_ident);
1615 IdentifierInfo *classId = Tok.getIdentifierInfo();
1616 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1617 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1618 "@compatibility_alias");
1619 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1623 /// property-synthesis:
1624 /// @synthesize property-ivar-list ';'
1626 /// property-ivar-list:
1628 /// property-ivar-list ',' property-ivar
1632 /// identifier '=' identifier
1634 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1635 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1636 "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1637 ConsumeToken(); // consume synthesize
1640 if (Tok.is(tok::code_completion)) {
1641 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1646 if (Tok.isNot(tok::identifier)) {
1647 Diag(Tok, diag::err_synthesized_property_name);
1648 SkipUntil(tok::semi);
1652 IdentifierInfo *propertyIvar = 0;
1653 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1654 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1655 SourceLocation propertyIvarLoc;
1656 if (Tok.is(tok::equal)) {
1657 // property '=' ivar-name
1658 ConsumeToken(); // consume '='
1660 if (Tok.is(tok::code_completion)) {
1661 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1666 if (Tok.isNot(tok::identifier)) {
1667 Diag(Tok, diag::err_expected_ident);
1670 propertyIvar = Tok.getIdentifierInfo();
1671 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1673 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1674 propertyId, propertyIvar, propertyIvarLoc);
1675 if (Tok.isNot(tok::comma))
1677 ConsumeToken(); // consume ','
1679 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1683 /// property-dynamic:
1684 /// @dynamic property-list
1688 /// property-list ',' identifier
1690 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1691 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1692 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1693 ConsumeToken(); // consume dynamic
1695 if (Tok.is(tok::code_completion)) {
1696 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1701 if (Tok.isNot(tok::identifier)) {
1702 Diag(Tok, diag::err_expected_ident);
1703 SkipUntil(tok::semi);
1707 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1708 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1709 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1710 propertyId, 0, SourceLocation());
1712 if (Tok.isNot(tok::comma))
1714 ConsumeToken(); // consume ','
1716 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1720 /// objc-throw-statement:
1721 /// throw expression[opt];
1723 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1725 ConsumeToken(); // consume throw
1726 if (Tok.isNot(tok::semi)) {
1727 Res = ParseExpression();
1728 if (Res.isInvalid()) {
1729 SkipUntil(tok::semi);
1734 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1735 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1738 /// objc-synchronized-statement:
1739 /// @synchronized '(' expression ')' compound-statement
1742 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1743 ConsumeToken(); // consume synchronized
1744 if (Tok.isNot(tok::l_paren)) {
1745 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1749 // The operand is surrounded with parentheses.
1750 ConsumeParen(); // '('
1751 ExprResult operand(ParseExpression());
1753 if (Tok.is(tok::r_paren)) {
1754 ConsumeParen(); // ')'
1756 if (!operand.isInvalid())
1757 Diag(Tok, diag::err_expected_rparen);
1759 // Skip forward until we see a left brace, but don't consume it.
1760 SkipUntil(tok::l_brace, true, true);
1763 // Require a compound statement.
1764 if (Tok.isNot(tok::l_brace)) {
1765 if (!operand.isInvalid())
1766 Diag(Tok, diag::err_expected_lbrace);
1770 // Check the @synchronized operand now.
1771 if (!operand.isInvalid())
1772 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1774 // Parse the compound statement within a new scope.
1775 ParseScope bodyScope(this, Scope::DeclScope);
1776 StmtResult body(ParseCompoundStatementBody());
1779 // If there was a semantic or parse error earlier with the
1780 // operand, fail now.
1781 if (operand.isInvalid())
1784 if (body.isInvalid())
1785 body = Actions.ActOnNullStmt(Tok.getLocation());
1787 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1790 /// objc-try-catch-statement:
1791 /// @try compound-statement objc-catch-list[opt]
1792 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1794 /// objc-catch-list:
1795 /// @catch ( parameter-declaration ) compound-statement
1796 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1797 /// catch-parameter-declaration:
1798 /// parameter-declaration
1801 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1802 bool catch_or_finally_seen = false;
1804 ConsumeToken(); // consume try
1805 if (Tok.isNot(tok::l_brace)) {
1806 Diag(Tok, diag::err_expected_lbrace);
1809 StmtVector CatchStmts(Actions);
1810 StmtResult FinallyStmt;
1811 ParseScope TryScope(this, Scope::DeclScope);
1812 StmtResult TryBody(ParseCompoundStatementBody());
1814 if (TryBody.isInvalid())
1815 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1817 while (Tok.is(tok::at)) {
1818 // At this point, we need to lookahead to determine if this @ is the start
1819 // of an @catch or @finally. We don't want to consume the @ token if this
1820 // is an @try or @encode or something else.
1821 Token AfterAt = GetLookAheadToken(1);
1822 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1823 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1826 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1827 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1828 Decl *FirstPart = 0;
1829 ConsumeToken(); // consume catch
1830 if (Tok.is(tok::l_paren)) {
1832 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1833 if (Tok.isNot(tok::ellipsis)) {
1834 DeclSpec DS(AttrFactory);
1835 ParseDeclarationSpecifiers(DS);
1836 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1837 ParseDeclarator(ParmDecl);
1839 // Inform the actions module about the declarator, so it
1840 // gets added to the current scope.
1841 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1843 ConsumeToken(); // consume '...'
1845 SourceLocation RParenLoc;
1847 if (Tok.is(tok::r_paren))
1848 RParenLoc = ConsumeParen();
1849 else // Skip over garbage, until we get to ')'. Eat the ')'.
1850 SkipUntil(tok::r_paren, true, false);
1852 StmtResult CatchBody(true);
1853 if (Tok.is(tok::l_brace))
1854 CatchBody = ParseCompoundStatementBody();
1856 Diag(Tok, diag::err_expected_lbrace);
1857 if (CatchBody.isInvalid())
1858 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1860 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1864 if (!Catch.isInvalid())
1865 CatchStmts.push_back(Catch.release());
1868 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1872 catch_or_finally_seen = true;
1874 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1875 ConsumeToken(); // consume finally
1876 ParseScope FinallyScope(this, Scope::DeclScope);
1878 StmtResult FinallyBody(true);
1879 if (Tok.is(tok::l_brace))
1880 FinallyBody = ParseCompoundStatementBody();
1882 Diag(Tok, diag::err_expected_lbrace);
1883 if (FinallyBody.isInvalid())
1884 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1885 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1886 FinallyBody.take());
1887 catch_or_finally_seen = true;
1891 if (!catch_or_finally_seen) {
1892 Diag(atLoc, diag::err_missing_catch_finally);
1896 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1897 move_arg(CatchStmts),
1898 FinallyStmt.take());
1901 /// objc-autoreleasepool-statement:
1902 /// @autoreleasepool compound-statement
1905 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1906 ConsumeToken(); // consume autoreleasepool
1907 if (Tok.isNot(tok::l_brace)) {
1908 Diag(Tok, diag::err_expected_lbrace);
1911 // Enter a scope to hold everything within the compound stmt. Compound
1912 // statements can always hold declarations.
1913 ParseScope BodyScope(this, Scope::DeclScope);
1915 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1918 if (AutoreleasePoolBody.isInvalid())
1919 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1920 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1921 AutoreleasePoolBody.take());
1924 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1925 /// for later parsing.
1926 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1927 LexedMethod* LM = new LexedMethod(this, MDecl);
1928 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1929 CachedTokens &Toks = LM->Toks;
1930 // Begin by storing the '{' or 'try' or ':' token.
1931 Toks.push_back(Tok);
1932 if (Tok.is(tok::kw_try)) {
1934 if (Tok.is(tok::colon)) {
1935 Toks.push_back(Tok);
1937 while (Tok.isNot(tok::l_brace)) {
1938 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1939 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1942 Toks.push_back(Tok); // also store '{'
1944 else if (Tok.is(tok::colon)) {
1946 while (Tok.isNot(tok::l_brace)) {
1947 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1948 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1950 Toks.push_back(Tok); // also store '{'
1953 // Consume everything up to (and including) the matching right brace.
1954 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1955 while (Tok.is(tok::kw_catch)) {
1956 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1957 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1961 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1963 Decl *Parser::ParseObjCMethodDefinition() {
1964 Decl *MDecl = ParseObjCMethodPrototype();
1966 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1967 "parsing Objective-C method");
1969 // parse optional ';'
1970 if (Tok.is(tok::semi)) {
1971 if (CurParsedObjCImpl) {
1972 Diag(Tok, diag::warn_semicolon_before_method_body)
1973 << FixItHint::CreateRemoval(Tok.getLocation());
1978 // We should have an opening brace now.
1979 if (Tok.isNot(tok::l_brace)) {
1980 Diag(Tok, diag::err_expected_method_body);
1982 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1983 SkipUntil(tok::l_brace, true, true);
1985 // If we didn't find the '{', bail out.
1986 if (Tok.isNot(tok::l_brace))
1992 SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
1996 // Allow the rest of sema to find private method decl implementations.
1997 Actions.AddAnyMethodToGlobalPool(MDecl);
1998 assert (CurParsedObjCImpl
1999 && "ParseObjCMethodDefinition - Method out of @implementation");
2000 // Consume the tokens and store them for later parsing.
2001 StashAwayMethodOrFunctionBodyTokens(MDecl);
2005 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2006 if (Tok.is(tok::code_completion)) {
2007 Actions.CodeCompleteObjCAtStatement(getCurScope());
2012 if (Tok.isObjCAtKeyword(tok::objc_try))
2013 return ParseObjCTryStmt(AtLoc);
2015 if (Tok.isObjCAtKeyword(tok::objc_throw))
2016 return ParseObjCThrowStmt(AtLoc);
2018 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2019 return ParseObjCSynchronizedStmt(AtLoc);
2021 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2022 return ParseObjCAutoreleasePoolStmt(AtLoc);
2024 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2025 if (Res.isInvalid()) {
2026 // If the expression is invalid, skip ahead to the next semicolon. Not
2027 // doing this opens us up to the possibility of infinite loops if
2028 // ParseExpression does not consume any tokens.
2029 SkipUntil(tok::semi);
2033 // Otherwise, eat the semicolon.
2034 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2035 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
2038 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2039 switch (Tok.getKind()) {
2040 case tok::code_completion:
2041 Actions.CodeCompleteObjCAtExpression(getCurScope());
2047 tok::TokenKind Kind = Tok.getKind();
2048 SourceLocation OpLoc = ConsumeToken();
2050 if (!Tok.is(tok::numeric_constant)) {
2051 const char *Symbol = 0;
2053 case tok::minus: Symbol = "-"; break;
2054 case tok::plus: Symbol = "+"; break;
2055 default: llvm_unreachable("missing unary operator case");
2057 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2062 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2063 if (Lit.isInvalid()) {
2066 ConsumeToken(); // Consume the literal token.
2068 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
2069 if (Lit.isInvalid())
2072 return ParsePostfixExpressionSuffix(
2073 Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2076 case tok::string_literal: // primary-expression: string-literal
2077 case tok::wide_string_literal:
2078 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2080 case tok::char_constant:
2081 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2083 case tok::numeric_constant:
2084 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2086 case tok::kw_true: // Objective-C++, etc.
2087 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2088 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2089 case tok::kw_false: // Objective-C++, etc.
2090 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2091 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2094 // Objective-C array literal
2095 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2098 // Objective-C dictionary literal
2099 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2102 // Objective-C boxed expression
2103 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2106 if (Tok.getIdentifierInfo() == 0)
2107 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2109 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2110 case tok::objc_encode:
2111 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2112 case tok::objc_protocol:
2113 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2114 case tok::objc_selector:
2115 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2117 const char *str = 0;
2118 if (GetLookAheadToken(1).is(tok::l_brace)) {
2119 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2122 : (ch == 'f' ? "finally"
2123 : (ch == 'a' ? "autoreleasepool" : 0));
2126 SourceLocation kwLoc = Tok.getLocation();
2127 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2128 FixItHint::CreateReplacement(kwLoc, str));
2131 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2137 /// \brirg Parse the receiver of an Objective-C++ message send.
2139 /// This routine parses the receiver of a message send in
2140 /// Objective-C++ either as a type or as an expression. Note that this
2141 /// routine must not be called to parse a send to 'super', since it
2142 /// has no way to return such a result.
2144 /// \param IsExpr Whether the receiver was parsed as an expression.
2146 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2147 /// IsExpr is true), the parsed expression. If the receiver was parsed
2148 /// as a type (\c IsExpr is false), the parsed type.
2150 /// \returns True if an error occurred during parsing or semantic
2151 /// analysis, in which case the arguments do not have valid
2152 /// values. Otherwise, returns false for a successful parse.
2154 /// objc-receiver: [C++]
2155 /// 'super' [not parsed here]
2157 /// simple-type-specifier
2158 /// typename-specifier
2159 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2160 InMessageExpressionRAIIObject InMessage(*this, true);
2162 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2163 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2164 TryAnnotateTypeOrScopeToken();
2166 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2169 ExprResult Receiver = ParseExpression();
2170 if (Receiver.isInvalid())
2174 TypeOrExpr = Receiver.take();
2179 // typename-specifier
2180 // simple-type-specifier
2181 // expression (that starts with one of the above)
2182 DeclSpec DS(AttrFactory);
2183 ParseCXXSimpleTypeSpecifier(DS);
2185 if (Tok.is(tok::l_paren)) {
2186 // If we see an opening parentheses at this point, we are
2187 // actually parsing an expression that starts with a
2188 // function-style cast, e.g.,
2190 // postfix-expression:
2191 // simple-type-specifier ( expression-list [opt] )
2192 // typename-specifier ( expression-list [opt] )
2194 // Parse the remainder of this case, then the (optional)
2195 // postfix-expression suffix, followed by the (optional)
2196 // right-hand side of the binary expression. We have an
2198 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2199 if (!Receiver.isInvalid())
2200 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
2201 if (!Receiver.isInvalid())
2202 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
2203 if (Receiver.isInvalid())
2207 TypeOrExpr = Receiver.take();
2211 // We have a class message. Turn the simple-type-specifier or
2212 // typename-specifier we parsed into a type and parse the
2213 // remainder of the class message.
2214 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2215 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2216 if (Type.isInvalid())
2220 TypeOrExpr = Type.get().getAsOpaquePtr();
2224 /// \brief Determine whether the parser is currently referring to a an
2225 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2227 /// This routine will only return true for a subset of valid message-send
2229 bool Parser::isSimpleObjCMessageExpression() {
2230 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2231 "Incorrect start for isSimpleObjCMessageExpression");
2232 return GetLookAheadToken(1).is(tok::identifier) &&
2233 GetLookAheadToken(2).is(tok::identifier);
2236 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2237 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2238 InMessageExpression)
2244 if (Tok.is(tok::annot_typename))
2245 Type = getTypeAnnotation(Tok);
2246 else if (Tok.is(tok::identifier))
2247 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2252 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2253 const Token &AfterNext = GetLookAheadToken(2);
2254 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2255 if (Tok.is(tok::identifier))
2256 TryAnnotateTypeOrScopeToken();
2258 return Tok.is(tok::annot_typename);
2265 /// objc-message-expr:
2266 /// '[' objc-receiver objc-message-args ']'
2268 /// objc-receiver: [C]
2274 ExprResult Parser::ParseObjCMessageExpression() {
2275 assert(Tok.is(tok::l_square) && "'[' expected");
2276 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2278 if (Tok.is(tok::code_completion)) {
2279 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2284 InMessageExpressionRAIIObject InMessage(*this, true);
2286 if (getLangOpts().CPlusPlus) {
2287 // We completely separate the C and C++ cases because C++ requires
2288 // more complicated (read: slower) parsing.
2290 // Handle send to super.
2291 // FIXME: This doesn't benefit from the same typo-correction we
2292 // get in Objective-C.
2293 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2294 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2295 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2298 // Parse the receiver, which is either a type or an expression.
2300 void *TypeOrExpr = NULL;
2301 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2302 SkipUntil(tok::r_square);
2307 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2309 static_cast<Expr*>(TypeOrExpr));
2311 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2312 ParsedType::getFromOpaquePtr(TypeOrExpr),
2316 if (Tok.is(tok::identifier)) {
2317 IdentifierInfo *Name = Tok.getIdentifierInfo();
2318 SourceLocation NameLoc = Tok.getLocation();
2319 ParsedType ReceiverType;
2320 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2321 Name == Ident_super,
2322 NextToken().is(tok::period),
2324 case Sema::ObjCSuperMessage:
2325 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2328 case Sema::ObjCClassMessage:
2329 if (!ReceiverType) {
2330 SkipUntil(tok::r_square);
2334 ConsumeToken(); // the type name
2336 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2339 case Sema::ObjCInstanceMessage:
2340 // Fall through to parse an expression.
2345 // Otherwise, an arbitrary expression can be the receiver of a send.
2346 ExprResult Res(ParseExpression());
2347 if (Res.isInvalid()) {
2348 SkipUntil(tok::r_square);
2352 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2353 ParsedType(), Res.take());
2356 /// \brief Parse the remainder of an Objective-C message following the
2357 /// '[' objc-receiver.
2359 /// This routine handles sends to super, class messages (sent to a
2360 /// class name), and instance messages (sent to an object), and the
2361 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2362 /// ReceiverExpr, respectively. Only one of these parameters may have
2365 /// \param LBracLoc The location of the opening '['.
2367 /// \param SuperLoc If this is a send to 'super', the location of the
2368 /// 'super' keyword that indicates a send to the superclass.
2370 /// \param ReceiverType If this is a class message, the type of the
2371 /// class we are sending a message to.
2373 /// \param ReceiverExpr If this is an instance message, the expression
2374 /// used to compute the receiver object.
2376 /// objc-message-args:
2378 /// objc-keywordarg-list
2380 /// objc-keywordarg-list:
2382 /// objc-keywordarg-list objc-keywordarg
2384 /// objc-keywordarg:
2385 /// selector-name[opt] ':' objc-keywordexpr
2387 /// objc-keywordexpr:
2388 /// nonempty-expr-list
2390 /// nonempty-expr-list:
2391 /// assignment-expression
2392 /// nonempty-expr-list , assignment-expression
2395 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2396 SourceLocation SuperLoc,
2397 ParsedType ReceiverType,
2398 ExprArg ReceiverExpr) {
2399 InMessageExpressionRAIIObject InMessage(*this, true);
2401 if (Tok.is(tok::code_completion)) {
2402 if (SuperLoc.isValid())
2403 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2405 else if (ReceiverType)
2406 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2409 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2415 // Parse objc-selector
2417 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2419 SmallVector<IdentifierInfo *, 12> KeyIdents;
2420 SmallVector<SourceLocation, 12> KeyLocs;
2421 ExprVector KeyExprs(Actions);
2423 if (Tok.is(tok::colon)) {
2425 // Each iteration parses a single keyword argument.
2426 KeyIdents.push_back(selIdent);
2427 KeyLocs.push_back(Loc);
2429 if (Tok.isNot(tok::colon)) {
2430 Diag(Tok, diag::err_expected_colon);
2431 // We must manually skip to a ']', otherwise the expression skipper will
2432 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2433 // the enclosing expression.
2434 SkipUntil(tok::r_square);
2438 ConsumeToken(); // Eat the ':'.
2439 /// Parse the expression after ':'
2441 if (Tok.is(tok::code_completion)) {
2442 if (SuperLoc.isValid())
2443 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2446 /*AtArgumentEpression=*/true);
2447 else if (ReceiverType)
2448 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2451 /*AtArgumentEpression=*/true);
2453 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2456 /*AtArgumentEpression=*/true);
2462 ExprResult Res(ParseAssignmentExpression());
2463 if (Res.isInvalid()) {
2464 // We must manually skip to a ']', otherwise the expression skipper will
2465 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2466 // the enclosing expression.
2467 SkipUntil(tok::r_square);
2471 // We have a valid expression.
2472 KeyExprs.push_back(Res.release());
2474 // Code completion after each argument.
2475 if (Tok.is(tok::code_completion)) {
2476 if (SuperLoc.isValid())
2477 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2480 /*AtArgumentEpression=*/false);
2481 else if (ReceiverType)
2482 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2485 /*AtArgumentEpression=*/false);
2487 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2490 /*AtArgumentEpression=*/false);
2495 // Check for another keyword selector.
2496 selIdent = ParseObjCSelectorPiece(Loc);
2497 if (!selIdent && Tok.isNot(tok::colon))
2499 // We have a selector or a colon, continue parsing.
2501 // Parse the, optional, argument list, comma separated.
2502 while (Tok.is(tok::comma)) {
2503 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2504 /// Parse the expression after ','
2505 ExprResult Res(ParseAssignmentExpression());
2506 if (Res.isInvalid()) {
2507 if (Tok.is(tok::colon)) {
2508 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2509 FixItHint::CreateRemoval(commaLoc);
2511 // We must manually skip to a ']', otherwise the expression skipper will
2512 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2513 // the enclosing expression.
2514 SkipUntil(tok::r_square);
2518 // We have a valid expression.
2519 KeyExprs.push_back(Res.release());
2521 } else if (!selIdent) {
2522 Diag(Tok, diag::err_expected_ident); // missing selector name.
2524 // We must manually skip to a ']', otherwise the expression skipper will
2525 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2526 // the enclosing expression.
2527 SkipUntil(tok::r_square);
2531 if (Tok.isNot(tok::r_square)) {
2532 if (Tok.is(tok::identifier))
2533 Diag(Tok, diag::err_expected_colon);
2535 Diag(Tok, diag::err_expected_rsquare);
2536 // We must manually skip to a ']', otherwise the expression skipper will
2537 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2538 // the enclosing expression.
2539 SkipUntil(tok::r_square);
2543 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2545 unsigned nKeys = KeyIdents.size();
2547 KeyIdents.push_back(selIdent);
2548 KeyLocs.push_back(Loc);
2550 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2552 if (SuperLoc.isValid())
2553 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2554 LBracLoc, KeyLocs, RBracLoc,
2555 MultiExprArg(Actions,
2558 else if (ReceiverType)
2559 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2560 LBracLoc, KeyLocs, RBracLoc,
2561 MultiExprArg(Actions,
2564 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2565 LBracLoc, KeyLocs, RBracLoc,
2566 MultiExprArg(Actions,
2571 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2572 ExprResult Res(ParseStringLiteralExpression());
2573 if (Res.isInvalid()) return move(Res);
2575 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2576 // expressions. At this point, we know that the only valid thing that starts
2577 // with '@' is an @"".
2578 SmallVector<SourceLocation, 4> AtLocs;
2579 ExprVector AtStrings(Actions);
2580 AtLocs.push_back(AtLoc);
2581 AtStrings.push_back(Res.release());
2583 while (Tok.is(tok::at)) {
2584 AtLocs.push_back(ConsumeToken()); // eat the @.
2586 // Invalid unless there is a string literal.
2587 if (!isTokenStringLiteral())
2588 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2590 ExprResult Lit(ParseStringLiteralExpression());
2591 if (Lit.isInvalid())
2594 AtStrings.push_back(Lit.release());
2597 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2601 /// ParseObjCBooleanLiteral -
2602 /// objc-scalar-literal : '@' boolean-keyword
2604 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2606 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2608 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2609 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2612 /// ParseObjCCharacterLiteral -
2613 /// objc-scalar-literal : '@' character-literal
2615 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2616 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2617 if (Lit.isInvalid()) {
2620 ConsumeToken(); // Consume the literal token.
2621 return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2624 /// ParseObjCNumericLiteral -
2625 /// objc-scalar-literal : '@' scalar-literal
2627 /// scalar-literal : | numeric-constant /* any numeric constant. */
2629 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2630 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2631 if (Lit.isInvalid()) {
2634 ConsumeToken(); // Consume the literal token.
2635 return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2638 /// ParseObjCBoxedExpr -
2639 /// objc-box-expression:
2640 /// @( assignment-expression )
2642 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2643 if (Tok.isNot(tok::l_paren))
2644 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2646 BalancedDelimiterTracker T(*this, tok::l_paren);
2648 ExprResult ValueExpr(ParseAssignmentExpression());
2649 if (T.consumeClose())
2652 if (ValueExpr.isInvalid())
2655 // Wrap the sub-expression in a parenthesized expression, to distinguish
2656 // a boxed expression from a literal.
2657 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2658 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take());
2659 return Owned(Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2663 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2664 ExprVector ElementExprs(Actions); // array elements.
2665 ConsumeBracket(); // consume the l_square.
2667 while (Tok.isNot(tok::r_square)) {
2668 // Parse list of array element expressions (all must be id types).
2669 ExprResult Res(ParseAssignmentExpression());
2670 if (Res.isInvalid()) {
2671 // We must manually skip to a ']', otherwise the expression skipper will
2672 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2673 // the enclosing expression.
2674 SkipUntil(tok::r_square);
2678 // Parse the ellipsis that indicates a pack expansion.
2679 if (Tok.is(tok::ellipsis))
2680 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2681 if (Res.isInvalid())
2684 ElementExprs.push_back(Res.release());
2686 if (Tok.is(tok::comma))
2687 ConsumeToken(); // Eat the ','.
2688 else if (Tok.isNot(tok::r_square))
2689 return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
2691 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2692 MultiExprArg Args(Actions, ElementExprs.take(), ElementExprs.size());
2693 return Owned(Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args));
2696 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2697 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2698 ConsumeBrace(); // consume the l_square.
2699 while (Tok.isNot(tok::r_brace)) {
2700 // Parse the comma separated key : value expressions.
2703 ColonProtectionRAIIObject X(*this);
2704 KeyExpr = ParseAssignmentExpression();
2705 if (KeyExpr.isInvalid()) {
2706 // We must manually skip to a '}', otherwise the expression skipper will
2707 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2708 // the enclosing expression.
2709 SkipUntil(tok::r_brace);
2710 return move(KeyExpr);
2714 if (Tok.is(tok::colon)) {
2717 return ExprError(Diag(Tok, diag::err_expected_colon));
2720 ExprResult ValueExpr(ParseAssignmentExpression());
2721 if (ValueExpr.isInvalid()) {
2722 // We must manually skip to a '}', otherwise the expression skipper will
2723 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2724 // the enclosing expression.
2725 SkipUntil(tok::r_brace);
2726 return move(ValueExpr);
2729 // Parse the ellipsis that designates this as a pack expansion.
2730 SourceLocation EllipsisLoc;
2731 if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
2732 EllipsisLoc = ConsumeToken();
2734 // We have a valid expression. Collect it in a vector so we can
2735 // build the argument list.
2736 ObjCDictionaryElement Element = {
2737 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, llvm::Optional<unsigned>()
2739 Elements.push_back(Element);
2741 if (Tok.is(tok::comma))
2742 ConsumeToken(); // Eat the ','.
2743 else if (Tok.isNot(tok::r_brace))
2744 return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
2746 SourceLocation EndLoc = ConsumeBrace();
2748 // Create the ObjCDictionaryLiteral.
2749 return Owned(Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2754 /// objc-encode-expression:
2755 /// @encode ( type-name )
2757 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2758 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2760 SourceLocation EncLoc = ConsumeToken();
2762 if (Tok.isNot(tok::l_paren))
2763 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2765 BalancedDelimiterTracker T(*this, tok::l_paren);
2768 TypeResult Ty = ParseTypeName();
2775 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc,
2776 T.getOpenLocation(), Ty.get(),
2777 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_ident));
2795 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2796 SourceLocation ProtoIdLoc = ConsumeToken();
2800 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2801 T.getOpenLocation(),
2803 T.getCloseLocation()));
2806 /// objc-selector-expression
2807 /// @selector '(' objc-keyword-selector ')'
2808 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2809 SourceLocation SelectorLoc = ConsumeToken();
2811 if (Tok.isNot(tok::l_paren))
2812 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2814 SmallVector<IdentifierInfo *, 12> KeyIdents;
2815 SourceLocation sLoc;
2817 BalancedDelimiterTracker T(*this, tok::l_paren);
2820 if (Tok.is(tok::code_completion)) {
2821 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2827 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2828 if (!SelIdent && // missing selector name.
2829 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2830 return ExprError(Diag(Tok, diag::err_expected_ident));
2832 KeyIdents.push_back(SelIdent);
2833 unsigned nColons = 0;
2834 if (Tok.isNot(tok::r_paren)) {
2836 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2838 KeyIdents.push_back(0);
2839 } else if (Tok.isNot(tok::colon))
2840 return ExprError(Diag(Tok, diag::err_expected_colon));
2843 ConsumeToken(); // Eat the ':' or '::'.
2844 if (Tok.is(tok::r_paren))
2847 if (Tok.is(tok::code_completion)) {
2848 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
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))
2863 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2864 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2865 T.getOpenLocation(),
2866 T.getCloseLocation()));
2869 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2870 // MCDecl might be null due to error in method or c-function prototype, etc.
2871 Decl *MCDecl = LM.D;
2872 bool skip = MCDecl &&
2873 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2874 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2878 // Save the current token position.
2879 SourceLocation OrigLoc = Tok.getLocation();
2881 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2882 // Append the current token at the end of the new token stream so that it
2883 // doesn't get lost.
2884 LM.Toks.push_back(Tok);
2885 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2887 // Consume the previously pushed token.
2890 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2891 Tok.is(tok::colon)) &&
2892 "Inline objective-c method not starting with '{' or 'try' or ':'");
2893 // Enter a scope for the method or c-fucntion body.
2894 ParseScope BodyScope(this,
2896 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2897 : Scope::FnScope|Scope::DeclScope);
2899 // Tell the actions module that we have entered a method or c-function definition
2900 // with the specified Declarator for the method/function.
2902 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2904 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2905 if (Tok.is(tok::kw_try))
2906 MCDecl = ParseFunctionTryBlock(MCDecl, BodyScope);
2908 if (Tok.is(tok::colon))
2909 ParseConstructorInitializer(MCDecl);
2910 MCDecl = ParseFunctionStatementBody(MCDecl, BodyScope);
2913 if (Tok.getLocation() != OrigLoc) {
2914 // Due to parsing error, we either went over the cached tokens or
2915 // there are still cached tokens left. If it's the latter case skip the
2917 // Since this is an uncommon situation that should be avoided, use the
2918 // expensive isBeforeInTranslationUnit call.
2919 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2921 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))