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))
293 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
294 superClassId, superClassLoc,
295 ProtocolRefs.data(), ProtocolRefs.size(),
297 EndProtoLoc, attrs.getList());
299 if (Tok.is(tok::l_brace))
300 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
302 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
306 /// The Objective-C property callback. This should be defined where
307 /// it's used, but instead it's been lifted to here to support VS2005.
308 struct Parser::ObjCPropertyCallback : FieldCallback {
310 virtual void anchor();
313 SmallVectorImpl<Decl *> &Props;
315 SourceLocation AtLoc;
316 SourceLocation LParenLoc;
317 tok::ObjCKeywordKind MethodImplKind;
319 ObjCPropertyCallback(Parser &P,
320 SmallVectorImpl<Decl *> &Props,
321 ObjCDeclSpec &OCDS, SourceLocation AtLoc,
322 SourceLocation LParenLoc,
323 tok::ObjCKeywordKind MethodImplKind) :
324 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
325 MethodImplKind(MethodImplKind) {
328 void invoke(ParsingFieldDeclarator &FD) {
329 if (FD.D.getIdentifier() == 0) {
330 P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
331 << FD.D.getSourceRange();
334 if (FD.BitfieldSize) {
335 P.Diag(AtLoc, diag::err_objc_property_bitfield)
336 << FD.D.getSourceRange();
340 // Install the property declarator into interfaceDecl.
341 IdentifierInfo *SelName =
342 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
345 P.PP.getSelectorTable().getNullarySelector(SelName);
346 IdentifierInfo *SetterName = OCDS.getSetterName();
349 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
351 SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
352 P.PP.getSelectorTable(),
353 FD.D.getIdentifier());
354 bool isOverridingProperty = false;
356 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
358 GetterSel, SetterSel,
359 &isOverridingProperty,
361 if (!isOverridingProperty)
362 Props.push_back(Property);
364 FD.complete(Property);
368 void Parser::ObjCPropertyCallback::anchor() {
371 /// objc-interface-decl-list:
373 /// objc-interface-decl-list objc-property-decl [OBJC2]
374 /// objc-interface-decl-list objc-method-requirement [OBJC2]
375 /// objc-interface-decl-list objc-method-proto ';'
376 /// objc-interface-decl-list declaration
377 /// objc-interface-decl-list ';'
379 /// objc-method-requirement: [OBJC2]
383 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
385 SmallVector<Decl *, 32> allMethods;
386 SmallVector<Decl *, 16> allProperties;
387 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
388 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
393 // If this is a method prototype, parse it.
394 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
395 if (Decl *methodPrototype =
396 ParseObjCMethodPrototype(MethodImplKind, false))
397 allMethods.push_back(methodPrototype);
398 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
399 // method definitions.
400 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
401 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
402 SkipUntil(tok::at, /*StopAtSemi=*/true, /*DontConsume=*/true);
403 if (Tok.is(tok::semi))
408 if (Tok.is(tok::l_paren)) {
409 Diag(Tok, diag::err_expected_minus_or_plus);
410 ParseObjCMethodDecl(Tok.getLocation(),
412 MethodImplKind, false);
415 // Ignore excess semicolons.
416 if (Tok.is(tok::semi)) {
421 // If we got to the end of the file, exit the loop.
422 if (Tok.is(tok::eof))
425 // Code completion within an Objective-C interface.
426 if (Tok.is(tok::code_completion)) {
427 Actions.CodeCompleteOrdinaryName(getCurScope(),
428 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
429 : Sema::PCC_ObjCInterface);
430 return cutOffParsing();
433 // If we don't have an @ directive, parse it as a function definition.
434 if (Tok.isNot(tok::at)) {
435 // The code below does not consume '}'s because it is afraid of eating the
436 // end of a namespace. Because of the way this code is structured, an
437 // erroneous r_brace would cause an infinite loop if not handled here.
438 if (Tok.is(tok::r_brace))
440 ParsedAttributesWithRange attrs(AttrFactory);
441 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
445 // Otherwise, we have an @ directive, eat the @.
446 SourceLocation AtLoc = ConsumeToken(); // the "@"
447 if (Tok.is(tok::code_completion)) {
448 Actions.CodeCompleteObjCAtDirective(getCurScope());
449 return cutOffParsing();
452 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
454 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
455 AtEnd.setBegin(AtLoc);
456 AtEnd.setEnd(Tok.getLocation());
458 } else if (DirectiveKind == tok::objc_not_keyword) {
459 Diag(Tok, diag::err_objc_unknown_at);
460 SkipUntil(tok::semi);
464 // Eat the identifier.
467 switch (DirectiveKind) {
469 // FIXME: If someone forgets an @end on a protocol, this loop will
470 // continue to eat up tons of stuff and spew lots of nonsense errors. It
471 // would probably be better to bail out if we saw an @class or @interface
472 // or something like that.
473 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
474 // Skip until we see an '@' or '}' or ';'.
475 SkipUntil(tok::r_brace, tok::at);
478 case tok::objc_implementation:
479 case tok::objc_interface:
480 Diag(AtLoc, diag::err_objc_missing_end)
481 << FixItHint::CreateInsertion(AtLoc, "@end\n");
482 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
483 << (int) Actions.getObjCContainerKind();
487 case tok::objc_required:
488 case tok::objc_optional:
489 // This is only valid on protocols.
490 // FIXME: Should this check for ObjC2 being enabled?
491 if (contextKey != tok::objc_protocol)
492 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
494 MethodImplKind = DirectiveKind;
497 case tok::objc_property:
498 if (!getLangOpts().ObjC2)
499 Diag(AtLoc, diag::err_objc_properties_require_objc2);
502 SourceLocation LParenLoc;
503 // Parse property attribute list, if any.
504 if (Tok.is(tok::l_paren)) {
505 LParenLoc = Tok.getLocation();
506 ParseObjCPropertyAttribute(OCDS);
509 ObjCPropertyCallback Callback(*this, allProperties,
510 OCDS, AtLoc, LParenLoc, MethodImplKind);
512 // Parse all the comma separated declarators.
513 ParsingDeclSpec DS(*this);
514 ParseStructDeclaration(DS, Callback);
516 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
521 // We break out of the big loop in two cases: when we see @end or when we see
522 // EOF. In the former case, eat the @end. In the later case, emit an error.
523 if (Tok.is(tok::code_completion)) {
524 Actions.CodeCompleteObjCAtDirective(getCurScope());
525 return cutOffParsing();
526 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
527 ConsumeToken(); // the "end" identifier
529 Diag(Tok, diag::err_objc_missing_end)
530 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
531 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
532 << (int) Actions.getObjCContainerKind();
533 AtEnd.setBegin(Tok.getLocation());
534 AtEnd.setEnd(Tok.getLocation());
537 // Insert collected methods declarations into the @interface object.
538 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
539 Actions.ActOnAtEnd(getCurScope(), AtEnd,
540 allMethods.data(), allMethods.size(),
541 allProperties.data(), allProperties.size(),
542 allTUVariables.data(), allTUVariables.size());
545 /// Parse property attribute declarations.
547 /// property-attr-decl: '(' property-attrlist ')'
548 /// property-attrlist:
549 /// property-attribute
550 /// property-attrlist ',' property-attribute
551 /// property-attribute:
552 /// getter '=' identifier
553 /// setter '=' identifier ':'
563 /// unsafe_unretained
565 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
566 assert(Tok.getKind() == tok::l_paren);
567 BalancedDelimiterTracker T(*this, tok::l_paren);
571 if (Tok.is(tok::code_completion)) {
572 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
573 return cutOffParsing();
575 const IdentifierInfo *II = Tok.getIdentifierInfo();
577 // If this is not an identifier at all, bail out early.
583 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
585 if (II->isStr("readonly"))
586 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
587 else if (II->isStr("assign"))
588 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
589 else if (II->isStr("unsafe_unretained"))
590 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
591 else if (II->isStr("readwrite"))
592 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
593 else if (II->isStr("retain"))
594 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
595 else if (II->isStr("strong"))
596 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
597 else if (II->isStr("copy"))
598 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
599 else if (II->isStr("nonatomic"))
600 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
601 else if (II->isStr("atomic"))
602 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
603 else if (II->isStr("weak"))
604 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
605 else if (II->isStr("getter") || II->isStr("setter")) {
606 bool IsSetter = II->getNameStart()[0] == 's';
608 // getter/setter require extra treatment.
609 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
610 diag::err_objc_expected_equal_for_getter;
612 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
615 if (Tok.is(tok::code_completion)) {
617 Actions.CodeCompleteObjCPropertySetter(getCurScope());
619 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
620 return cutOffParsing();
624 SourceLocation SelLoc;
625 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
628 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
630 SkipUntil(tok::r_paren);
635 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
636 DS.setSetterName(SelIdent);
638 if (ExpectAndConsume(tok::colon,
639 diag::err_expected_colon_after_setter_name, "",
643 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
644 DS.setGetterName(SelIdent);
647 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
648 SkipUntil(tok::r_paren);
652 if (Tok.isNot(tok::comma))
661 /// objc-method-proto:
662 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
663 /// objc-class-method objc-method-decl objc-method-attributes[opt]
665 /// objc-instance-method: '-'
666 /// objc-class-method: '+'
668 /// objc-method-attributes: [OBJC2]
669 /// __attribute__((deprecated))
671 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
672 bool MethodDefinition) {
673 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
675 tok::TokenKind methodType = Tok.getKind();
676 SourceLocation mLoc = ConsumeToken();
677 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
679 // Since this rule is used for both method declarations and definitions,
680 // the caller is (optionally) responsible for consuming the ';'.
687 /// enum struct union if else while do for switch case default
688 /// break continue return goto asm sizeof typeof __alignof
689 /// unsigned long const short volatile signed restrict _Complex
690 /// in out inout bycopy byref oneway int char float double void _Bool
692 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
694 switch (Tok.getKind()) {
703 case tok::exclaimequal:
707 case tok::caretequal: {
708 std::string ThisTok(PP.getSpelling(Tok));
709 if (isLetter(ThisTok[0])) {
710 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
711 Tok.setKind(tok::identifier);
712 SelectorLoc = ConsumeToken();
718 case tok::identifier:
728 case tok::kw_const_cast:
729 case tok::kw_continue:
730 case tok::kw_default:
734 case tok::kw_dynamic_cast:
737 case tok::kw_explicit:
749 case tok::kw_mutable:
750 case tok::kw_namespace:
752 case tok::kw_operator:
753 case tok::kw_private:
754 case tok::kw_protected:
756 case tok::kw_register:
757 case tok::kw_reinterpret_cast:
758 case tok::kw_restrict:
764 case tok::kw_static_cast:
767 case tok::kw_template:
772 case tok::kw_typedef:
774 case tok::kw_typename:
777 case tok::kw_unsigned:
779 case tok::kw_virtual:
781 case tok::kw_volatile:
782 case tok::kw_wchar_t:
785 case tok::kw__Complex:
786 case tok::kw___alignof:
787 IdentifierInfo *II = Tok.getIdentifierInfo();
788 SelectorLoc = ConsumeToken();
793 /// objc-for-collection-in: 'in'
795 bool Parser::isTokIdentifier_in() const {
796 // FIXME: May have to do additional look-ahead to only allow for
797 // valid tokens following an 'in'; such as an identifier, unary operators,
799 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
800 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
803 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
804 /// qualifier list and builds their bitmask representation in the input
807 /// objc-type-qualifiers:
808 /// objc-type-qualifier
809 /// objc-type-qualifiers objc-type-qualifier
811 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
812 Declarator::TheContext Context) {
813 assert(Context == Declarator::ObjCParameterContext ||
814 Context == Declarator::ObjCResultContext);
817 if (Tok.is(tok::code_completion)) {
818 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
819 Context == Declarator::ObjCParameterContext);
820 return cutOffParsing();
823 if (Tok.isNot(tok::identifier))
826 const IdentifierInfo *II = Tok.getIdentifierInfo();
827 for (unsigned i = 0; i != objc_NumQuals; ++i) {
828 if (II != ObjCTypeQuals[i])
831 ObjCDeclSpec::ObjCDeclQualifier Qual;
833 default: llvm_unreachable("Unknown decl qualifier");
834 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
835 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
836 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
837 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
838 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
839 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
841 DS.setObjCDeclQualifier(Qual);
847 // If this wasn't a recognized qualifier, bail out.
852 /// Take all the decl attributes out of the given list and add
853 /// them to the given attribute set.
854 static void takeDeclAttributes(ParsedAttributes &attrs,
855 AttributeList *list) {
857 AttributeList *cur = list;
858 list = cur->getNext();
860 if (!cur->isUsedAsTypeAttr()) {
861 // Clear out the next pointer. We're really completely
862 // destroying the internal invariants of the declarator here,
863 // but it doesn't matter because we're done with it.
870 /// takeDeclAttributes - Take all the decl attributes from the given
871 /// declarator and add them to the given list.
872 static void takeDeclAttributes(ParsedAttributes &attrs,
874 // First, take ownership of all attributes.
875 attrs.getPool().takeAllFrom(D.getAttributePool());
876 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
878 // Now actually move the attributes over.
879 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
880 takeDeclAttributes(attrs, D.getAttributes());
881 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
882 takeDeclAttributes(attrs,
883 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
887 /// '(' objc-type-qualifiers[opt] type-name ')'
888 /// '(' objc-type-qualifiers[opt] ')'
890 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
891 Declarator::TheContext context,
892 ParsedAttributes *paramAttrs) {
893 assert(context == Declarator::ObjCParameterContext ||
894 context == Declarator::ObjCResultContext);
895 assert((paramAttrs != 0) == (context == Declarator::ObjCParameterContext));
897 assert(Tok.is(tok::l_paren) && "expected (");
899 BalancedDelimiterTracker T(*this, tok::l_paren);
902 SourceLocation TypeStartLoc = Tok.getLocation();
903 ObjCDeclContextSwitch ObjCDC(*this);
905 // Parse type qualifiers, in, inout, etc.
906 ParseObjCTypeQualifierList(DS, context);
909 if (isTypeSpecifierQualifier()) {
910 // Parse an abstract declarator.
911 DeclSpec declSpec(AttrFactory);
912 declSpec.setObjCQualifiers(&DS);
913 ParseSpecifierQualifierList(declSpec);
914 declSpec.SetRangeEnd(Tok.getLocation());
915 Declarator declarator(declSpec, context);
916 ParseDeclarator(declarator);
918 // If that's not invalid, extract a type.
919 if (!declarator.isInvalidType()) {
920 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
921 if (!type.isInvalid())
924 // If we're parsing a parameter, steal all the decl attributes
925 // and add them to the decl spec.
926 if (context == Declarator::ObjCParameterContext)
927 takeDeclAttributes(*paramAttrs, declarator);
929 } else if (context == Declarator::ObjCResultContext &&
930 Tok.is(tok::identifier)) {
931 if (!Ident_instancetype)
932 Ident_instancetype = PP.getIdentifierInfo("instancetype");
934 if (Tok.getIdentifierInfo() == Ident_instancetype) {
935 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
940 if (Tok.is(tok::r_paren))
942 else if (Tok.getLocation() == TypeStartLoc) {
943 // If we didn't eat any tokens, then this isn't a type.
944 Diag(Tok, diag::err_expected_type);
945 SkipUntil(tok::r_paren);
947 // Otherwise, we found *something*, but didn't get a ')' in the right
948 // place. Emit an error then return what we have as the type.
954 /// objc-method-decl:
956 /// objc-keyword-selector objc-parmlist[opt]
957 /// objc-type-name objc-selector
958 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
960 /// objc-keyword-selector:
961 /// objc-keyword-decl
962 /// objc-keyword-selector objc-keyword-decl
964 /// objc-keyword-decl:
965 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
966 /// objc-selector ':' objc-keyword-attributes[opt] identifier
967 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
968 /// ':' objc-keyword-attributes[opt] identifier
971 /// objc-parms objc-ellipsis[opt]
974 /// objc-parms , parameter-declaration
979 /// objc-keyword-attributes: [OBJC2]
980 /// __attribute__((unused))
982 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
983 tok::TokenKind mType,
984 tok::ObjCKeywordKind MethodImplKind,
985 bool MethodDefinition) {
986 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
988 if (Tok.is(tok::code_completion)) {
989 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
990 /*ReturnType=*/ ParsedType());
995 // Parse the return type if present.
996 ParsedType ReturnType;
998 if (Tok.is(tok::l_paren))
999 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, 0);
1001 // If attributes exist before the method, parse them.
1002 ParsedAttributes methodAttrs(AttrFactory);
1003 if (getLangOpts().ObjC2)
1004 MaybeParseGNUAttributes(methodAttrs);
1006 if (Tok.is(tok::code_completion)) {
1007 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1013 // Now parse the selector.
1014 SourceLocation selLoc;
1015 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1017 // An unnamed colon is valid.
1018 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1019 Diag(Tok, diag::err_expected_selector_for_method)
1020 << SourceRange(mLoc, Tok.getLocation());
1021 // Skip until we get a ; or @.
1022 SkipUntil(tok::at, true /*StopAtSemi*/, true /*don't consume*/);
1026 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1027 if (Tok.isNot(tok::colon)) {
1028 // If attributes exist after the method, parse them.
1029 if (getLangOpts().ObjC2)
1030 MaybeParseGNUAttributes(methodAttrs);
1032 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1034 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1035 mType, DSRet, ReturnType,
1037 CParamInfo.data(), CParamInfo.size(),
1038 methodAttrs.getList(), MethodImplKind,
1039 false, MethodDefinition);
1040 PD.complete(Result);
1044 SmallVector<IdentifierInfo *, 12> KeyIdents;
1045 SmallVector<SourceLocation, 12> KeyLocs;
1046 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1047 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1048 Scope::FunctionDeclarationScope | Scope::DeclScope);
1050 AttributePool allParamAttrs(AttrFactory);
1052 ParsedAttributes paramAttrs(AttrFactory);
1053 Sema::ObjCArgInfo ArgInfo;
1055 // Each iteration parses a single keyword argument.
1056 if (Tok.isNot(tok::colon)) {
1057 Diag(Tok, diag::err_expected_colon);
1060 ConsumeToken(); // Eat the ':'.
1062 ArgInfo.Type = ParsedType();
1063 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1064 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1065 Declarator::ObjCParameterContext,
1068 // If attributes exist before the argument name, parse them.
1069 // Regardless, collect all the attributes we've parsed so far.
1070 ArgInfo.ArgAttrs = 0;
1071 if (getLangOpts().ObjC2) {
1072 MaybeParseGNUAttributes(paramAttrs);
1073 ArgInfo.ArgAttrs = paramAttrs.getList();
1076 // Code completion for the next piece of the selector.
1077 if (Tok.is(tok::code_completion)) {
1078 KeyIdents.push_back(SelIdent);
1079 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1080 mType == tok::minus,
1081 /*AtParameterName=*/true,
1089 if (Tok.isNot(tok::identifier)) {
1090 Diag(Tok, diag::err_expected_ident); // missing argument name.
1094 ArgInfo.Name = Tok.getIdentifierInfo();
1095 ArgInfo.NameLoc = Tok.getLocation();
1096 ConsumeToken(); // Eat the identifier.
1098 ArgInfos.push_back(ArgInfo);
1099 KeyIdents.push_back(SelIdent);
1100 KeyLocs.push_back(selLoc);
1102 // Make sure the attributes persist.
1103 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1105 // Code completion for the next piece of the selector.
1106 if (Tok.is(tok::code_completion)) {
1107 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1108 mType == tok::minus,
1109 /*AtParameterName=*/false,
1117 // Check for another keyword selector.
1118 SelIdent = ParseObjCSelectorPiece(selLoc);
1119 if (!SelIdent && Tok.isNot(tok::colon))
1122 SourceLocation ColonLoc = Tok.getLocation();
1123 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1124 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1125 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1126 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1129 // We have a selector or a colon, continue parsing.
1132 bool isVariadic = false;
1133 bool cStyleParamWarned = false;
1134 // Parse the (optional) parameter list.
1135 while (Tok.is(tok::comma)) {
1137 if (Tok.is(tok::ellipsis)) {
1142 if (!cStyleParamWarned) {
1143 Diag(Tok, diag::warn_cstyle_param);
1144 cStyleParamWarned = true;
1146 DeclSpec DS(AttrFactory);
1147 ParseDeclarationSpecifiers(DS);
1148 // Parse the declarator.
1149 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1150 ParseDeclarator(ParmDecl);
1151 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1152 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1153 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1154 ParmDecl.getIdentifierLoc(),
1159 // FIXME: Add support for optional parameter list...
1160 // If attributes exist after the method, parse them.
1161 if (getLangOpts().ObjC2)
1162 MaybeParseGNUAttributes(methodAttrs);
1164 if (KeyIdents.size() == 0)
1167 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1170 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1171 mType, DSRet, ReturnType,
1172 KeyLocs, Sel, &ArgInfos[0],
1173 CParamInfo.data(), CParamInfo.size(),
1174 methodAttrs.getList(),
1175 MethodImplKind, isVariadic, MethodDefinition);
1177 PD.complete(Result);
1181 /// objc-protocol-refs:
1182 /// '<' identifier-list '>'
1185 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1186 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1187 bool WarnOnDeclarations,
1188 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1189 assert(Tok.is(tok::less) && "expected <");
1191 LAngleLoc = ConsumeToken(); // the "<"
1193 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1196 if (Tok.is(tok::code_completion)) {
1197 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1198 ProtocolIdents.size());
1203 if (Tok.isNot(tok::identifier)) {
1204 Diag(Tok, diag::err_expected_ident);
1205 SkipUntil(tok::greater);
1208 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1209 Tok.getLocation()));
1210 ProtocolLocs.push_back(Tok.getLocation());
1213 if (Tok.isNot(tok::comma))
1219 if (ParseGreaterThanInTemplateList(EndLoc, /*ConsumeLastToken=*/true))
1222 // Convert the list of protocols identifiers into a list of protocol decls.
1223 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1224 &ProtocolIdents[0], ProtocolIdents.size(),
1229 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1230 /// in a decl-specifier-seq, starting at the '<'.
1231 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1232 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1233 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1234 SourceLocation LAngleLoc, EndProtoLoc;
1235 SmallVector<Decl *, 8> ProtocolDecl;
1236 SmallVector<SourceLocation, 8> ProtocolLocs;
1237 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1238 LAngleLoc, EndProtoLoc);
1239 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1240 ProtocolLocs.data(), LAngleLoc);
1241 if (EndProtoLoc.isValid())
1242 DS.SetRangeEnd(EndProtoLoc);
1246 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1247 BalancedDelimiterTracker &T,
1248 SmallVectorImpl<Decl *> &AllIvarDecls,
1249 bool RBraceMissing) {
1253 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1254 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1255 Actions.ActOnObjCContainerFinishDefinition();
1256 // Call ActOnFields() even if we don't have any decls. This is useful
1257 // for code rewriting tools that need to be aware of the empty list.
1258 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1260 T.getOpenLocation(), T.getCloseLocation(), 0);
1263 /// objc-class-instance-variables:
1264 /// '{' objc-instance-variable-decl-list[opt] '}'
1266 /// objc-instance-variable-decl-list:
1267 /// objc-visibility-spec
1268 /// objc-instance-variable-decl ';'
1270 /// objc-instance-variable-decl-list objc-visibility-spec
1271 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1272 /// objc-instance-variable-decl-list ';'
1274 /// objc-visibility-spec:
1278 /// @package [OBJC2]
1280 /// objc-instance-variable-decl:
1281 /// struct-declaration
1283 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1284 tok::ObjCKeywordKind visibility,
1285 SourceLocation atLoc) {
1286 assert(Tok.is(tok::l_brace) && "expected {");
1287 SmallVector<Decl *, 32> AllIvarDecls;
1289 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1290 ObjCDeclContextSwitch ObjCDC(*this);
1292 BalancedDelimiterTracker T(*this, tok::l_brace);
1294 // While we still have something to read, read the instance variables.
1295 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1296 // Each iteration of this loop reads one objc-instance-variable-decl.
1298 // Check for extraneous top-level semicolon.
1299 if (Tok.is(tok::semi)) {
1300 ConsumeExtraSemi(InstanceVariableList);
1304 // Set the default visibility to private.
1305 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1306 ConsumeToken(); // eat the @ sign
1308 if (Tok.is(tok::code_completion)) {
1309 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1310 return cutOffParsing();
1313 switch (Tok.getObjCKeywordID()) {
1314 case tok::objc_private:
1315 case tok::objc_public:
1316 case tok::objc_protected:
1317 case tok::objc_package:
1318 visibility = Tok.getObjCKeywordID();
1323 Diag(Tok, diag::err_objc_unexpected_atend);
1324 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1325 Tok.setKind(tok::at);
1328 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1329 T, AllIvarDecls, true);
1333 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1338 if (Tok.is(tok::code_completion)) {
1339 Actions.CodeCompleteOrdinaryName(getCurScope(),
1340 Sema::PCC_ObjCInstanceVariableList);
1341 return cutOffParsing();
1344 struct ObjCIvarCallback : FieldCallback {
1347 tok::ObjCKeywordKind visibility;
1348 SmallVectorImpl<Decl *> &AllIvarDecls;
1350 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1351 SmallVectorImpl<Decl *> &AllIvarDecls) :
1352 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1355 void invoke(ParsingFieldDeclarator &FD) {
1356 P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1357 // Install the declarator into the interface decl.
1359 = P.Actions.ActOnIvar(P.getCurScope(),
1360 FD.D.getDeclSpec().getSourceRange().getBegin(),
1361 FD.D, FD.BitfieldSize, visibility);
1362 P.Actions.ActOnObjCContainerFinishDefinition();
1364 AllIvarDecls.push_back(Field);
1367 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1369 // Parse all the comma separated declarators.
1370 ParsingDeclSpec DS(*this);
1371 ParseStructDeclaration(DS, Callback);
1373 if (Tok.is(tok::semi)) {
1376 Diag(Tok, diag::err_expected_semi_decl_list);
1377 // Skip to end of block or statement
1378 SkipUntil(tok::r_brace, true, true);
1381 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1382 T, AllIvarDecls, false);
1386 /// objc-protocol-declaration:
1387 /// objc-protocol-definition
1388 /// objc-protocol-forward-reference
1390 /// objc-protocol-definition:
1391 /// \@protocol identifier
1392 /// objc-protocol-refs[opt]
1393 /// objc-interface-decl-list
1396 /// objc-protocol-forward-reference:
1397 /// \@protocol identifier-list ';'
1399 /// "\@protocol identifier ;" should be resolved as "\@protocol
1400 /// identifier-list ;": objc-interface-decl-list may not start with a
1401 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1402 Parser::DeclGroupPtrTy
1403 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1404 ParsedAttributes &attrs) {
1405 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1406 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1407 ConsumeToken(); // the "protocol" identifier
1409 if (Tok.is(tok::code_completion)) {
1410 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1412 return DeclGroupPtrTy();
1415 MaybeSkipAttributes(tok::objc_protocol);
1417 if (Tok.isNot(tok::identifier)) {
1418 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1419 return DeclGroupPtrTy();
1421 // Save the protocol name, then consume it.
1422 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1423 SourceLocation nameLoc = ConsumeToken();
1425 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1426 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1428 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1432 CheckNestedObjCContexts(AtLoc);
1434 if (Tok.is(tok::comma)) { // list of forward declarations.
1435 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1436 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1438 // Parse the list of forward declarations.
1440 ConsumeToken(); // the ','
1441 if (Tok.isNot(tok::identifier)) {
1442 Diag(Tok, diag::err_expected_ident);
1443 SkipUntil(tok::semi);
1444 return DeclGroupPtrTy();
1446 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1447 Tok.getLocation()));
1448 ConsumeToken(); // the identifier
1450 if (Tok.isNot(tok::comma))
1454 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1455 return DeclGroupPtrTy();
1457 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1459 ProtocolRefs.size(),
1463 // Last, and definitely not least, parse a protocol declaration.
1464 SourceLocation LAngleLoc, EndProtoLoc;
1466 SmallVector<Decl *, 8> ProtocolRefs;
1467 SmallVector<SourceLocation, 8> ProtocolLocs;
1468 if (Tok.is(tok::less) &&
1469 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1470 LAngleLoc, EndProtoLoc))
1471 return DeclGroupPtrTy();
1474 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1475 ProtocolRefs.data(),
1476 ProtocolRefs.size(),
1477 ProtocolLocs.data(),
1478 EndProtoLoc, attrs.getList());
1480 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1481 return Actions.ConvertDeclToDeclGroup(ProtoType);
1484 /// objc-implementation:
1485 /// objc-class-implementation-prologue
1486 /// objc-category-implementation-prologue
1488 /// objc-class-implementation-prologue:
1489 /// @implementation identifier objc-superclass[opt]
1490 /// objc-class-instance-variables[opt]
1492 /// objc-category-implementation-prologue:
1493 /// @implementation identifier ( identifier )
1494 Parser::DeclGroupPtrTy
1495 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1496 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1497 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1498 CheckNestedObjCContexts(AtLoc);
1499 ConsumeToken(); // the "implementation" identifier
1501 // Code completion after '@implementation'.
1502 if (Tok.is(tok::code_completion)) {
1503 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1505 return DeclGroupPtrTy();
1508 MaybeSkipAttributes(tok::objc_implementation);
1510 if (Tok.isNot(tok::identifier)) {
1511 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1512 return DeclGroupPtrTy();
1514 // We have a class or category name - consume it.
1515 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1516 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1517 Decl *ObjCImpDecl = 0;
1519 if (Tok.is(tok::l_paren)) {
1520 // we have a category implementation.
1522 SourceLocation categoryLoc, rparenLoc;
1523 IdentifierInfo *categoryId = 0;
1525 if (Tok.is(tok::code_completion)) {
1526 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1528 return DeclGroupPtrTy();
1531 if (Tok.is(tok::identifier)) {
1532 categoryId = Tok.getIdentifierInfo();
1533 categoryLoc = ConsumeToken();
1535 Diag(Tok, diag::err_expected_ident); // missing category name.
1536 return DeclGroupPtrTy();
1538 if (Tok.isNot(tok::r_paren)) {
1539 Diag(Tok, diag::err_expected_rparen);
1540 SkipUntil(tok::r_paren, false); // don't stop at ';'
1541 return DeclGroupPtrTy();
1543 rparenLoc = ConsumeParen();
1544 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1545 AtLoc, nameId, nameLoc, categoryId,
1549 // We have a class implementation
1550 SourceLocation superClassLoc;
1551 IdentifierInfo *superClassId = 0;
1552 if (Tok.is(tok::colon)) {
1553 // We have a super class
1555 if (Tok.isNot(tok::identifier)) {
1556 Diag(Tok, diag::err_expected_ident); // missing super class name.
1557 return DeclGroupPtrTy();
1559 superClassId = Tok.getIdentifierInfo();
1560 superClassLoc = ConsumeToken(); // Consume super class name
1562 ObjCImpDecl = Actions.ActOnStartClassImplementation(
1563 AtLoc, nameId, nameLoc,
1564 superClassId, superClassLoc);
1566 if (Tok.is(tok::l_brace)) // we have ivars
1567 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
1569 assert(ObjCImpDecl);
1571 SmallVector<Decl *, 8> DeclsInGroup;
1574 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1575 while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
1576 ParsedAttributesWithRange attrs(AttrFactory);
1577 MaybeParseCXX11Attributes(attrs);
1578 MaybeParseMicrosoftAttributes(attrs);
1579 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1580 DeclGroupRef DG = DGP.get();
1581 DeclsInGroup.append(DG.begin(), DG.end());
1586 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1589 Parser::DeclGroupPtrTy
1590 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1591 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1592 "ParseObjCAtEndDeclaration(): Expected @end");
1593 ConsumeToken(); // the "end" identifier
1594 if (CurParsedObjCImpl)
1595 CurParsedObjCImpl->finish(atEnd);
1597 // missing @implementation
1598 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1599 return DeclGroupPtrTy();
1602 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1604 finish(P.Tok.getLocation());
1605 if (P.Tok.is(tok::eof)) {
1606 P.Diag(P.Tok, diag::err_objc_missing_end)
1607 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1608 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1609 << Sema::OCK_Implementation;
1612 P.CurParsedObjCImpl = 0;
1613 assert(LateParsedObjCMethods.empty());
1616 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1618 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1619 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1620 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1623 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1626 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1627 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1628 false/*c-functions*/);
1630 /// \brief Clear and free the cached objc methods.
1631 for (LateParsedObjCMethodContainer::iterator
1632 I = LateParsedObjCMethods.begin(),
1633 E = LateParsedObjCMethods.end(); I != E; ++I)
1635 LateParsedObjCMethods.clear();
1640 /// compatibility-alias-decl:
1641 /// @compatibility_alias alias-name class-name ';'
1643 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1644 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1645 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1646 ConsumeToken(); // consume compatibility_alias
1647 if (Tok.isNot(tok::identifier)) {
1648 Diag(Tok, diag::err_expected_ident);
1651 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1652 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1653 if (Tok.isNot(tok::identifier)) {
1654 Diag(Tok, diag::err_expected_ident);
1657 IdentifierInfo *classId = Tok.getIdentifierInfo();
1658 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1659 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1660 "@compatibility_alias");
1661 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1665 /// property-synthesis:
1666 /// @synthesize property-ivar-list ';'
1668 /// property-ivar-list:
1670 /// property-ivar-list ',' property-ivar
1674 /// identifier '=' identifier
1676 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1677 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1678 "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1679 ConsumeToken(); // consume synthesize
1682 if (Tok.is(tok::code_completion)) {
1683 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1688 if (Tok.isNot(tok::identifier)) {
1689 Diag(Tok, diag::err_synthesized_property_name);
1690 SkipUntil(tok::semi);
1694 IdentifierInfo *propertyIvar = 0;
1695 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1696 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1697 SourceLocation propertyIvarLoc;
1698 if (Tok.is(tok::equal)) {
1699 // property '=' ivar-name
1700 ConsumeToken(); // consume '='
1702 if (Tok.is(tok::code_completion)) {
1703 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1708 if (Tok.isNot(tok::identifier)) {
1709 Diag(Tok, diag::err_expected_ident);
1712 propertyIvar = Tok.getIdentifierInfo();
1713 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1715 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1716 propertyId, propertyIvar, propertyIvarLoc);
1717 if (Tok.isNot(tok::comma))
1719 ConsumeToken(); // consume ','
1721 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1725 /// property-dynamic:
1726 /// @dynamic property-list
1730 /// property-list ',' identifier
1732 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1733 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1734 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1735 ConsumeToken(); // consume dynamic
1737 if (Tok.is(tok::code_completion)) {
1738 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1743 if (Tok.isNot(tok::identifier)) {
1744 Diag(Tok, diag::err_expected_ident);
1745 SkipUntil(tok::semi);
1749 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1750 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1751 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1752 propertyId, 0, SourceLocation());
1754 if (Tok.isNot(tok::comma))
1756 ConsumeToken(); // consume ','
1758 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1762 /// objc-throw-statement:
1763 /// throw expression[opt];
1765 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1767 ConsumeToken(); // consume throw
1768 if (Tok.isNot(tok::semi)) {
1769 Res = ParseExpression();
1770 if (Res.isInvalid()) {
1771 SkipUntil(tok::semi);
1776 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1777 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1780 /// objc-synchronized-statement:
1781 /// @synchronized '(' expression ')' compound-statement
1784 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1785 ConsumeToken(); // consume synchronized
1786 if (Tok.isNot(tok::l_paren)) {
1787 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1791 // The operand is surrounded with parentheses.
1792 ConsumeParen(); // '('
1793 ExprResult operand(ParseExpression());
1795 if (Tok.is(tok::r_paren)) {
1796 ConsumeParen(); // ')'
1798 if (!operand.isInvalid())
1799 Diag(Tok, diag::err_expected_rparen);
1801 // Skip forward until we see a left brace, but don't consume it.
1802 SkipUntil(tok::l_brace, true, true);
1805 // Require a compound statement.
1806 if (Tok.isNot(tok::l_brace)) {
1807 if (!operand.isInvalid())
1808 Diag(Tok, diag::err_expected_lbrace);
1812 // Check the @synchronized operand now.
1813 if (!operand.isInvalid())
1814 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1816 // Parse the compound statement within a new scope.
1817 ParseScope bodyScope(this, Scope::DeclScope);
1818 StmtResult body(ParseCompoundStatementBody());
1821 // If there was a semantic or parse error earlier with the
1822 // operand, fail now.
1823 if (operand.isInvalid())
1826 if (body.isInvalid())
1827 body = Actions.ActOnNullStmt(Tok.getLocation());
1829 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1832 /// objc-try-catch-statement:
1833 /// @try compound-statement objc-catch-list[opt]
1834 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1836 /// objc-catch-list:
1837 /// @catch ( parameter-declaration ) compound-statement
1838 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1839 /// catch-parameter-declaration:
1840 /// parameter-declaration
1843 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1844 bool catch_or_finally_seen = false;
1846 ConsumeToken(); // consume try
1847 if (Tok.isNot(tok::l_brace)) {
1848 Diag(Tok, diag::err_expected_lbrace);
1851 StmtVector CatchStmts;
1852 StmtResult FinallyStmt;
1853 ParseScope TryScope(this, Scope::DeclScope);
1854 StmtResult TryBody(ParseCompoundStatementBody());
1856 if (TryBody.isInvalid())
1857 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1859 while (Tok.is(tok::at)) {
1860 // At this point, we need to lookahead to determine if this @ is the start
1861 // of an @catch or @finally. We don't want to consume the @ token if this
1862 // is an @try or @encode or something else.
1863 Token AfterAt = GetLookAheadToken(1);
1864 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1865 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1868 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1869 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1870 Decl *FirstPart = 0;
1871 ConsumeToken(); // consume catch
1872 if (Tok.is(tok::l_paren)) {
1874 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1875 if (Tok.isNot(tok::ellipsis)) {
1876 DeclSpec DS(AttrFactory);
1877 ParseDeclarationSpecifiers(DS);
1878 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1879 ParseDeclarator(ParmDecl);
1881 // Inform the actions module about the declarator, so it
1882 // gets added to the current scope.
1883 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1885 ConsumeToken(); // consume '...'
1887 SourceLocation RParenLoc;
1889 if (Tok.is(tok::r_paren))
1890 RParenLoc = ConsumeParen();
1891 else // Skip over garbage, until we get to ')'. Eat the ')'.
1892 SkipUntil(tok::r_paren, true, false);
1894 StmtResult CatchBody(true);
1895 if (Tok.is(tok::l_brace))
1896 CatchBody = ParseCompoundStatementBody();
1898 Diag(Tok, diag::err_expected_lbrace);
1899 if (CatchBody.isInvalid())
1900 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1902 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1906 if (!Catch.isInvalid())
1907 CatchStmts.push_back(Catch.release());
1910 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1914 catch_or_finally_seen = true;
1916 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1917 ConsumeToken(); // consume finally
1918 ParseScope FinallyScope(this, Scope::DeclScope);
1920 StmtResult FinallyBody(true);
1921 if (Tok.is(tok::l_brace))
1922 FinallyBody = ParseCompoundStatementBody();
1924 Diag(Tok, diag::err_expected_lbrace);
1925 if (FinallyBody.isInvalid())
1926 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1927 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1928 FinallyBody.take());
1929 catch_or_finally_seen = true;
1933 if (!catch_or_finally_seen) {
1934 Diag(atLoc, diag::err_missing_catch_finally);
1938 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1940 FinallyStmt.take());
1943 /// objc-autoreleasepool-statement:
1944 /// @autoreleasepool compound-statement
1947 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1948 ConsumeToken(); // consume autoreleasepool
1949 if (Tok.isNot(tok::l_brace)) {
1950 Diag(Tok, diag::err_expected_lbrace);
1953 // Enter a scope to hold everything within the compound stmt. Compound
1954 // statements can always hold declarations.
1955 ParseScope BodyScope(this, Scope::DeclScope);
1957 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1960 if (AutoreleasePoolBody.isInvalid())
1961 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1962 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1963 AutoreleasePoolBody.take());
1966 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1967 /// for later parsing.
1968 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1969 LexedMethod* LM = new LexedMethod(this, MDecl);
1970 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1971 CachedTokens &Toks = LM->Toks;
1972 // Begin by storing the '{' or 'try' or ':' token.
1973 Toks.push_back(Tok);
1974 if (Tok.is(tok::kw_try)) {
1976 if (Tok.is(tok::colon)) {
1977 Toks.push_back(Tok);
1979 while (Tok.isNot(tok::l_brace)) {
1980 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1981 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1984 Toks.push_back(Tok); // also store '{'
1986 else if (Tok.is(tok::colon)) {
1988 while (Tok.isNot(tok::l_brace)) {
1989 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1990 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1992 Toks.push_back(Tok); // also store '{'
1995 // Consume everything up to (and including) the matching right brace.
1996 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1997 while (Tok.is(tok::kw_catch)) {
1998 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1999 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2003 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2005 Decl *Parser::ParseObjCMethodDefinition() {
2006 Decl *MDecl = ParseObjCMethodPrototype();
2008 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2009 "parsing Objective-C method");
2011 // parse optional ';'
2012 if (Tok.is(tok::semi)) {
2013 if (CurParsedObjCImpl) {
2014 Diag(Tok, diag::warn_semicolon_before_method_body)
2015 << FixItHint::CreateRemoval(Tok.getLocation());
2020 // We should have an opening brace now.
2021 if (Tok.isNot(tok::l_brace)) {
2022 Diag(Tok, diag::err_expected_method_body);
2024 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2025 SkipUntil(tok::l_brace, true, true);
2027 // If we didn't find the '{', bail out.
2028 if (Tok.isNot(tok::l_brace))
2034 SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
2038 // Allow the rest of sema to find private method decl implementations.
2039 Actions.AddAnyMethodToGlobalPool(MDecl);
2040 assert (CurParsedObjCImpl
2041 && "ParseObjCMethodDefinition - Method out of @implementation");
2042 // Consume the tokens and store them for later parsing.
2043 StashAwayMethodOrFunctionBodyTokens(MDecl);
2047 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2048 if (Tok.is(tok::code_completion)) {
2049 Actions.CodeCompleteObjCAtStatement(getCurScope());
2054 if (Tok.isObjCAtKeyword(tok::objc_try))
2055 return ParseObjCTryStmt(AtLoc);
2057 if (Tok.isObjCAtKeyword(tok::objc_throw))
2058 return ParseObjCThrowStmt(AtLoc);
2060 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2061 return ParseObjCSynchronizedStmt(AtLoc);
2063 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2064 return ParseObjCAutoreleasePoolStmt(AtLoc);
2066 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2067 if (Res.isInvalid()) {
2068 // If the expression is invalid, skip ahead to the next semicolon. Not
2069 // doing this opens us up to the possibility of infinite loops if
2070 // ParseExpression does not consume any tokens.
2071 SkipUntil(tok::semi);
2075 // Otherwise, eat the semicolon.
2076 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2077 return Actions.ActOnExprStmt(Res);
2080 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2081 switch (Tok.getKind()) {
2082 case tok::code_completion:
2083 Actions.CodeCompleteObjCAtExpression(getCurScope());
2089 tok::TokenKind Kind = Tok.getKind();
2090 SourceLocation OpLoc = ConsumeToken();
2092 if (!Tok.is(tok::numeric_constant)) {
2093 const char *Symbol = 0;
2095 case tok::minus: Symbol = "-"; break;
2096 case tok::plus: Symbol = "+"; break;
2097 default: llvm_unreachable("missing unary operator case");
2099 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2104 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2105 if (Lit.isInvalid()) {
2108 ConsumeToken(); // Consume the literal token.
2110 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
2111 if (Lit.isInvalid())
2114 return ParsePostfixExpressionSuffix(
2115 Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2118 case tok::string_literal: // primary-expression: string-literal
2119 case tok::wide_string_literal:
2120 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2122 case tok::char_constant:
2123 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2125 case tok::numeric_constant:
2126 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2128 case tok::kw_true: // Objective-C++, etc.
2129 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2130 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2131 case tok::kw_false: // Objective-C++, etc.
2132 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2133 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2136 // Objective-C array literal
2137 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2140 // Objective-C dictionary literal
2141 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2144 // Objective-C boxed expression
2145 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2148 if (Tok.getIdentifierInfo() == 0)
2149 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2151 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2152 case tok::objc_encode:
2153 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2154 case tok::objc_protocol:
2155 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2156 case tok::objc_selector:
2157 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2159 const char *str = 0;
2160 if (GetLookAheadToken(1).is(tok::l_brace)) {
2161 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2164 : (ch == 'f' ? "finally"
2165 : (ch == 'a' ? "autoreleasepool" : 0));
2168 SourceLocation kwLoc = Tok.getLocation();
2169 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2170 FixItHint::CreateReplacement(kwLoc, str));
2173 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2179 /// \brief Parse the receiver of an Objective-C++ message send.
2181 /// This routine parses the receiver of a message send in
2182 /// Objective-C++ either as a type or as an expression. Note that this
2183 /// routine must not be called to parse a send to 'super', since it
2184 /// has no way to return such a result.
2186 /// \param IsExpr Whether the receiver was parsed as an expression.
2188 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2189 /// IsExpr is true), the parsed expression. If the receiver was parsed
2190 /// as a type (\c IsExpr is false), the parsed type.
2192 /// \returns True if an error occurred during parsing or semantic
2193 /// analysis, in which case the arguments do not have valid
2194 /// values. Otherwise, returns false for a successful parse.
2196 /// objc-receiver: [C++]
2197 /// 'super' [not parsed here]
2199 /// simple-type-specifier
2200 /// typename-specifier
2201 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2202 InMessageExpressionRAIIObject InMessage(*this, true);
2204 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2205 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2206 TryAnnotateTypeOrScopeToken();
2208 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2211 ExprResult Receiver = ParseExpression();
2212 if (Receiver.isInvalid())
2216 TypeOrExpr = Receiver.take();
2221 // typename-specifier
2222 // simple-type-specifier
2223 // expression (that starts with one of the above)
2224 DeclSpec DS(AttrFactory);
2225 ParseCXXSimpleTypeSpecifier(DS);
2227 if (Tok.is(tok::l_paren)) {
2228 // If we see an opening parentheses at this point, we are
2229 // actually parsing an expression that starts with a
2230 // function-style cast, e.g.,
2232 // postfix-expression:
2233 // simple-type-specifier ( expression-list [opt] )
2234 // typename-specifier ( expression-list [opt] )
2236 // Parse the remainder of this case, then the (optional)
2237 // postfix-expression suffix, followed by the (optional)
2238 // right-hand side of the binary expression. We have an
2240 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2241 if (!Receiver.isInvalid())
2242 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
2243 if (!Receiver.isInvalid())
2244 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
2245 if (Receiver.isInvalid())
2249 TypeOrExpr = Receiver.take();
2253 // We have a class message. Turn the simple-type-specifier or
2254 // typename-specifier we parsed into a type and parse the
2255 // remainder of the class message.
2256 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2257 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2258 if (Type.isInvalid())
2262 TypeOrExpr = Type.get().getAsOpaquePtr();
2266 /// \brief Determine whether the parser is currently referring to a an
2267 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2269 /// This routine will only return true for a subset of valid message-send
2271 bool Parser::isSimpleObjCMessageExpression() {
2272 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2273 "Incorrect start for isSimpleObjCMessageExpression");
2274 return GetLookAheadToken(1).is(tok::identifier) &&
2275 GetLookAheadToken(2).is(tok::identifier);
2278 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2279 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2280 InMessageExpression)
2286 if (Tok.is(tok::annot_typename))
2287 Type = getTypeAnnotation(Tok);
2288 else if (Tok.is(tok::identifier))
2289 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2294 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2295 const Token &AfterNext = GetLookAheadToken(2);
2296 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2297 if (Tok.is(tok::identifier))
2298 TryAnnotateTypeOrScopeToken();
2300 return Tok.is(tok::annot_typename);
2307 /// objc-message-expr:
2308 /// '[' objc-receiver objc-message-args ']'
2310 /// objc-receiver: [C]
2316 ExprResult Parser::ParseObjCMessageExpression() {
2317 assert(Tok.is(tok::l_square) && "'[' expected");
2318 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2320 if (Tok.is(tok::code_completion)) {
2321 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2326 InMessageExpressionRAIIObject InMessage(*this, true);
2328 if (getLangOpts().CPlusPlus) {
2329 // We completely separate the C and C++ cases because C++ requires
2330 // more complicated (read: slower) parsing.
2332 // Handle send to super.
2333 // FIXME: This doesn't benefit from the same typo-correction we
2334 // get in Objective-C.
2335 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2336 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2337 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2340 // Parse the receiver, which is either a type or an expression.
2342 void *TypeOrExpr = NULL;
2343 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2344 SkipUntil(tok::r_square);
2349 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2351 static_cast<Expr*>(TypeOrExpr));
2353 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2354 ParsedType::getFromOpaquePtr(TypeOrExpr),
2358 if (Tok.is(tok::identifier)) {
2359 IdentifierInfo *Name = Tok.getIdentifierInfo();
2360 SourceLocation NameLoc = Tok.getLocation();
2361 ParsedType ReceiverType;
2362 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2363 Name == Ident_super,
2364 NextToken().is(tok::period),
2366 case Sema::ObjCSuperMessage:
2367 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2370 case Sema::ObjCClassMessage:
2371 if (!ReceiverType) {
2372 SkipUntil(tok::r_square);
2376 ConsumeToken(); // the type name
2378 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2381 case Sema::ObjCInstanceMessage:
2382 // Fall through to parse an expression.
2387 // Otherwise, an arbitrary expression can be the receiver of a send.
2388 ExprResult Res(ParseExpression());
2389 if (Res.isInvalid()) {
2390 SkipUntil(tok::r_square);
2394 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2395 ParsedType(), Res.take());
2398 /// \brief Parse the remainder of an Objective-C message following the
2399 /// '[' objc-receiver.
2401 /// This routine handles sends to super, class messages (sent to a
2402 /// class name), and instance messages (sent to an object), and the
2403 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2404 /// ReceiverExpr, respectively. Only one of these parameters may have
2407 /// \param LBracLoc The location of the opening '['.
2409 /// \param SuperLoc If this is a send to 'super', the location of the
2410 /// 'super' keyword that indicates a send to the superclass.
2412 /// \param ReceiverType If this is a class message, the type of the
2413 /// class we are sending a message to.
2415 /// \param ReceiverExpr If this is an instance message, the expression
2416 /// used to compute the receiver object.
2418 /// objc-message-args:
2420 /// objc-keywordarg-list
2422 /// objc-keywordarg-list:
2424 /// objc-keywordarg-list objc-keywordarg
2426 /// objc-keywordarg:
2427 /// selector-name[opt] ':' objc-keywordexpr
2429 /// objc-keywordexpr:
2430 /// nonempty-expr-list
2432 /// nonempty-expr-list:
2433 /// assignment-expression
2434 /// nonempty-expr-list , assignment-expression
2437 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2438 SourceLocation SuperLoc,
2439 ParsedType ReceiverType,
2440 ExprArg ReceiverExpr) {
2441 InMessageExpressionRAIIObject InMessage(*this, true);
2443 if (Tok.is(tok::code_completion)) {
2444 if (SuperLoc.isValid())
2445 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2447 else if (ReceiverType)
2448 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2451 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2457 // Parse objc-selector
2459 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2461 SmallVector<IdentifierInfo *, 12> KeyIdents;
2462 SmallVector<SourceLocation, 12> KeyLocs;
2463 ExprVector KeyExprs;
2465 if (Tok.is(tok::colon)) {
2467 // Each iteration parses a single keyword argument.
2468 KeyIdents.push_back(selIdent);
2469 KeyLocs.push_back(Loc);
2471 if (Tok.isNot(tok::colon)) {
2472 Diag(Tok, diag::err_expected_colon);
2473 // We must manually skip to a ']', otherwise the expression skipper will
2474 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2475 // the enclosing expression.
2476 SkipUntil(tok::r_square);
2480 ConsumeToken(); // Eat the ':'.
2481 /// Parse the expression after ':'
2483 if (Tok.is(tok::code_completion)) {
2484 if (SuperLoc.isValid())
2485 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2488 /*AtArgumentEpression=*/true);
2489 else if (ReceiverType)
2490 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2493 /*AtArgumentEpression=*/true);
2495 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2498 /*AtArgumentEpression=*/true);
2504 ExprResult Res(ParseAssignmentExpression());
2505 if (Res.isInvalid()) {
2506 // We must manually skip to a ']', otherwise the expression skipper will
2507 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2508 // the enclosing expression.
2509 SkipUntil(tok::r_square);
2513 // We have a valid expression.
2514 KeyExprs.push_back(Res.release());
2516 // Code completion after each argument.
2517 if (Tok.is(tok::code_completion)) {
2518 if (SuperLoc.isValid())
2519 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2522 /*AtArgumentEpression=*/false);
2523 else if (ReceiverType)
2524 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2527 /*AtArgumentEpression=*/false);
2529 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2532 /*AtArgumentEpression=*/false);
2537 // Check for another keyword selector.
2538 selIdent = ParseObjCSelectorPiece(Loc);
2539 if (!selIdent && Tok.isNot(tok::colon))
2541 // We have a selector or a colon, continue parsing.
2543 // Parse the, optional, argument list, comma separated.
2544 while (Tok.is(tok::comma)) {
2545 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2546 /// Parse the expression after ','
2547 ExprResult Res(ParseAssignmentExpression());
2548 if (Res.isInvalid()) {
2549 if (Tok.is(tok::colon)) {
2550 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2551 FixItHint::CreateRemoval(commaLoc);
2553 // We must manually skip to a ']', otherwise the expression skipper will
2554 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2555 // the enclosing expression.
2556 SkipUntil(tok::r_square);
2560 // We have a valid expression.
2561 KeyExprs.push_back(Res.release());
2563 } else if (!selIdent) {
2564 Diag(Tok, diag::err_expected_ident); // missing selector name.
2566 // We must manually skip to a ']', otherwise the expression skipper will
2567 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2568 // the enclosing expression.
2569 SkipUntil(tok::r_square);
2573 if (Tok.isNot(tok::r_square)) {
2574 if (Tok.is(tok::identifier))
2575 Diag(Tok, diag::err_expected_colon);
2577 Diag(Tok, diag::err_expected_rsquare);
2578 // We must manually skip to a ']', otherwise the expression skipper will
2579 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2580 // the enclosing expression.
2581 SkipUntil(tok::r_square);
2585 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2587 unsigned nKeys = KeyIdents.size();
2589 KeyIdents.push_back(selIdent);
2590 KeyLocs.push_back(Loc);
2592 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2594 if (SuperLoc.isValid())
2595 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2596 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2597 else if (ReceiverType)
2598 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2599 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2600 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2601 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2604 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2605 ExprResult Res(ParseStringLiteralExpression());
2606 if (Res.isInvalid()) return Res;
2608 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2609 // expressions. At this point, we know that the only valid thing that starts
2610 // with '@' is an @"".
2611 SmallVector<SourceLocation, 4> AtLocs;
2612 ExprVector AtStrings;
2613 AtLocs.push_back(AtLoc);
2614 AtStrings.push_back(Res.release());
2616 while (Tok.is(tok::at)) {
2617 AtLocs.push_back(ConsumeToken()); // eat the @.
2619 // Invalid unless there is a string literal.
2620 if (!isTokenStringLiteral())
2621 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2623 ExprResult Lit(ParseStringLiteralExpression());
2624 if (Lit.isInvalid())
2627 AtStrings.push_back(Lit.release());
2630 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2634 /// ParseObjCBooleanLiteral -
2635 /// objc-scalar-literal : '@' boolean-keyword
2637 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2639 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2641 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2642 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2645 /// ParseObjCCharacterLiteral -
2646 /// objc-scalar-literal : '@' character-literal
2648 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2649 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2650 if (Lit.isInvalid()) {
2653 ConsumeToken(); // Consume the literal token.
2654 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take());
2657 /// ParseObjCNumericLiteral -
2658 /// objc-scalar-literal : '@' scalar-literal
2660 /// scalar-literal : | numeric-constant /* any numeric constant. */
2662 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2663 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2664 if (Lit.isInvalid()) {
2667 ConsumeToken(); // Consume the literal token.
2668 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take());
2671 /// ParseObjCBoxedExpr -
2672 /// objc-box-expression:
2673 /// @( assignment-expression )
2675 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2676 if (Tok.isNot(tok::l_paren))
2677 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2679 BalancedDelimiterTracker T(*this, tok::l_paren);
2681 ExprResult ValueExpr(ParseAssignmentExpression());
2682 if (T.consumeClose())
2685 if (ValueExpr.isInvalid())
2688 // Wrap the sub-expression in a parenthesized expression, to distinguish
2689 // a boxed expression from a literal.
2690 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2691 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take());
2692 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2696 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2697 ExprVector ElementExprs; // array elements.
2698 ConsumeBracket(); // consume the l_square.
2700 while (Tok.isNot(tok::r_square)) {
2701 // Parse list of array element expressions (all must be id types).
2702 ExprResult Res(ParseAssignmentExpression());
2703 if (Res.isInvalid()) {
2704 // We must manually skip to a ']', otherwise the expression skipper will
2705 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2706 // the enclosing expression.
2707 SkipUntil(tok::r_square);
2711 // Parse the ellipsis that indicates a pack expansion.
2712 if (Tok.is(tok::ellipsis))
2713 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2714 if (Res.isInvalid())
2717 ElementExprs.push_back(Res.release());
2719 if (Tok.is(tok::comma))
2720 ConsumeToken(); // Eat the ','.
2721 else if (Tok.isNot(tok::r_square))
2722 return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
2724 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2725 MultiExprArg Args(ElementExprs);
2726 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
2729 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2730 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2731 ConsumeBrace(); // consume the l_square.
2732 while (Tok.isNot(tok::r_brace)) {
2733 // Parse the comma separated key : value expressions.
2736 ColonProtectionRAIIObject X(*this);
2737 KeyExpr = ParseAssignmentExpression();
2738 if (KeyExpr.isInvalid()) {
2739 // We must manually skip to a '}', otherwise the expression skipper will
2740 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2741 // the enclosing expression.
2742 SkipUntil(tok::r_brace);
2747 if (Tok.is(tok::colon)) {
2750 return ExprError(Diag(Tok, diag::err_expected_colon));
2753 ExprResult ValueExpr(ParseAssignmentExpression());
2754 if (ValueExpr.isInvalid()) {
2755 // We must manually skip to a '}', otherwise the expression skipper will
2756 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2757 // the enclosing expression.
2758 SkipUntil(tok::r_brace);
2762 // Parse the ellipsis that designates this as a pack expansion.
2763 SourceLocation EllipsisLoc;
2764 if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
2765 EllipsisLoc = ConsumeToken();
2767 // We have a valid expression. Collect it in a vector so we can
2768 // build the argument list.
2769 ObjCDictionaryElement Element = {
2770 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
2772 Elements.push_back(Element);
2774 if (Tok.is(tok::comma))
2775 ConsumeToken(); // Eat the ','.
2776 else if (Tok.isNot(tok::r_brace))
2777 return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
2779 SourceLocation EndLoc = ConsumeBrace();
2781 // Create the ObjCDictionaryLiteral.
2782 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2783 Elements.data(), Elements.size());
2786 /// objc-encode-expression:
2787 /// \@encode ( type-name )
2789 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2790 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2792 SourceLocation EncLoc = ConsumeToken();
2794 if (Tok.isNot(tok::l_paren))
2795 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2797 BalancedDelimiterTracker T(*this, tok::l_paren);
2800 TypeResult Ty = ParseTypeName();
2807 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
2808 Ty.get(), T.getCloseLocation());
2811 /// objc-protocol-expression
2812 /// \@protocol ( protocol-name )
2814 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2815 SourceLocation ProtoLoc = ConsumeToken();
2817 if (Tok.isNot(tok::l_paren))
2818 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2820 BalancedDelimiterTracker T(*this, tok::l_paren);
2823 if (Tok.isNot(tok::identifier))
2824 return ExprError(Diag(Tok, diag::err_expected_ident));
2826 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2827 SourceLocation ProtoIdLoc = ConsumeToken();
2831 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2832 T.getOpenLocation(), ProtoIdLoc,
2833 T.getCloseLocation());
2836 /// objc-selector-expression
2837 /// @selector '(' objc-keyword-selector ')'
2838 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2839 SourceLocation SelectorLoc = ConsumeToken();
2841 if (Tok.isNot(tok::l_paren))
2842 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2844 SmallVector<IdentifierInfo *, 12> KeyIdents;
2845 SourceLocation sLoc;
2847 BalancedDelimiterTracker T(*this, tok::l_paren);
2850 if (Tok.is(tok::code_completion)) {
2851 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2857 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2858 if (!SelIdent && // missing selector name.
2859 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2860 return ExprError(Diag(Tok, diag::err_expected_ident));
2862 KeyIdents.push_back(SelIdent);
2863 unsigned nColons = 0;
2864 if (Tok.isNot(tok::r_paren)) {
2866 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2868 KeyIdents.push_back(0);
2869 } else if (Tok.isNot(tok::colon))
2870 return ExprError(Diag(Tok, diag::err_expected_colon));
2873 ConsumeToken(); // Eat the ':' or '::'.
2874 if (Tok.is(tok::r_paren))
2877 if (Tok.is(tok::code_completion)) {
2878 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2884 // Check for another keyword selector.
2886 SelIdent = ParseObjCSelectorPiece(Loc);
2887 KeyIdents.push_back(SelIdent);
2888 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2893 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2894 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2895 T.getOpenLocation(),
2896 T.getCloseLocation());
2899 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2900 // MCDecl might be null due to error in method or c-function prototype, etc.
2901 Decl *MCDecl = LM.D;
2902 bool skip = MCDecl &&
2903 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2904 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2908 // Save the current token position.
2909 SourceLocation OrigLoc = Tok.getLocation();
2911 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2912 // Append the current token at the end of the new token stream so that it
2913 // doesn't get lost.
2914 LM.Toks.push_back(Tok);
2915 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2917 // Consume the previously pushed token.
2918 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
2920 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2921 Tok.is(tok::colon)) &&
2922 "Inline objective-c method not starting with '{' or 'try' or ':'");
2923 // Enter a scope for the method or c-fucntion body.
2924 ParseScope BodyScope(this,
2926 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2927 : Scope::FnScope|Scope::DeclScope);
2929 // Tell the actions module that we have entered a method or c-function definition
2930 // with the specified Declarator for the method/function.
2932 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2934 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2935 if (Tok.is(tok::kw_try))
2936 MCDecl = ParseFunctionTryBlock(MCDecl, BodyScope);
2938 if (Tok.is(tok::colon))
2939 ParseConstructorInitializer(MCDecl);
2940 MCDecl = ParseFunctionStatementBody(MCDecl, BodyScope);
2943 if (Tok.getLocation() != OrigLoc) {
2944 // Due to parsing error, we either went over the cached tokens or
2945 // there are still cached tokens left. If it's the latter case skip the
2947 // Since this is an uncommon situation that should be avoided, use the
2948 // expensive isBeforeInTranslationUnit call.
2949 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2951 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))