1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Objective-C portions of the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Sema/DeclSpec.h"
19 #include "clang/Sema/PrettyDeclStackTrace.h"
20 #include "clang/Sema/Scope.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 using namespace clang;
25 /// Skips attributes after an Objective-C @ directive. Emits a diagnostic.
26 void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) {
27 ParsedAttributes attrs(AttrFactory);
28 if (Tok.is(tok::kw___attribute)) {
29 if (Kind == tok::objc_interface || Kind == tok::objc_protocol)
30 Diag(Tok, diag::err_objc_postfix_attribute_hint)
31 << (Kind == tok::objc_protocol);
33 Diag(Tok, diag::err_objc_postfix_attribute);
34 ParseGNUAttributes(attrs);
38 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
39 /// external-declaration: [C99 6.9]
40 /// [OBJC] objc-class-definition
41 /// [OBJC] objc-class-declaration
42 /// [OBJC] objc-alias-declaration
43 /// [OBJC] objc-protocol-definition
44 /// [OBJC] objc-method-definition
46 Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() {
47 SourceLocation AtLoc = ConsumeToken(); // the "@"
49 if (Tok.is(tok::code_completion)) {
50 Actions.CodeCompleteObjCAtDirective(getCurScope());
52 return DeclGroupPtrTy();
56 switch (Tok.getObjCKeywordID()) {
58 return ParseObjCAtClassDeclaration(AtLoc);
59 case tok::objc_interface: {
60 ParsedAttributes attrs(AttrFactory);
61 SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
64 case tok::objc_protocol: {
65 ParsedAttributes attrs(AttrFactory);
66 return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
68 case tok::objc_implementation:
69 return ParseObjCAtImplementationDeclaration(AtLoc);
71 return ParseObjCAtEndDeclaration(AtLoc);
72 case tok::objc_compatibility_alias:
73 SingleDecl = ParseObjCAtAliasDeclaration(AtLoc);
75 case tok::objc_synthesize:
76 SingleDecl = ParseObjCPropertySynthesize(AtLoc);
78 case tok::objc_dynamic:
79 SingleDecl = ParseObjCPropertyDynamic(AtLoc);
81 case tok::objc_import:
82 if (getLangOpts().Modules)
83 return ParseModuleImport(AtLoc);
88 Diag(AtLoc, diag::err_unexpected_at);
93 return Actions.ConvertDeclToDeclGroup(SingleDecl);
97 /// objc-class-declaration:
98 /// '@' 'class' identifier-list ';'
100 Parser::DeclGroupPtrTy
101 Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
102 ConsumeToken(); // the identifier "class"
103 SmallVector<IdentifierInfo *, 8> ClassNames;
104 SmallVector<SourceLocation, 8> ClassLocs;
108 MaybeSkipAttributes(tok::objc_class);
109 if (Tok.isNot(tok::identifier)) {
110 Diag(Tok, diag::err_expected_ident);
111 SkipUntil(tok::semi);
112 return Actions.ConvertDeclToDeclGroup(0);
114 ClassNames.push_back(Tok.getIdentifierInfo());
115 ClassLocs.push_back(Tok.getLocation());
118 if (Tok.isNot(tok::comma))
125 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
126 return Actions.ConvertDeclToDeclGroup(0);
128 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
133 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
135 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
136 if (ock == Sema::OCK_None)
139 Decl *Decl = Actions.getObjCDeclContext();
140 if (CurParsedObjCImpl) {
141 CurParsedObjCImpl->finish(AtLoc);
143 Actions.ActOnAtEnd(getCurScope(), AtLoc);
145 Diag(AtLoc, diag::err_objc_missing_end)
146 << FixItHint::CreateInsertion(AtLoc, "@end\n");
148 Diag(Decl->getLocStart(), diag::note_objc_container_start)
154 /// objc-class-interface-attributes[opt] objc-class-interface
155 /// objc-category-interface
157 /// objc-class-interface:
158 /// '@' 'interface' identifier objc-superclass[opt]
159 /// objc-protocol-refs[opt]
160 /// objc-class-instance-variables[opt]
161 /// objc-interface-decl-list
164 /// objc-category-interface:
165 /// '@' 'interface' identifier '(' identifier[opt] ')'
166 /// objc-protocol-refs[opt]
167 /// objc-interface-decl-list
173 /// objc-class-interface-attributes:
174 /// __attribute__((visibility("default")))
175 /// __attribute__((visibility("hidden")))
176 /// __attribute__((deprecated))
177 /// __attribute__((unavailable))
178 /// __attribute__((objc_exception)) - used by NSException on 64-bit
179 /// __attribute__((objc_root_class))
181 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
182 ParsedAttributes &attrs) {
183 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
184 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
185 CheckNestedObjCContexts(AtLoc);
186 ConsumeToken(); // the "interface" identifier
188 // Code completion after '@interface'.
189 if (Tok.is(tok::code_completion)) {
190 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
195 MaybeSkipAttributes(tok::objc_interface);
197 if (Tok.isNot(tok::identifier)) {
198 Diag(Tok, diag::err_expected_ident); // missing class or category name.
202 // We have a class or category name - consume it.
203 IdentifierInfo *nameId = Tok.getIdentifierInfo();
204 SourceLocation nameLoc = ConsumeToken();
205 if (Tok.is(tok::l_paren) &&
206 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
208 BalancedDelimiterTracker T(*this, tok::l_paren);
211 SourceLocation categoryLoc;
212 IdentifierInfo *categoryId = 0;
213 if (Tok.is(tok::code_completion)) {
214 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
219 // For ObjC2, the category name is optional (not an error).
220 if (Tok.is(tok::identifier)) {
221 categoryId = Tok.getIdentifierInfo();
222 categoryLoc = ConsumeToken();
224 else if (!getLangOpts().ObjC2) {
225 Diag(Tok, diag::err_expected_ident); // missing category name.
230 if (T.getCloseLocation().isInvalid())
233 if (!attrs.empty()) { // categories don't support attributes.
234 Diag(nameLoc, diag::err_objc_no_attributes_on_category);
238 // Next, we need to check for any protocol references.
239 SourceLocation LAngleLoc, EndProtoLoc;
240 SmallVector<Decl *, 8> ProtocolRefs;
241 SmallVector<SourceLocation, 8> ProtocolLocs;
242 if (Tok.is(tok::less) &&
243 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
244 LAngleLoc, EndProtoLoc))
248 Actions.ActOnStartCategoryInterface(AtLoc,
250 categoryId, categoryLoc,
256 if (Tok.is(tok::l_brace))
257 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc);
259 ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
262 // Parse a class interface.
263 IdentifierInfo *superClassId = 0;
264 SourceLocation superClassLoc;
266 if (Tok.is(tok::colon)) { // a super class is specified.
269 // Code completion of superclass names.
270 if (Tok.is(tok::code_completion)) {
271 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
276 if (Tok.isNot(tok::identifier)) {
277 Diag(Tok, diag::err_expected_ident); // missing super class name.
280 superClassId = Tok.getIdentifierInfo();
281 superClassLoc = ConsumeToken();
283 // Next, we need to check for any protocol references.
284 SmallVector<Decl *, 8> ProtocolRefs;
285 SmallVector<SourceLocation, 8> ProtocolLocs;
286 SourceLocation LAngleLoc, EndProtoLoc;
287 if (Tok.is(tok::less) &&
288 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
289 LAngleLoc, EndProtoLoc))
292 if (Tok.isNot(tok::less))
293 Actions.ActOnTypedefedProtocols(ProtocolRefs, superClassId, superClassLoc);
296 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
297 superClassId, superClassLoc,
298 ProtocolRefs.data(), ProtocolRefs.size(),
300 EndProtoLoc, attrs.getList());
302 if (Tok.is(tok::l_brace))
303 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
305 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
309 /// The Objective-C property callback. This should be defined where
310 /// it's used, but instead it's been lifted to here to support VS2005.
311 struct Parser::ObjCPropertyCallback : FieldCallback {
313 virtual void anchor();
316 SmallVectorImpl<Decl *> &Props;
318 SourceLocation AtLoc;
319 SourceLocation LParenLoc;
320 tok::ObjCKeywordKind MethodImplKind;
322 ObjCPropertyCallback(Parser &P,
323 SmallVectorImpl<Decl *> &Props,
324 ObjCDeclSpec &OCDS, SourceLocation AtLoc,
325 SourceLocation LParenLoc,
326 tok::ObjCKeywordKind MethodImplKind) :
327 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
328 MethodImplKind(MethodImplKind) {
331 void invoke(ParsingFieldDeclarator &FD) {
332 if (FD.D.getIdentifier() == 0) {
333 P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
334 << FD.D.getSourceRange();
337 if (FD.BitfieldSize) {
338 P.Diag(AtLoc, diag::err_objc_property_bitfield)
339 << FD.D.getSourceRange();
343 // Install the property declarator into interfaceDecl.
344 IdentifierInfo *SelName =
345 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
348 P.PP.getSelectorTable().getNullarySelector(SelName);
349 IdentifierInfo *SetterName = OCDS.getSetterName();
352 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
355 SelectorTable::constructSetterSelector(P.PP.getIdentifierTable(),
356 P.PP.getSelectorTable(),
357 FD.D.getIdentifier());
358 bool isOverridingProperty = false;
360 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
362 GetterSel, SetterSel,
363 &isOverridingProperty,
365 if (!isOverridingProperty)
366 Props.push_back(Property);
368 FD.complete(Property);
372 void Parser::ObjCPropertyCallback::anchor() {
375 /// objc-interface-decl-list:
377 /// objc-interface-decl-list objc-property-decl [OBJC2]
378 /// objc-interface-decl-list objc-method-requirement [OBJC2]
379 /// objc-interface-decl-list objc-method-proto ';'
380 /// objc-interface-decl-list declaration
381 /// objc-interface-decl-list ';'
383 /// objc-method-requirement: [OBJC2]
387 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
389 SmallVector<Decl *, 32> allMethods;
390 SmallVector<Decl *, 16> allProperties;
391 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
392 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
397 // If this is a method prototype, parse it.
398 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
399 if (Decl *methodPrototype =
400 ParseObjCMethodPrototype(MethodImplKind, false))
401 allMethods.push_back(methodPrototype);
402 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
403 // method definitions.
404 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
405 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
406 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
407 if (Tok.is(tok::semi))
412 if (Tok.is(tok::l_paren)) {
413 Diag(Tok, diag::err_expected_minus_or_plus);
414 ParseObjCMethodDecl(Tok.getLocation(),
416 MethodImplKind, false);
419 // Ignore excess semicolons.
420 if (Tok.is(tok::semi)) {
425 // If we got to the end of the file, exit the loop.
426 if (Tok.is(tok::eof))
429 // Code completion within an Objective-C interface.
430 if (Tok.is(tok::code_completion)) {
431 Actions.CodeCompleteOrdinaryName(getCurScope(),
432 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
433 : Sema::PCC_ObjCInterface);
434 return cutOffParsing();
437 // If we don't have an @ directive, parse it as a function definition.
438 if (Tok.isNot(tok::at)) {
439 // The code below does not consume '}'s because it is afraid of eating the
440 // end of a namespace. Because of the way this code is structured, an
441 // erroneous r_brace would cause an infinite loop if not handled here.
442 if (Tok.is(tok::r_brace))
444 ParsedAttributesWithRange attrs(AttrFactory);
445 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
449 // Otherwise, we have an @ directive, eat the @.
450 SourceLocation AtLoc = ConsumeToken(); // the "@"
451 if (Tok.is(tok::code_completion)) {
452 Actions.CodeCompleteObjCAtDirective(getCurScope());
453 return cutOffParsing();
456 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
458 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
459 AtEnd.setBegin(AtLoc);
460 AtEnd.setEnd(Tok.getLocation());
462 } else if (DirectiveKind == tok::objc_not_keyword) {
463 Diag(Tok, diag::err_objc_unknown_at);
464 SkipUntil(tok::semi);
468 // Eat the identifier.
471 switch (DirectiveKind) {
473 // FIXME: If someone forgets an @end on a protocol, this loop will
474 // continue to eat up tons of stuff and spew lots of nonsense errors. It
475 // would probably be better to bail out if we saw an @class or @interface
476 // or something like that.
477 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
478 // Skip until we see an '@' or '}' or ';'.
479 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
482 case tok::objc_implementation:
483 case tok::objc_interface:
484 Diag(AtLoc, diag::err_objc_missing_end)
485 << FixItHint::CreateInsertion(AtLoc, "@end\n");
486 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
487 << (int) Actions.getObjCContainerKind();
491 case tok::objc_required:
492 case tok::objc_optional:
493 // This is only valid on protocols.
494 // FIXME: Should this check for ObjC2 being enabled?
495 if (contextKey != tok::objc_protocol)
496 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
498 MethodImplKind = DirectiveKind;
501 case tok::objc_property:
502 if (!getLangOpts().ObjC2)
503 Diag(AtLoc, diag::err_objc_properties_require_objc2);
506 SourceLocation LParenLoc;
507 // Parse property attribute list, if any.
508 if (Tok.is(tok::l_paren)) {
509 LParenLoc = Tok.getLocation();
510 ParseObjCPropertyAttribute(OCDS);
513 ObjCPropertyCallback Callback(*this, allProperties,
514 OCDS, AtLoc, LParenLoc, MethodImplKind);
516 // Parse all the comma separated declarators.
517 ParsingDeclSpec DS(*this);
518 ParseStructDeclaration(DS, Callback);
520 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
525 // We break out of the big loop in two cases: when we see @end or when we see
526 // EOF. In the former case, eat the @end. In the later case, emit an error.
527 if (Tok.is(tok::code_completion)) {
528 Actions.CodeCompleteObjCAtDirective(getCurScope());
529 return cutOffParsing();
530 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
531 ConsumeToken(); // the "end" identifier
533 Diag(Tok, diag::err_objc_missing_end)
534 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
535 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
536 << (int) Actions.getObjCContainerKind();
537 AtEnd.setBegin(Tok.getLocation());
538 AtEnd.setEnd(Tok.getLocation());
541 // Insert collected methods declarations into the @interface object.
542 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
543 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
546 /// Parse property attribute declarations.
548 /// property-attr-decl: '(' property-attrlist ')'
549 /// property-attrlist:
550 /// property-attribute
551 /// property-attrlist ',' property-attribute
552 /// property-attribute:
553 /// getter '=' identifier
554 /// setter '=' identifier ':'
564 /// unsafe_unretained
566 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
567 assert(Tok.getKind() == tok::l_paren);
568 BalancedDelimiterTracker T(*this, tok::l_paren);
572 if (Tok.is(tok::code_completion)) {
573 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
574 return cutOffParsing();
576 const IdentifierInfo *II = Tok.getIdentifierInfo();
578 // If this is not an identifier at all, bail out early.
584 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
586 if (II->isStr("readonly"))
587 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
588 else if (II->isStr("assign"))
589 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
590 else if (II->isStr("unsafe_unretained"))
591 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
592 else if (II->isStr("readwrite"))
593 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
594 else if (II->isStr("retain"))
595 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
596 else if (II->isStr("strong"))
597 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
598 else if (II->isStr("copy"))
599 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
600 else if (II->isStr("nonatomic"))
601 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
602 else if (II->isStr("atomic"))
603 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
604 else if (II->isStr("weak"))
605 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
606 else if (II->isStr("getter") || II->isStr("setter")) {
607 bool IsSetter = II->getNameStart()[0] == 's';
609 // getter/setter require extra treatment.
610 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
611 diag::err_objc_expected_equal_for_getter;
613 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
616 if (Tok.is(tok::code_completion)) {
618 Actions.CodeCompleteObjCPropertySetter(getCurScope());
620 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
621 return cutOffParsing();
625 SourceLocation SelLoc;
626 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
629 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
631 SkipUntil(tok::r_paren, StopAtSemi);
636 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
637 DS.setSetterName(SelIdent);
639 if (ExpectAndConsume(tok::colon,
640 diag::err_expected_colon_after_setter_name, "",
644 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
645 DS.setGetterName(SelIdent);
648 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
649 SkipUntil(tok::r_paren, StopAtSemi);
653 if (Tok.isNot(tok::comma))
662 /// objc-method-proto:
663 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
664 /// objc-class-method objc-method-decl objc-method-attributes[opt]
666 /// objc-instance-method: '-'
667 /// objc-class-method: '+'
669 /// objc-method-attributes: [OBJC2]
670 /// __attribute__((deprecated))
672 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
673 bool MethodDefinition) {
674 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
676 tok::TokenKind methodType = Tok.getKind();
677 SourceLocation mLoc = ConsumeToken();
678 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
680 // Since this rule is used for both method declarations and definitions,
681 // the caller is (optionally) responsible for consuming the ';'.
688 /// enum struct union if else while do for switch case default
689 /// break continue return goto asm sizeof typeof __alignof
690 /// unsigned long const short volatile signed restrict _Complex
691 /// in out inout bycopy byref oneway int char float double void _Bool
693 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
695 switch (Tok.getKind()) {
704 case tok::exclaimequal:
708 case tok::caretequal: {
709 std::string ThisTok(PP.getSpelling(Tok));
710 if (isLetter(ThisTok[0])) {
711 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
712 Tok.setKind(tok::identifier);
713 SelectorLoc = ConsumeToken();
719 case tok::identifier:
729 case tok::kw_const_cast:
730 case tok::kw_continue:
731 case tok::kw_default:
735 case tok::kw_dynamic_cast:
738 case tok::kw_explicit:
750 case tok::kw_mutable:
751 case tok::kw_namespace:
753 case tok::kw_operator:
754 case tok::kw_private:
755 case tok::kw_protected:
757 case tok::kw_register:
758 case tok::kw_reinterpret_cast:
759 case tok::kw_restrict:
765 case tok::kw_static_cast:
768 case tok::kw_template:
773 case tok::kw_typedef:
775 case tok::kw_typename:
778 case tok::kw_unsigned:
780 case tok::kw_virtual:
782 case tok::kw_volatile:
783 case tok::kw_wchar_t:
786 case tok::kw__Complex:
787 case tok::kw___alignof:
788 IdentifierInfo *II = Tok.getIdentifierInfo();
789 SelectorLoc = ConsumeToken();
794 /// objc-for-collection-in: 'in'
796 bool Parser::isTokIdentifier_in() const {
797 // FIXME: May have to do additional look-ahead to only allow for
798 // valid tokens following an 'in'; such as an identifier, unary operators,
800 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
801 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
804 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
805 /// qualifier list and builds their bitmask representation in the input
808 /// objc-type-qualifiers:
809 /// objc-type-qualifier
810 /// objc-type-qualifiers objc-type-qualifier
812 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
813 Declarator::TheContext Context) {
814 assert(Context == Declarator::ObjCParameterContext ||
815 Context == Declarator::ObjCResultContext);
818 if (Tok.is(tok::code_completion)) {
819 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
820 Context == Declarator::ObjCParameterContext);
821 return cutOffParsing();
824 if (Tok.isNot(tok::identifier))
827 const IdentifierInfo *II = Tok.getIdentifierInfo();
828 for (unsigned i = 0; i != objc_NumQuals; ++i) {
829 if (II != ObjCTypeQuals[i])
832 ObjCDeclSpec::ObjCDeclQualifier Qual;
834 default: llvm_unreachable("Unknown decl qualifier");
835 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
836 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
837 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
838 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
839 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
840 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
842 DS.setObjCDeclQualifier(Qual);
848 // If this wasn't a recognized qualifier, bail out.
853 /// Take all the decl attributes out of the given list and add
854 /// them to the given attribute set.
855 static void takeDeclAttributes(ParsedAttributes &attrs,
856 AttributeList *list) {
858 AttributeList *cur = list;
859 list = cur->getNext();
861 if (!cur->isUsedAsTypeAttr()) {
862 // Clear out the next pointer. We're really completely
863 // destroying the internal invariants of the declarator here,
864 // but it doesn't matter because we're done with it.
871 /// takeDeclAttributes - Take all the decl attributes from the given
872 /// declarator and add them to the given list.
873 static void takeDeclAttributes(ParsedAttributes &attrs,
875 // First, take ownership of all attributes.
876 attrs.getPool().takeAllFrom(D.getAttributePool());
877 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
879 // Now actually move the attributes over.
880 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
881 takeDeclAttributes(attrs, D.getAttributes());
882 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
883 takeDeclAttributes(attrs,
884 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
888 /// '(' objc-type-qualifiers[opt] type-name ')'
889 /// '(' objc-type-qualifiers[opt] ')'
891 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
892 Declarator::TheContext context,
893 ParsedAttributes *paramAttrs) {
894 assert(context == Declarator::ObjCParameterContext ||
895 context == Declarator::ObjCResultContext);
896 assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
898 assert(Tok.is(tok::l_paren) && "expected (");
900 BalancedDelimiterTracker T(*this, tok::l_paren);
903 SourceLocation TypeStartLoc = Tok.getLocation();
904 ObjCDeclContextSwitch ObjCDC(*this);
906 // Parse type qualifiers, in, inout, etc.
907 ParseObjCTypeQualifierList(DS, context);
910 if (isTypeSpecifierQualifier()) {
911 // Parse an abstract declarator.
912 DeclSpec declSpec(AttrFactory);
913 declSpec.setObjCQualifiers(&DS);
914 ParseSpecifierQualifierList(declSpec);
915 declSpec.SetRangeEnd(Tok.getLocation());
916 Declarator declarator(declSpec, context);
917 ParseDeclarator(declarator);
919 // If that's not invalid, extract a type.
920 if (!declarator.isInvalidType()) {
921 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
922 if (!type.isInvalid())
925 // If we're parsing a parameter, steal all the decl attributes
926 // and add them to the decl spec.
927 if (context == Declarator::ObjCParameterContext)
928 takeDeclAttributes(*paramAttrs, declarator);
930 } else if (context == Declarator::ObjCResultContext &&
931 Tok.is(tok::identifier)) {
932 if (!Ident_instancetype)
933 Ident_instancetype = PP.getIdentifierInfo("instancetype");
935 if (Tok.getIdentifierInfo() == Ident_instancetype) {
936 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
941 if (Tok.is(tok::r_paren))
943 else if (Tok.getLocation() == TypeStartLoc) {
944 // If we didn't eat any tokens, then this isn't a type.
945 Diag(Tok, diag::err_expected_type);
946 SkipUntil(tok::r_paren, StopAtSemi);
948 // Otherwise, we found *something*, but didn't get a ')' in the right
949 // place. Emit an error then return what we have as the type.
955 /// objc-method-decl:
957 /// objc-keyword-selector objc-parmlist[opt]
958 /// objc-type-name objc-selector
959 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
961 /// objc-keyword-selector:
962 /// objc-keyword-decl
963 /// objc-keyword-selector objc-keyword-decl
965 /// objc-keyword-decl:
966 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
967 /// objc-selector ':' objc-keyword-attributes[opt] identifier
968 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
969 /// ':' objc-keyword-attributes[opt] identifier
972 /// objc-parms objc-ellipsis[opt]
975 /// objc-parms , parameter-declaration
980 /// objc-keyword-attributes: [OBJC2]
981 /// __attribute__((unused))
983 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
984 tok::TokenKind mType,
985 tok::ObjCKeywordKind MethodImplKind,
986 bool MethodDefinition) {
987 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
989 if (Tok.is(tok::code_completion)) {
990 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
991 /*ReturnType=*/ ParsedType());
996 // Parse the return type if present.
997 ParsedType ReturnType;
999 if (Tok.is(tok::l_paren))
1000 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
1002 // If attributes exist before the method, parse them.
1003 ParsedAttributes methodAttrs(AttrFactory);
1004 if (getLangOpts().ObjC2)
1005 MaybeParseGNUAttributes(methodAttrs);
1007 if (Tok.is(tok::code_completion)) {
1008 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1014 // Now parse the selector.
1015 SourceLocation selLoc;
1016 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1018 // An unnamed colon is valid.
1019 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1020 Diag(Tok, diag::err_expected_selector_for_method)
1021 << SourceRange(mLoc, Tok.getLocation());
1022 // Skip until we get a ; or @.
1023 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1027 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1028 if (Tok.isNot(tok::colon)) {
1029 // If attributes exist after the method, parse them.
1030 if (getLangOpts().ObjC2)
1031 MaybeParseGNUAttributes(methodAttrs);
1033 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1035 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1036 mType, DSRet, ReturnType,
1038 CParamInfo.data(), CParamInfo.size(),
1039 methodAttrs.getList(), MethodImplKind,
1040 false, MethodDefinition);
1041 PD.complete(Result);
1045 SmallVector<IdentifierInfo *, 12> KeyIdents;
1046 SmallVector<SourceLocation, 12> KeyLocs;
1047 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1048 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1049 Scope::FunctionDeclarationScope | Scope::DeclScope);
1051 AttributePool allParamAttrs(AttrFactory);
1053 ParsedAttributes paramAttrs(AttrFactory);
1054 Sema::ObjCArgInfo ArgInfo;
1056 // Each iteration parses a single keyword argument.
1057 if (Tok.isNot(tok::colon)) {
1058 Diag(Tok, diag::err_expected_colon);
1061 ConsumeToken(); // Eat the ':'.
1063 ArgInfo.Type = ParsedType();
1064 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1065 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1066 Declarator::ObjCParameterContext,
1069 // If attributes exist before the argument name, parse them.
1070 // Regardless, collect all the attributes we've parsed so far.
1071 ArgInfo.ArgAttrs = 0;
1072 if (getLangOpts().ObjC2) {
1073 MaybeParseGNUAttributes(paramAttrs);
1074 ArgInfo.ArgAttrs = paramAttrs.getList();
1077 // Code completion for the next piece of the selector.
1078 if (Tok.is(tok::code_completion)) {
1079 KeyIdents.push_back(SelIdent);
1080 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1081 mType == tok::minus,
1082 /*AtParameterName=*/true,
1083 ReturnType, KeyIdents);
1088 if (Tok.isNot(tok::identifier)) {
1089 Diag(Tok, diag::err_expected_ident); // missing argument name.
1093 ArgInfo.Name = Tok.getIdentifierInfo();
1094 ArgInfo.NameLoc = Tok.getLocation();
1095 ConsumeToken(); // Eat the identifier.
1097 ArgInfos.push_back(ArgInfo);
1098 KeyIdents.push_back(SelIdent);
1099 KeyLocs.push_back(selLoc);
1101 // Make sure the attributes persist.
1102 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1104 // Code completion for the next piece of the selector.
1105 if (Tok.is(tok::code_completion)) {
1106 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1107 mType == tok::minus,
1108 /*AtParameterName=*/false,
1109 ReturnType, KeyIdents);
1114 // Check for another keyword selector.
1115 SelIdent = ParseObjCSelectorPiece(selLoc);
1116 if (!SelIdent && Tok.isNot(tok::colon))
1119 SourceLocation ColonLoc = Tok.getLocation();
1120 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1121 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1122 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1123 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1126 // We have a selector or a colon, continue parsing.
1129 bool isVariadic = false;
1130 bool cStyleParamWarned = false;
1131 // Parse the (optional) parameter list.
1132 while (Tok.is(tok::comma)) {
1134 if (Tok.is(tok::ellipsis)) {
1139 if (!cStyleParamWarned) {
1140 Diag(Tok, diag::warn_cstyle_param);
1141 cStyleParamWarned = true;
1143 DeclSpec DS(AttrFactory);
1144 ParseDeclarationSpecifiers(DS);
1145 // Parse the declarator.
1146 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1147 ParseDeclarator(ParmDecl);
1148 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1149 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1150 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1151 ParmDecl.getIdentifierLoc(),
1156 // FIXME: Add support for optional parameter list...
1157 // If attributes exist after the method, parse them.
1158 if (getLangOpts().ObjC2)
1159 MaybeParseGNUAttributes(methodAttrs);
1161 if (KeyIdents.size() == 0)
1164 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1167 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1168 mType, DSRet, ReturnType,
1169 KeyLocs, Sel, &ArgInfos[0],
1170 CParamInfo.data(), CParamInfo.size(),
1171 methodAttrs.getList(),
1172 MethodImplKind, isVariadic, MethodDefinition);
1174 PD.complete(Result);
1178 /// objc-protocol-refs:
1179 /// '<' identifier-list '>'
1182 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1183 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1184 bool WarnOnDeclarations,
1185 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1186 assert(Tok.is(tok::less) && "expected <");
1188 LAngleLoc = ConsumeToken(); // the "<"
1190 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1193 if (Tok.is(tok::code_completion)) {
1194 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1195 ProtocolIdents.size());
1200 if (Tok.isNot(tok::identifier)) {
1201 Diag(Tok, diag::err_expected_ident);
1202 SkipUntil(tok::greater, StopAtSemi);
1205 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1206 Tok.getLocation()));
1207 ProtocolLocs.push_back(Tok.getLocation());
1210 if (Tok.isNot(tok::comma))
1216 if (ParseGreaterThanInTemplateList(EndLoc, /*ConsumeLastToken=*/true))
1219 // Convert the list of protocols identifiers into a list of protocol decls.
1220 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1221 &ProtocolIdents[0], ProtocolIdents.size(),
1226 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1227 /// in a decl-specifier-seq, starting at the '<'.
1228 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1229 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1230 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1231 SourceLocation LAngleLoc, EndProtoLoc;
1232 SmallVector<Decl *, 8> ProtocolDecl;
1233 SmallVector<SourceLocation, 8> ProtocolLocs;
1234 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1235 LAngleLoc, EndProtoLoc);
1236 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1237 ProtocolLocs.data(), LAngleLoc);
1238 if (EndProtoLoc.isValid())
1239 DS.SetRangeEnd(EndProtoLoc);
1243 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1244 BalancedDelimiterTracker &T,
1245 SmallVectorImpl<Decl *> &AllIvarDecls,
1246 bool RBraceMissing) {
1250 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1251 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1252 Actions.ActOnObjCContainerFinishDefinition();
1253 // Call ActOnFields() even if we don't have any decls. This is useful
1254 // for code rewriting tools that need to be aware of the empty list.
1255 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1257 T.getOpenLocation(), T.getCloseLocation(), 0);
1260 /// objc-class-instance-variables:
1261 /// '{' objc-instance-variable-decl-list[opt] '}'
1263 /// objc-instance-variable-decl-list:
1264 /// objc-visibility-spec
1265 /// objc-instance-variable-decl ';'
1267 /// objc-instance-variable-decl-list objc-visibility-spec
1268 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1269 /// objc-instance-variable-decl-list ';'
1271 /// objc-visibility-spec:
1275 /// @package [OBJC2]
1277 /// objc-instance-variable-decl:
1278 /// struct-declaration
1280 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1281 tok::ObjCKeywordKind visibility,
1282 SourceLocation atLoc) {
1283 assert(Tok.is(tok::l_brace) && "expected {");
1284 SmallVector<Decl *, 32> AllIvarDecls;
1286 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1287 ObjCDeclContextSwitch ObjCDC(*this);
1289 BalancedDelimiterTracker T(*this, tok::l_brace);
1291 // While we still have something to read, read the instance variables.
1292 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1293 // Each iteration of this loop reads one objc-instance-variable-decl.
1295 // Check for extraneous top-level semicolon.
1296 if (Tok.is(tok::semi)) {
1297 ConsumeExtraSemi(InstanceVariableList);
1301 // Set the default visibility to private.
1302 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1303 ConsumeToken(); // eat the @ sign
1305 if (Tok.is(tok::code_completion)) {
1306 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1307 return cutOffParsing();
1310 switch (Tok.getObjCKeywordID()) {
1311 case tok::objc_private:
1312 case tok::objc_public:
1313 case tok::objc_protected:
1314 case tok::objc_package:
1315 visibility = Tok.getObjCKeywordID();
1320 Diag(Tok, diag::err_objc_unexpected_atend);
1321 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1322 Tok.setKind(tok::at);
1325 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1326 T, AllIvarDecls, true);
1330 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1335 if (Tok.is(tok::code_completion)) {
1336 Actions.CodeCompleteOrdinaryName(getCurScope(),
1337 Sema::PCC_ObjCInstanceVariableList);
1338 return cutOffParsing();
1341 struct ObjCIvarCallback : FieldCallback {
1344 tok::ObjCKeywordKind visibility;
1345 SmallVectorImpl<Decl *> &AllIvarDecls;
1347 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1348 SmallVectorImpl<Decl *> &AllIvarDecls) :
1349 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1352 void invoke(ParsingFieldDeclarator &FD) {
1353 P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1354 // Install the declarator into the interface decl.
1356 = P.Actions.ActOnIvar(P.getCurScope(),
1357 FD.D.getDeclSpec().getSourceRange().getBegin(),
1358 FD.D, FD.BitfieldSize, visibility);
1359 P.Actions.ActOnObjCContainerFinishDefinition();
1361 AllIvarDecls.push_back(Field);
1364 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1366 // Parse all the comma separated declarators.
1367 ParsingDeclSpec DS(*this);
1368 ParseStructDeclaration(DS, Callback);
1370 if (Tok.is(tok::semi)) {
1373 Diag(Tok, diag::err_expected_semi_decl_list);
1374 // Skip to end of block or statement
1375 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1378 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1379 T, AllIvarDecls, false);
1383 /// objc-protocol-declaration:
1384 /// objc-protocol-definition
1385 /// objc-protocol-forward-reference
1387 /// objc-protocol-definition:
1388 /// \@protocol identifier
1389 /// objc-protocol-refs[opt]
1390 /// objc-interface-decl-list
1393 /// objc-protocol-forward-reference:
1394 /// \@protocol identifier-list ';'
1396 /// "\@protocol identifier ;" should be resolved as "\@protocol
1397 /// identifier-list ;": objc-interface-decl-list may not start with a
1398 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1399 Parser::DeclGroupPtrTy
1400 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1401 ParsedAttributes &attrs) {
1402 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1403 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1404 ConsumeToken(); // the "protocol" identifier
1406 if (Tok.is(tok::code_completion)) {
1407 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1409 return DeclGroupPtrTy();
1412 MaybeSkipAttributes(tok::objc_protocol);
1414 if (Tok.isNot(tok::identifier)) {
1415 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1416 return DeclGroupPtrTy();
1418 // Save the protocol name, then consume it.
1419 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1420 SourceLocation nameLoc = ConsumeToken();
1422 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1423 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1425 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1429 CheckNestedObjCContexts(AtLoc);
1431 if (Tok.is(tok::comma)) { // list of forward declarations.
1432 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1433 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1435 // Parse the list of forward declarations.
1437 ConsumeToken(); // the ','
1438 if (Tok.isNot(tok::identifier)) {
1439 Diag(Tok, diag::err_expected_ident);
1440 SkipUntil(tok::semi);
1441 return DeclGroupPtrTy();
1443 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1444 Tok.getLocation()));
1445 ConsumeToken(); // the identifier
1447 if (Tok.isNot(tok::comma))
1451 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1452 return DeclGroupPtrTy();
1454 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1456 ProtocolRefs.size(),
1460 // Last, and definitely not least, parse a protocol declaration.
1461 SourceLocation LAngleLoc, EndProtoLoc;
1463 SmallVector<Decl *, 8> ProtocolRefs;
1464 SmallVector<SourceLocation, 8> ProtocolLocs;
1465 if (Tok.is(tok::less) &&
1466 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1467 LAngleLoc, EndProtoLoc))
1468 return DeclGroupPtrTy();
1471 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1472 ProtocolRefs.data(),
1473 ProtocolRefs.size(),
1474 ProtocolLocs.data(),
1475 EndProtoLoc, attrs.getList());
1477 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1478 return Actions.ConvertDeclToDeclGroup(ProtoType);
1481 /// objc-implementation:
1482 /// objc-class-implementation-prologue
1483 /// objc-category-implementation-prologue
1485 /// objc-class-implementation-prologue:
1486 /// @implementation identifier objc-superclass[opt]
1487 /// objc-class-instance-variables[opt]
1489 /// objc-category-implementation-prologue:
1490 /// @implementation identifier ( identifier )
1491 Parser::DeclGroupPtrTy
1492 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1493 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1494 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1495 CheckNestedObjCContexts(AtLoc);
1496 ConsumeToken(); // the "implementation" identifier
1498 // Code completion after '@implementation'.
1499 if (Tok.is(tok::code_completion)) {
1500 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1502 return DeclGroupPtrTy();
1505 MaybeSkipAttributes(tok::objc_implementation);
1507 if (Tok.isNot(tok::identifier)) {
1508 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1509 return DeclGroupPtrTy();
1511 // We have a class or category name - consume it.
1512 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1513 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1514 Decl *ObjCImpDecl = 0;
1516 if (Tok.is(tok::l_paren)) {
1517 // we have a category implementation.
1519 SourceLocation categoryLoc, rparenLoc;
1520 IdentifierInfo *categoryId = 0;
1522 if (Tok.is(tok::code_completion)) {
1523 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1525 return DeclGroupPtrTy();
1528 if (Tok.is(tok::identifier)) {
1529 categoryId = Tok.getIdentifierInfo();
1530 categoryLoc = ConsumeToken();
1532 Diag(Tok, diag::err_expected_ident); // missing category name.
1533 return DeclGroupPtrTy();
1535 if (Tok.isNot(tok::r_paren)) {
1536 Diag(Tok, diag::err_expected_rparen);
1537 SkipUntil(tok::r_paren); // don't stop at ';'
1538 return DeclGroupPtrTy();
1540 rparenLoc = ConsumeParen();
1541 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1542 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1543 AttributeFactory attr;
1545 (void)ParseObjCProtocolQualifiers(DS);
1547 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1548 AtLoc, nameId, nameLoc, categoryId,
1552 // We have a class implementation
1553 SourceLocation superClassLoc;
1554 IdentifierInfo *superClassId = 0;
1555 if (Tok.is(tok::colon)) {
1556 // We have a super class
1558 if (Tok.isNot(tok::identifier)) {
1559 Diag(Tok, diag::err_expected_ident); // missing super class name.
1560 return DeclGroupPtrTy();
1562 superClassId = Tok.getIdentifierInfo();
1563 superClassLoc = ConsumeToken(); // Consume super class name
1565 ObjCImpDecl = Actions.ActOnStartClassImplementation(
1566 AtLoc, nameId, nameLoc,
1567 superClassId, superClassLoc);
1569 if (Tok.is(tok::l_brace)) // we have ivars
1570 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
1571 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1572 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1574 AttributeFactory attr;
1576 (void)ParseObjCProtocolQualifiers(DS);
1579 assert(ObjCImpDecl);
1581 SmallVector<Decl *, 8> DeclsInGroup;
1584 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1585 while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
1586 ParsedAttributesWithRange attrs(AttrFactory);
1587 MaybeParseCXX11Attributes(attrs);
1588 MaybeParseMicrosoftAttributes(attrs);
1589 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1590 DeclGroupRef DG = DGP.get();
1591 DeclsInGroup.append(DG.begin(), DG.end());
1596 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1599 Parser::DeclGroupPtrTy
1600 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1601 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1602 "ParseObjCAtEndDeclaration(): Expected @end");
1603 ConsumeToken(); // the "end" identifier
1604 if (CurParsedObjCImpl)
1605 CurParsedObjCImpl->finish(atEnd);
1607 // missing @implementation
1608 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1609 return DeclGroupPtrTy();
1612 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1614 finish(P.Tok.getLocation());
1615 if (P.Tok.is(tok::eof)) {
1616 P.Diag(P.Tok, diag::err_objc_missing_end)
1617 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1618 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1619 << Sema::OCK_Implementation;
1622 P.CurParsedObjCImpl = 0;
1623 assert(LateParsedObjCMethods.empty());
1626 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1628 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1629 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1630 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1633 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1636 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1637 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1638 false/*c-functions*/);
1640 /// \brief Clear and free the cached objc methods.
1641 for (LateParsedObjCMethodContainer::iterator
1642 I = LateParsedObjCMethods.begin(),
1643 E = LateParsedObjCMethods.end(); I != E; ++I)
1645 LateParsedObjCMethods.clear();
1650 /// compatibility-alias-decl:
1651 /// @compatibility_alias alias-name class-name ';'
1653 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1654 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1655 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1656 ConsumeToken(); // consume compatibility_alias
1657 if (Tok.isNot(tok::identifier)) {
1658 Diag(Tok, diag::err_expected_ident);
1661 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1662 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1663 if (Tok.isNot(tok::identifier)) {
1664 Diag(Tok, diag::err_expected_ident);
1667 IdentifierInfo *classId = Tok.getIdentifierInfo();
1668 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1669 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1670 "@compatibility_alias");
1671 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1675 /// property-synthesis:
1676 /// @synthesize property-ivar-list ';'
1678 /// property-ivar-list:
1680 /// property-ivar-list ',' property-ivar
1684 /// identifier '=' identifier
1686 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1687 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1688 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
1689 ConsumeToken(); // consume synthesize
1692 if (Tok.is(tok::code_completion)) {
1693 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1698 if (Tok.isNot(tok::identifier)) {
1699 Diag(Tok, diag::err_synthesized_property_name);
1700 SkipUntil(tok::semi);
1704 IdentifierInfo *propertyIvar = 0;
1705 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1706 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1707 SourceLocation propertyIvarLoc;
1708 if (Tok.is(tok::equal)) {
1709 // property '=' ivar-name
1710 ConsumeToken(); // consume '='
1712 if (Tok.is(tok::code_completion)) {
1713 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1718 if (Tok.isNot(tok::identifier)) {
1719 Diag(Tok, diag::err_expected_ident);
1722 propertyIvar = Tok.getIdentifierInfo();
1723 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1725 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1726 propertyId, propertyIvar, propertyIvarLoc);
1727 if (Tok.isNot(tok::comma))
1729 ConsumeToken(); // consume ','
1731 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1735 /// property-dynamic:
1736 /// @dynamic property-list
1740 /// property-list ',' identifier
1742 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1743 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1744 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1745 ConsumeToken(); // consume dynamic
1747 if (Tok.is(tok::code_completion)) {
1748 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1753 if (Tok.isNot(tok::identifier)) {
1754 Diag(Tok, diag::err_expected_ident);
1755 SkipUntil(tok::semi);
1759 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1760 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1761 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1762 propertyId, 0, SourceLocation());
1764 if (Tok.isNot(tok::comma))
1766 ConsumeToken(); // consume ','
1768 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1772 /// objc-throw-statement:
1773 /// throw expression[opt];
1775 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1777 ConsumeToken(); // consume throw
1778 if (Tok.isNot(tok::semi)) {
1779 Res = ParseExpression();
1780 if (Res.isInvalid()) {
1781 SkipUntil(tok::semi);
1786 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1787 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1790 /// objc-synchronized-statement:
1791 /// @synchronized '(' expression ')' compound-statement
1794 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1795 ConsumeToken(); // consume synchronized
1796 if (Tok.isNot(tok::l_paren)) {
1797 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1801 // The operand is surrounded with parentheses.
1802 ConsumeParen(); // '('
1803 ExprResult operand(ParseExpression());
1805 if (Tok.is(tok::r_paren)) {
1806 ConsumeParen(); // ')'
1808 if (!operand.isInvalid())
1809 Diag(Tok, diag::err_expected_rparen);
1811 // Skip forward until we see a left brace, but don't consume it.
1812 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1815 // Require a compound statement.
1816 if (Tok.isNot(tok::l_brace)) {
1817 if (!operand.isInvalid())
1818 Diag(Tok, diag::err_expected_lbrace);
1822 // Check the @synchronized operand now.
1823 if (!operand.isInvalid())
1824 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1826 // Parse the compound statement within a new scope.
1827 ParseScope bodyScope(this, Scope::DeclScope);
1828 StmtResult body(ParseCompoundStatementBody());
1831 // If there was a semantic or parse error earlier with the
1832 // operand, fail now.
1833 if (operand.isInvalid())
1836 if (body.isInvalid())
1837 body = Actions.ActOnNullStmt(Tok.getLocation());
1839 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1842 /// objc-try-catch-statement:
1843 /// @try compound-statement objc-catch-list[opt]
1844 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1846 /// objc-catch-list:
1847 /// @catch ( parameter-declaration ) compound-statement
1848 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1849 /// catch-parameter-declaration:
1850 /// parameter-declaration
1853 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1854 bool catch_or_finally_seen = false;
1856 ConsumeToken(); // consume try
1857 if (Tok.isNot(tok::l_brace)) {
1858 Diag(Tok, diag::err_expected_lbrace);
1861 StmtVector CatchStmts;
1862 StmtResult FinallyStmt;
1863 ParseScope TryScope(this, Scope::DeclScope);
1864 StmtResult TryBody(ParseCompoundStatementBody());
1866 if (TryBody.isInvalid())
1867 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1869 while (Tok.is(tok::at)) {
1870 // At this point, we need to lookahead to determine if this @ is the start
1871 // of an @catch or @finally. We don't want to consume the @ token if this
1872 // is an @try or @encode or something else.
1873 Token AfterAt = GetLookAheadToken(1);
1874 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1875 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1878 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1879 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1880 Decl *FirstPart = 0;
1881 ConsumeToken(); // consume catch
1882 if (Tok.is(tok::l_paren)) {
1884 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1885 if (Tok.isNot(tok::ellipsis)) {
1886 DeclSpec DS(AttrFactory);
1887 ParseDeclarationSpecifiers(DS);
1888 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1889 ParseDeclarator(ParmDecl);
1891 // Inform the actions module about the declarator, so it
1892 // gets added to the current scope.
1893 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1895 ConsumeToken(); // consume '...'
1897 SourceLocation RParenLoc;
1899 if (Tok.is(tok::r_paren))
1900 RParenLoc = ConsumeParen();
1901 else // Skip over garbage, until we get to ')'. Eat the ')'.
1902 SkipUntil(tok::r_paren, StopAtSemi);
1904 StmtResult CatchBody(true);
1905 if (Tok.is(tok::l_brace))
1906 CatchBody = ParseCompoundStatementBody();
1908 Diag(Tok, diag::err_expected_lbrace);
1909 if (CatchBody.isInvalid())
1910 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1912 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1916 if (!Catch.isInvalid())
1917 CatchStmts.push_back(Catch.release());
1920 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1924 catch_or_finally_seen = true;
1926 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1927 ConsumeToken(); // consume finally
1928 ParseScope FinallyScope(this, Scope::DeclScope);
1930 StmtResult FinallyBody(true);
1931 if (Tok.is(tok::l_brace))
1932 FinallyBody = ParseCompoundStatementBody();
1934 Diag(Tok, diag::err_expected_lbrace);
1935 if (FinallyBody.isInvalid())
1936 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1937 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1938 FinallyBody.take());
1939 catch_or_finally_seen = true;
1943 if (!catch_or_finally_seen) {
1944 Diag(atLoc, diag::err_missing_catch_finally);
1948 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1950 FinallyStmt.take());
1953 /// objc-autoreleasepool-statement:
1954 /// @autoreleasepool compound-statement
1957 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1958 ConsumeToken(); // consume autoreleasepool
1959 if (Tok.isNot(tok::l_brace)) {
1960 Diag(Tok, diag::err_expected_lbrace);
1963 // Enter a scope to hold everything within the compound stmt. Compound
1964 // statements can always hold declarations.
1965 ParseScope BodyScope(this, Scope::DeclScope);
1967 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1970 if (AutoreleasePoolBody.isInvalid())
1971 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1972 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1973 AutoreleasePoolBody.take());
1976 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1977 /// for later parsing.
1978 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1979 LexedMethod* LM = new LexedMethod(this, MDecl);
1980 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1981 CachedTokens &Toks = LM->Toks;
1982 // Begin by storing the '{' or 'try' or ':' token.
1983 Toks.push_back(Tok);
1984 if (Tok.is(tok::kw_try)) {
1986 if (Tok.is(tok::colon)) {
1987 Toks.push_back(Tok);
1989 while (Tok.isNot(tok::l_brace)) {
1990 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1991 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1994 Toks.push_back(Tok); // also store '{'
1996 else if (Tok.is(tok::colon)) {
1998 while (Tok.isNot(tok::l_brace)) {
1999 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
2000 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2002 Toks.push_back(Tok); // also store '{'
2005 // Consume everything up to (and including) the matching right brace.
2006 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2007 while (Tok.is(tok::kw_catch)) {
2008 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2009 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2013 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2015 Decl *Parser::ParseObjCMethodDefinition() {
2016 Decl *MDecl = ParseObjCMethodPrototype();
2018 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2019 "parsing Objective-C method");
2021 // parse optional ';'
2022 if (Tok.is(tok::semi)) {
2023 if (CurParsedObjCImpl) {
2024 Diag(Tok, diag::warn_semicolon_before_method_body)
2025 << FixItHint::CreateRemoval(Tok.getLocation());
2030 // We should have an opening brace now.
2031 if (Tok.isNot(tok::l_brace)) {
2032 Diag(Tok, diag::err_expected_method_body);
2034 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2035 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2037 // If we didn't find the '{', bail out.
2038 if (Tok.isNot(tok::l_brace))
2044 SkipUntil(tok::r_brace);
2048 // Allow the rest of sema to find private method decl implementations.
2049 Actions.AddAnyMethodToGlobalPool(MDecl);
2050 assert (CurParsedObjCImpl
2051 && "ParseObjCMethodDefinition - Method out of @implementation");
2052 // Consume the tokens and store them for later parsing.
2053 StashAwayMethodOrFunctionBodyTokens(MDecl);
2057 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2058 if (Tok.is(tok::code_completion)) {
2059 Actions.CodeCompleteObjCAtStatement(getCurScope());
2064 if (Tok.isObjCAtKeyword(tok::objc_try))
2065 return ParseObjCTryStmt(AtLoc);
2067 if (Tok.isObjCAtKeyword(tok::objc_throw))
2068 return ParseObjCThrowStmt(AtLoc);
2070 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2071 return ParseObjCSynchronizedStmt(AtLoc);
2073 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2074 return ParseObjCAutoreleasePoolStmt(AtLoc);
2076 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2077 if (Res.isInvalid()) {
2078 // If the expression is invalid, skip ahead to the next semicolon. Not
2079 // doing this opens us up to the possibility of infinite loops if
2080 // ParseExpression does not consume any tokens.
2081 SkipUntil(tok::semi);
2085 // Otherwise, eat the semicolon.
2086 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2087 return Actions.ActOnExprStmt(Res);
2090 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2091 switch (Tok.getKind()) {
2092 case tok::code_completion:
2093 Actions.CodeCompleteObjCAtExpression(getCurScope());
2099 tok::TokenKind Kind = Tok.getKind();
2100 SourceLocation OpLoc = ConsumeToken();
2102 if (!Tok.is(tok::numeric_constant)) {
2103 const char *Symbol = 0;
2105 case tok::minus: Symbol = "-"; break;
2106 case tok::plus: Symbol = "+"; break;
2107 default: llvm_unreachable("missing unary operator case");
2109 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2114 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2115 if (Lit.isInvalid()) {
2118 ConsumeToken(); // Consume the literal token.
2120 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
2121 if (Lit.isInvalid())
2124 return ParsePostfixExpressionSuffix(
2125 Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2128 case tok::string_literal: // primary-expression: string-literal
2129 case tok::wide_string_literal:
2130 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2132 case tok::char_constant:
2133 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2135 case tok::numeric_constant:
2136 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2138 case tok::kw_true: // Objective-C++, etc.
2139 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2140 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2141 case tok::kw_false: // Objective-C++, etc.
2142 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2143 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2146 // Objective-C array literal
2147 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2150 // Objective-C dictionary literal
2151 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2154 // Objective-C boxed expression
2155 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2158 if (Tok.getIdentifierInfo() == 0)
2159 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2161 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2162 case tok::objc_encode:
2163 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2164 case tok::objc_protocol:
2165 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2166 case tok::objc_selector:
2167 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2169 const char *str = 0;
2170 if (GetLookAheadToken(1).is(tok::l_brace)) {
2171 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2174 : (ch == 'f' ? "finally"
2175 : (ch == 'a' ? "autoreleasepool" : 0));
2178 SourceLocation kwLoc = Tok.getLocation();
2179 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2180 FixItHint::CreateReplacement(kwLoc, str));
2183 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2189 /// \brief Parse the receiver of an Objective-C++ message send.
2191 /// This routine parses the receiver of a message send in
2192 /// Objective-C++ either as a type or as an expression. Note that this
2193 /// routine must not be called to parse a send to 'super', since it
2194 /// has no way to return such a result.
2196 /// \param IsExpr Whether the receiver was parsed as an expression.
2198 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2199 /// IsExpr is true), the parsed expression. If the receiver was parsed
2200 /// as a type (\c IsExpr is false), the parsed type.
2202 /// \returns True if an error occurred during parsing or semantic
2203 /// analysis, in which case the arguments do not have valid
2204 /// values. Otherwise, returns false for a successful parse.
2206 /// objc-receiver: [C++]
2207 /// 'super' [not parsed here]
2209 /// simple-type-specifier
2210 /// typename-specifier
2211 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2212 InMessageExpressionRAIIObject InMessage(*this, true);
2214 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2215 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2216 TryAnnotateTypeOrScopeToken();
2218 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2221 ExprResult Receiver = ParseExpression();
2222 if (Receiver.isInvalid())
2226 TypeOrExpr = Receiver.take();
2231 // typename-specifier
2232 // simple-type-specifier
2233 // expression (that starts with one of the above)
2234 DeclSpec DS(AttrFactory);
2235 ParseCXXSimpleTypeSpecifier(DS);
2237 if (Tok.is(tok::l_paren)) {
2238 // If we see an opening parentheses at this point, we are
2239 // actually parsing an expression that starts with a
2240 // function-style cast, e.g.,
2242 // postfix-expression:
2243 // simple-type-specifier ( expression-list [opt] )
2244 // typename-specifier ( expression-list [opt] )
2246 // Parse the remainder of this case, then the (optional)
2247 // postfix-expression suffix, followed by the (optional)
2248 // right-hand side of the binary expression. We have an
2250 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2251 if (!Receiver.isInvalid())
2252 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
2253 if (!Receiver.isInvalid())
2254 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
2255 if (Receiver.isInvalid())
2259 TypeOrExpr = Receiver.take();
2263 // We have a class message. Turn the simple-type-specifier or
2264 // typename-specifier we parsed into a type and parse the
2265 // remainder of the class message.
2266 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2267 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2268 if (Type.isInvalid())
2272 TypeOrExpr = Type.get().getAsOpaquePtr();
2276 /// \brief Determine whether the parser is currently referring to a an
2277 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2279 /// This routine will only return true for a subset of valid message-send
2281 bool Parser::isSimpleObjCMessageExpression() {
2282 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2283 "Incorrect start for isSimpleObjCMessageExpression");
2284 return GetLookAheadToken(1).is(tok::identifier) &&
2285 GetLookAheadToken(2).is(tok::identifier);
2288 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2289 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2290 InMessageExpression)
2296 if (Tok.is(tok::annot_typename))
2297 Type = getTypeAnnotation(Tok);
2298 else if (Tok.is(tok::identifier))
2299 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2304 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2305 const Token &AfterNext = GetLookAheadToken(2);
2306 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2307 if (Tok.is(tok::identifier))
2308 TryAnnotateTypeOrScopeToken();
2310 return Tok.is(tok::annot_typename);
2317 /// objc-message-expr:
2318 /// '[' objc-receiver objc-message-args ']'
2320 /// objc-receiver: [C]
2326 ExprResult Parser::ParseObjCMessageExpression() {
2327 assert(Tok.is(tok::l_square) && "'[' expected");
2328 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2330 if (Tok.is(tok::code_completion)) {
2331 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2336 InMessageExpressionRAIIObject InMessage(*this, true);
2338 if (getLangOpts().CPlusPlus) {
2339 // We completely separate the C and C++ cases because C++ requires
2340 // more complicated (read: slower) parsing.
2342 // Handle send to super.
2343 // FIXME: This doesn't benefit from the same typo-correction we
2344 // get in Objective-C.
2345 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2346 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2347 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2350 // Parse the receiver, which is either a type or an expression.
2352 void *TypeOrExpr = NULL;
2353 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2354 SkipUntil(tok::r_square, StopAtSemi);
2359 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2361 static_cast<Expr*>(TypeOrExpr));
2363 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2364 ParsedType::getFromOpaquePtr(TypeOrExpr),
2368 if (Tok.is(tok::identifier)) {
2369 IdentifierInfo *Name = Tok.getIdentifierInfo();
2370 SourceLocation NameLoc = Tok.getLocation();
2371 ParsedType ReceiverType;
2372 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2373 Name == Ident_super,
2374 NextToken().is(tok::period),
2376 case Sema::ObjCSuperMessage:
2377 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2380 case Sema::ObjCClassMessage:
2381 if (!ReceiverType) {
2382 SkipUntil(tok::r_square, StopAtSemi);
2386 ConsumeToken(); // the type name
2388 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2391 case Sema::ObjCInstanceMessage:
2392 // Fall through to parse an expression.
2397 // Otherwise, an arbitrary expression can be the receiver of a send.
2398 ExprResult Res(ParseExpression());
2399 if (Res.isInvalid()) {
2400 SkipUntil(tok::r_square, StopAtSemi);
2404 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2405 ParsedType(), Res.take());
2408 /// \brief Parse the remainder of an Objective-C message following the
2409 /// '[' objc-receiver.
2411 /// This routine handles sends to super, class messages (sent to a
2412 /// class name), and instance messages (sent to an object), and the
2413 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2414 /// ReceiverExpr, respectively. Only one of these parameters may have
2417 /// \param LBracLoc The location of the opening '['.
2419 /// \param SuperLoc If this is a send to 'super', the location of the
2420 /// 'super' keyword that indicates a send to the superclass.
2422 /// \param ReceiverType If this is a class message, the type of the
2423 /// class we are sending a message to.
2425 /// \param ReceiverExpr If this is an instance message, the expression
2426 /// used to compute the receiver object.
2428 /// objc-message-args:
2430 /// objc-keywordarg-list
2432 /// objc-keywordarg-list:
2434 /// objc-keywordarg-list objc-keywordarg
2436 /// objc-keywordarg:
2437 /// selector-name[opt] ':' objc-keywordexpr
2439 /// objc-keywordexpr:
2440 /// nonempty-expr-list
2442 /// nonempty-expr-list:
2443 /// assignment-expression
2444 /// nonempty-expr-list , assignment-expression
2447 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2448 SourceLocation SuperLoc,
2449 ParsedType ReceiverType,
2450 ExprArg ReceiverExpr) {
2451 InMessageExpressionRAIIObject InMessage(*this, true);
2453 if (Tok.is(tok::code_completion)) {
2454 if (SuperLoc.isValid())
2455 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
2457 else if (ReceiverType)
2458 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
2461 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2467 // Parse objc-selector
2469 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2471 SmallVector<IdentifierInfo *, 12> KeyIdents;
2472 SmallVector<SourceLocation, 12> KeyLocs;
2473 ExprVector KeyExprs;
2475 if (Tok.is(tok::colon)) {
2477 // Each iteration parses a single keyword argument.
2478 KeyIdents.push_back(selIdent);
2479 KeyLocs.push_back(Loc);
2481 if (Tok.isNot(tok::colon)) {
2482 Diag(Tok, diag::err_expected_colon);
2483 // We must manually skip to a ']', otherwise the expression skipper will
2484 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2485 // the enclosing expression.
2486 SkipUntil(tok::r_square, StopAtSemi);
2490 ConsumeToken(); // Eat the ':'.
2491 /// Parse the expression after ':'
2493 if (Tok.is(tok::code_completion)) {
2494 if (SuperLoc.isValid())
2495 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2497 /*AtArgumentEpression=*/true);
2498 else if (ReceiverType)
2499 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2501 /*AtArgumentEpression=*/true);
2503 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2505 /*AtArgumentEpression=*/true);
2512 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2513 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2514 Expr = ParseBraceInitializer();
2516 Expr = ParseAssignmentExpression();
2518 ExprResult Res(Expr);
2519 if (Res.isInvalid()) {
2520 // We must manually skip to a ']', otherwise the expression skipper will
2521 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2522 // the enclosing expression.
2523 SkipUntil(tok::r_square, StopAtSemi);
2527 // We have a valid expression.
2528 KeyExprs.push_back(Res.release());
2530 // Code completion after each argument.
2531 if (Tok.is(tok::code_completion)) {
2532 if (SuperLoc.isValid())
2533 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2535 /*AtArgumentEpression=*/false);
2536 else if (ReceiverType)
2537 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2539 /*AtArgumentEpression=*/false);
2541 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2543 /*AtArgumentEpression=*/false);
2548 // Check for another keyword selector.
2549 selIdent = ParseObjCSelectorPiece(Loc);
2550 if (!selIdent && Tok.isNot(tok::colon))
2552 // We have a selector or a colon, continue parsing.
2554 // Parse the, optional, argument list, comma separated.
2555 while (Tok.is(tok::comma)) {
2556 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2557 /// Parse the expression after ','
2558 ExprResult Res(ParseAssignmentExpression());
2559 if (Res.isInvalid()) {
2560 if (Tok.is(tok::colon)) {
2561 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2562 FixItHint::CreateRemoval(commaLoc);
2564 // We must manually skip to a ']', otherwise the expression skipper will
2565 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2566 // the enclosing expression.
2567 SkipUntil(tok::r_square, StopAtSemi);
2571 // We have a valid expression.
2572 KeyExprs.push_back(Res.release());
2574 } else if (!selIdent) {
2575 Diag(Tok, diag::err_expected_ident); // missing selector name.
2577 // We must manually skip to a ']', otherwise the expression skipper will
2578 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2579 // the enclosing expression.
2580 SkipUntil(tok::r_square, StopAtSemi);
2584 if (Tok.isNot(tok::r_square)) {
2585 if (Tok.is(tok::identifier))
2586 Diag(Tok, diag::err_expected_colon);
2588 Diag(Tok, diag::err_expected_rsquare);
2589 // We must manually skip to a ']', otherwise the expression skipper will
2590 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2591 // the enclosing expression.
2592 SkipUntil(tok::r_square, StopAtSemi);
2596 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2598 unsigned nKeys = KeyIdents.size();
2600 KeyIdents.push_back(selIdent);
2601 KeyLocs.push_back(Loc);
2603 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2605 if (SuperLoc.isValid())
2606 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2607 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2608 else if (ReceiverType)
2609 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2610 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2611 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2612 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2615 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2616 ExprResult Res(ParseStringLiteralExpression());
2617 if (Res.isInvalid()) return Res;
2619 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2620 // expressions. At this point, we know that the only valid thing that starts
2621 // with '@' is an @"".
2622 SmallVector<SourceLocation, 4> AtLocs;
2623 ExprVector AtStrings;
2624 AtLocs.push_back(AtLoc);
2625 AtStrings.push_back(Res.release());
2627 while (Tok.is(tok::at)) {
2628 AtLocs.push_back(ConsumeToken()); // eat the @.
2630 // Invalid unless there is a string literal.
2631 if (!isTokenStringLiteral())
2632 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2634 ExprResult Lit(ParseStringLiteralExpression());
2635 if (Lit.isInvalid())
2638 AtStrings.push_back(Lit.release());
2641 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2645 /// ParseObjCBooleanLiteral -
2646 /// objc-scalar-literal : '@' boolean-keyword
2648 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2650 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2652 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2653 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2656 /// ParseObjCCharacterLiteral -
2657 /// objc-scalar-literal : '@' character-literal
2659 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2660 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2661 if (Lit.isInvalid()) {
2664 ConsumeToken(); // Consume the literal token.
2665 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take());
2668 /// ParseObjCNumericLiteral -
2669 /// objc-scalar-literal : '@' scalar-literal
2671 /// scalar-literal : | numeric-constant /* any numeric constant. */
2673 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2674 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2675 if (Lit.isInvalid()) {
2678 ConsumeToken(); // Consume the literal token.
2679 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take());
2682 /// ParseObjCBoxedExpr -
2683 /// objc-box-expression:
2684 /// @( assignment-expression )
2686 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2687 if (Tok.isNot(tok::l_paren))
2688 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2690 BalancedDelimiterTracker T(*this, tok::l_paren);
2692 ExprResult ValueExpr(ParseAssignmentExpression());
2693 if (T.consumeClose())
2696 if (ValueExpr.isInvalid())
2699 // Wrap the sub-expression in a parenthesized expression, to distinguish
2700 // a boxed expression from a literal.
2701 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2702 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take());
2703 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2707 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2708 ExprVector ElementExprs; // array elements.
2709 ConsumeBracket(); // consume the l_square.
2711 while (Tok.isNot(tok::r_square)) {
2712 // Parse list of array element expressions (all must be id types).
2713 ExprResult Res(ParseAssignmentExpression());
2714 if (Res.isInvalid()) {
2715 // We must manually skip to a ']', otherwise the expression skipper will
2716 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2717 // the enclosing expression.
2718 SkipUntil(tok::r_square, StopAtSemi);
2722 // Parse the ellipsis that indicates a pack expansion.
2723 if (Tok.is(tok::ellipsis))
2724 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2725 if (Res.isInvalid())
2728 ElementExprs.push_back(Res.release());
2730 if (Tok.is(tok::comma))
2731 ConsumeToken(); // Eat the ','.
2732 else if (Tok.isNot(tok::r_square))
2733 return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
2735 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2736 MultiExprArg Args(ElementExprs);
2737 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
2740 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2741 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2742 ConsumeBrace(); // consume the l_square.
2743 while (Tok.isNot(tok::r_brace)) {
2744 // Parse the comma separated key : value expressions.
2747 ColonProtectionRAIIObject X(*this);
2748 KeyExpr = ParseAssignmentExpression();
2749 if (KeyExpr.isInvalid()) {
2750 // We must manually skip to a '}', otherwise the expression skipper will
2751 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2752 // the enclosing expression.
2753 SkipUntil(tok::r_brace, StopAtSemi);
2758 if (Tok.is(tok::colon)) {
2761 Diag(Tok, diag::err_expected_colon);
2762 SkipUntil(tok::r_brace, StopAtSemi);
2766 ExprResult ValueExpr(ParseAssignmentExpression());
2767 if (ValueExpr.isInvalid()) {
2768 // We must manually skip to a '}', otherwise the expression skipper will
2769 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2770 // the enclosing expression.
2771 SkipUntil(tok::r_brace, StopAtSemi);
2775 // Parse the ellipsis that designates this as a pack expansion.
2776 SourceLocation EllipsisLoc;
2777 if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
2778 EllipsisLoc = ConsumeToken();
2780 // We have a valid expression. Collect it in a vector so we can
2781 // build the argument list.
2782 ObjCDictionaryElement Element = {
2783 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
2785 Elements.push_back(Element);
2787 if (Tok.is(tok::comma))
2788 ConsumeToken(); // Eat the ','.
2789 else if (Tok.isNot(tok::r_brace))
2790 return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
2792 SourceLocation EndLoc = ConsumeBrace();
2794 // Create the ObjCDictionaryLiteral.
2795 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2796 Elements.data(), Elements.size());
2799 /// objc-encode-expression:
2800 /// \@encode ( type-name )
2802 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2803 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2805 SourceLocation EncLoc = ConsumeToken();
2807 if (Tok.isNot(tok::l_paren))
2808 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2810 BalancedDelimiterTracker T(*this, tok::l_paren);
2813 TypeResult Ty = ParseTypeName();
2820 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
2821 Ty.get(), T.getCloseLocation());
2824 /// objc-protocol-expression
2825 /// \@protocol ( protocol-name )
2827 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2828 SourceLocation ProtoLoc = ConsumeToken();
2830 if (Tok.isNot(tok::l_paren))
2831 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2833 BalancedDelimiterTracker T(*this, tok::l_paren);
2836 if (Tok.isNot(tok::identifier))
2837 return ExprError(Diag(Tok, diag::err_expected_ident));
2839 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2840 SourceLocation ProtoIdLoc = ConsumeToken();
2844 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2845 T.getOpenLocation(), ProtoIdLoc,
2846 T.getCloseLocation());
2849 /// objc-selector-expression
2850 /// @selector '(' objc-keyword-selector ')'
2851 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2852 SourceLocation SelectorLoc = ConsumeToken();
2854 if (Tok.isNot(tok::l_paren))
2855 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2857 SmallVector<IdentifierInfo *, 12> KeyIdents;
2858 SourceLocation sLoc;
2860 BalancedDelimiterTracker T(*this, tok::l_paren);
2863 if (Tok.is(tok::code_completion)) {
2864 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2869 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2870 if (!SelIdent && // missing selector name.
2871 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2872 return ExprError(Diag(Tok, diag::err_expected_ident));
2874 KeyIdents.push_back(SelIdent);
2875 unsigned nColons = 0;
2876 if (Tok.isNot(tok::r_paren)) {
2878 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2880 KeyIdents.push_back(0);
2881 } else if (Tok.isNot(tok::colon))
2882 return ExprError(Diag(Tok, diag::err_expected_colon));
2885 ConsumeToken(); // Eat the ':' or '::'.
2886 if (Tok.is(tok::r_paren))
2889 if (Tok.is(tok::code_completion)) {
2890 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2895 // Check for another keyword selector.
2897 SelIdent = ParseObjCSelectorPiece(Loc);
2898 KeyIdents.push_back(SelIdent);
2899 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2904 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2905 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2906 T.getOpenLocation(),
2907 T.getCloseLocation());
2910 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2911 // MCDecl might be null due to error in method or c-function prototype, etc.
2912 Decl *MCDecl = LM.D;
2913 bool skip = MCDecl &&
2914 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2915 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2919 // Save the current token position.
2920 SourceLocation OrigLoc = Tok.getLocation();
2922 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2923 // Append the current token at the end of the new token stream so that it
2924 // doesn't get lost.
2925 LM.Toks.push_back(Tok);
2926 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2928 // Consume the previously pushed token.
2929 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
2931 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2932 Tok.is(tok::colon)) &&
2933 "Inline objective-c method not starting with '{' or 'try' or ':'");
2934 // Enter a scope for the method or c-fucntion body.
2935 ParseScope BodyScope(this,
2937 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2938 : Scope::FnScope|Scope::DeclScope);
2940 // Tell the actions module that we have entered a method or c-function definition
2941 // with the specified Declarator for the method/function.
2943 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2945 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2946 if (Tok.is(tok::kw_try))
2947 MCDecl = ParseFunctionTryBlock(MCDecl, BodyScope);
2949 if (Tok.is(tok::colon))
2950 ParseConstructorInitializer(MCDecl);
2951 MCDecl = ParseFunctionStatementBody(MCDecl, BodyScope);
2954 if (Tok.getLocation() != OrigLoc) {
2955 // Due to parsing error, we either went over the cached tokens or
2956 // there are still cached tokens left. If it's the latter case skip the
2958 // Since this is an uncommon situation that should be avoided, use the
2959 // expensive isBeforeInTranslationUnit call.
2960 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2962 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))