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);
1568 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1569 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1571 AttributeFactory attr;
1573 (void)ParseObjCProtocolQualifiers(DS);
1576 assert(ObjCImpDecl);
1578 SmallVector<Decl *, 8> DeclsInGroup;
1581 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1582 while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
1583 ParsedAttributesWithRange attrs(AttrFactory);
1584 MaybeParseCXX11Attributes(attrs);
1585 MaybeParseMicrosoftAttributes(attrs);
1586 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1587 DeclGroupRef DG = DGP.get();
1588 DeclsInGroup.append(DG.begin(), DG.end());
1593 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1596 Parser::DeclGroupPtrTy
1597 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1598 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1599 "ParseObjCAtEndDeclaration(): Expected @end");
1600 ConsumeToken(); // the "end" identifier
1601 if (CurParsedObjCImpl)
1602 CurParsedObjCImpl->finish(atEnd);
1604 // missing @implementation
1605 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1606 return DeclGroupPtrTy();
1609 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1611 finish(P.Tok.getLocation());
1612 if (P.Tok.is(tok::eof)) {
1613 P.Diag(P.Tok, diag::err_objc_missing_end)
1614 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1615 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1616 << Sema::OCK_Implementation;
1619 P.CurParsedObjCImpl = 0;
1620 assert(LateParsedObjCMethods.empty());
1623 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1625 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1626 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1627 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1630 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1633 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1634 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1635 false/*c-functions*/);
1637 /// \brief Clear and free the cached objc methods.
1638 for (LateParsedObjCMethodContainer::iterator
1639 I = LateParsedObjCMethods.begin(),
1640 E = LateParsedObjCMethods.end(); I != E; ++I)
1642 LateParsedObjCMethods.clear();
1647 /// compatibility-alias-decl:
1648 /// @compatibility_alias alias-name class-name ';'
1650 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1651 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1652 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1653 ConsumeToken(); // consume compatibility_alias
1654 if (Tok.isNot(tok::identifier)) {
1655 Diag(Tok, diag::err_expected_ident);
1658 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1659 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1660 if (Tok.isNot(tok::identifier)) {
1661 Diag(Tok, diag::err_expected_ident);
1664 IdentifierInfo *classId = Tok.getIdentifierInfo();
1665 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1666 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1667 "@compatibility_alias");
1668 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1672 /// property-synthesis:
1673 /// @synthesize property-ivar-list ';'
1675 /// property-ivar-list:
1677 /// property-ivar-list ',' property-ivar
1681 /// identifier '=' identifier
1683 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1684 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1685 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
1686 ConsumeToken(); // consume synthesize
1689 if (Tok.is(tok::code_completion)) {
1690 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1695 if (Tok.isNot(tok::identifier)) {
1696 Diag(Tok, diag::err_synthesized_property_name);
1697 SkipUntil(tok::semi);
1701 IdentifierInfo *propertyIvar = 0;
1702 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1703 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1704 SourceLocation propertyIvarLoc;
1705 if (Tok.is(tok::equal)) {
1706 // property '=' ivar-name
1707 ConsumeToken(); // consume '='
1709 if (Tok.is(tok::code_completion)) {
1710 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1715 if (Tok.isNot(tok::identifier)) {
1716 Diag(Tok, diag::err_expected_ident);
1719 propertyIvar = Tok.getIdentifierInfo();
1720 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1722 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1723 propertyId, propertyIvar, propertyIvarLoc);
1724 if (Tok.isNot(tok::comma))
1726 ConsumeToken(); // consume ','
1728 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1732 /// property-dynamic:
1733 /// @dynamic property-list
1737 /// property-list ',' identifier
1739 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1740 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1741 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1742 ConsumeToken(); // consume dynamic
1744 if (Tok.is(tok::code_completion)) {
1745 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1750 if (Tok.isNot(tok::identifier)) {
1751 Diag(Tok, diag::err_expected_ident);
1752 SkipUntil(tok::semi);
1756 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1757 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1758 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1759 propertyId, 0, SourceLocation());
1761 if (Tok.isNot(tok::comma))
1763 ConsumeToken(); // consume ','
1765 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1769 /// objc-throw-statement:
1770 /// throw expression[opt];
1772 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1774 ConsumeToken(); // consume throw
1775 if (Tok.isNot(tok::semi)) {
1776 Res = ParseExpression();
1777 if (Res.isInvalid()) {
1778 SkipUntil(tok::semi);
1783 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1784 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1787 /// objc-synchronized-statement:
1788 /// @synchronized '(' expression ')' compound-statement
1791 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1792 ConsumeToken(); // consume synchronized
1793 if (Tok.isNot(tok::l_paren)) {
1794 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1798 // The operand is surrounded with parentheses.
1799 ConsumeParen(); // '('
1800 ExprResult operand(ParseExpression());
1802 if (Tok.is(tok::r_paren)) {
1803 ConsumeParen(); // ')'
1805 if (!operand.isInvalid())
1806 Diag(Tok, diag::err_expected_rparen);
1808 // Skip forward until we see a left brace, but don't consume it.
1809 SkipUntil(tok::l_brace, true, true);
1812 // Require a compound statement.
1813 if (Tok.isNot(tok::l_brace)) {
1814 if (!operand.isInvalid())
1815 Diag(Tok, diag::err_expected_lbrace);
1819 // Check the @synchronized operand now.
1820 if (!operand.isInvalid())
1821 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.take());
1823 // Parse the compound statement within a new scope.
1824 ParseScope bodyScope(this, Scope::DeclScope);
1825 StmtResult body(ParseCompoundStatementBody());
1828 // If there was a semantic or parse error earlier with the
1829 // operand, fail now.
1830 if (operand.isInvalid())
1833 if (body.isInvalid())
1834 body = Actions.ActOnNullStmt(Tok.getLocation());
1836 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1839 /// objc-try-catch-statement:
1840 /// @try compound-statement objc-catch-list[opt]
1841 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1843 /// objc-catch-list:
1844 /// @catch ( parameter-declaration ) compound-statement
1845 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1846 /// catch-parameter-declaration:
1847 /// parameter-declaration
1850 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1851 bool catch_or_finally_seen = false;
1853 ConsumeToken(); // consume try
1854 if (Tok.isNot(tok::l_brace)) {
1855 Diag(Tok, diag::err_expected_lbrace);
1858 StmtVector CatchStmts;
1859 StmtResult FinallyStmt;
1860 ParseScope TryScope(this, Scope::DeclScope);
1861 StmtResult TryBody(ParseCompoundStatementBody());
1863 if (TryBody.isInvalid())
1864 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1866 while (Tok.is(tok::at)) {
1867 // At this point, we need to lookahead to determine if this @ is the start
1868 // of an @catch or @finally. We don't want to consume the @ token if this
1869 // is an @try or @encode or something else.
1870 Token AfterAt = GetLookAheadToken(1);
1871 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1872 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1875 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1876 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1877 Decl *FirstPart = 0;
1878 ConsumeToken(); // consume catch
1879 if (Tok.is(tok::l_paren)) {
1881 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1882 if (Tok.isNot(tok::ellipsis)) {
1883 DeclSpec DS(AttrFactory);
1884 ParseDeclarationSpecifiers(DS);
1885 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1886 ParseDeclarator(ParmDecl);
1888 // Inform the actions module about the declarator, so it
1889 // gets added to the current scope.
1890 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1892 ConsumeToken(); // consume '...'
1894 SourceLocation RParenLoc;
1896 if (Tok.is(tok::r_paren))
1897 RParenLoc = ConsumeParen();
1898 else // Skip over garbage, until we get to ')'. Eat the ')'.
1899 SkipUntil(tok::r_paren, true, false);
1901 StmtResult CatchBody(true);
1902 if (Tok.is(tok::l_brace))
1903 CatchBody = ParseCompoundStatementBody();
1905 Diag(Tok, diag::err_expected_lbrace);
1906 if (CatchBody.isInvalid())
1907 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1909 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1913 if (!Catch.isInvalid())
1914 CatchStmts.push_back(Catch.release());
1917 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1921 catch_or_finally_seen = true;
1923 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1924 ConsumeToken(); // consume finally
1925 ParseScope FinallyScope(this, Scope::DeclScope);
1927 StmtResult FinallyBody(true);
1928 if (Tok.is(tok::l_brace))
1929 FinallyBody = ParseCompoundStatementBody();
1931 Diag(Tok, diag::err_expected_lbrace);
1932 if (FinallyBody.isInvalid())
1933 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1934 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1935 FinallyBody.take());
1936 catch_or_finally_seen = true;
1940 if (!catch_or_finally_seen) {
1941 Diag(atLoc, diag::err_missing_catch_finally);
1945 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1947 FinallyStmt.take());
1950 /// objc-autoreleasepool-statement:
1951 /// @autoreleasepool compound-statement
1954 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1955 ConsumeToken(); // consume autoreleasepool
1956 if (Tok.isNot(tok::l_brace)) {
1957 Diag(Tok, diag::err_expected_lbrace);
1960 // Enter a scope to hold everything within the compound stmt. Compound
1961 // statements can always hold declarations.
1962 ParseScope BodyScope(this, Scope::DeclScope);
1964 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1967 if (AutoreleasePoolBody.isInvalid())
1968 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1969 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1970 AutoreleasePoolBody.take());
1973 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1974 /// for later parsing.
1975 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1976 LexedMethod* LM = new LexedMethod(this, MDecl);
1977 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1978 CachedTokens &Toks = LM->Toks;
1979 // Begin by storing the '{' or 'try' or ':' token.
1980 Toks.push_back(Tok);
1981 if (Tok.is(tok::kw_try)) {
1983 if (Tok.is(tok::colon)) {
1984 Toks.push_back(Tok);
1986 while (Tok.isNot(tok::l_brace)) {
1987 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1988 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1991 Toks.push_back(Tok); // also store '{'
1993 else if (Tok.is(tok::colon)) {
1995 while (Tok.isNot(tok::l_brace)) {
1996 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1997 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1999 Toks.push_back(Tok); // also store '{'
2002 // Consume everything up to (and including) the matching right brace.
2003 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2004 while (Tok.is(tok::kw_catch)) {
2005 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2006 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2010 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2012 Decl *Parser::ParseObjCMethodDefinition() {
2013 Decl *MDecl = ParseObjCMethodPrototype();
2015 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2016 "parsing Objective-C method");
2018 // parse optional ';'
2019 if (Tok.is(tok::semi)) {
2020 if (CurParsedObjCImpl) {
2021 Diag(Tok, diag::warn_semicolon_before_method_body)
2022 << FixItHint::CreateRemoval(Tok.getLocation());
2027 // We should have an opening brace now.
2028 if (Tok.isNot(tok::l_brace)) {
2029 Diag(Tok, diag::err_expected_method_body);
2031 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2032 SkipUntil(tok::l_brace, true, true);
2034 // If we didn't find the '{', bail out.
2035 if (Tok.isNot(tok::l_brace))
2041 SkipUntil(tok::r_brace, /*StopAtSemi=*/false);
2045 // Allow the rest of sema to find private method decl implementations.
2046 Actions.AddAnyMethodToGlobalPool(MDecl);
2047 assert (CurParsedObjCImpl
2048 && "ParseObjCMethodDefinition - Method out of @implementation");
2049 // Consume the tokens and store them for later parsing.
2050 StashAwayMethodOrFunctionBodyTokens(MDecl);
2054 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2055 if (Tok.is(tok::code_completion)) {
2056 Actions.CodeCompleteObjCAtStatement(getCurScope());
2061 if (Tok.isObjCAtKeyword(tok::objc_try))
2062 return ParseObjCTryStmt(AtLoc);
2064 if (Tok.isObjCAtKeyword(tok::objc_throw))
2065 return ParseObjCThrowStmt(AtLoc);
2067 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2068 return ParseObjCSynchronizedStmt(AtLoc);
2070 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2071 return ParseObjCAutoreleasePoolStmt(AtLoc);
2073 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2074 if (Res.isInvalid()) {
2075 // If the expression is invalid, skip ahead to the next semicolon. Not
2076 // doing this opens us up to the possibility of infinite loops if
2077 // ParseExpression does not consume any tokens.
2078 SkipUntil(tok::semi);
2082 // Otherwise, eat the semicolon.
2083 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2084 return Actions.ActOnExprStmt(Res);
2087 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2088 switch (Tok.getKind()) {
2089 case tok::code_completion:
2090 Actions.CodeCompleteObjCAtExpression(getCurScope());
2096 tok::TokenKind Kind = Tok.getKind();
2097 SourceLocation OpLoc = ConsumeToken();
2099 if (!Tok.is(tok::numeric_constant)) {
2100 const char *Symbol = 0;
2102 case tok::minus: Symbol = "-"; break;
2103 case tok::plus: Symbol = "+"; break;
2104 default: llvm_unreachable("missing unary operator case");
2106 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2111 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2112 if (Lit.isInvalid()) {
2115 ConsumeToken(); // Consume the literal token.
2117 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
2118 if (Lit.isInvalid())
2121 return ParsePostfixExpressionSuffix(
2122 Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
2125 case tok::string_literal: // primary-expression: string-literal
2126 case tok::wide_string_literal:
2127 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2129 case tok::char_constant:
2130 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2132 case tok::numeric_constant:
2133 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2135 case tok::kw_true: // Objective-C++, etc.
2136 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2137 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2138 case tok::kw_false: // Objective-C++, etc.
2139 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2140 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2143 // Objective-C array literal
2144 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2147 // Objective-C dictionary literal
2148 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2151 // Objective-C boxed expression
2152 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2155 if (Tok.getIdentifierInfo() == 0)
2156 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2158 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2159 case tok::objc_encode:
2160 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2161 case tok::objc_protocol:
2162 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2163 case tok::objc_selector:
2164 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2166 const char *str = 0;
2167 if (GetLookAheadToken(1).is(tok::l_brace)) {
2168 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2171 : (ch == 'f' ? "finally"
2172 : (ch == 'a' ? "autoreleasepool" : 0));
2175 SourceLocation kwLoc = Tok.getLocation();
2176 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2177 FixItHint::CreateReplacement(kwLoc, str));
2180 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2186 /// \brief Parse the receiver of an Objective-C++ message send.
2188 /// This routine parses the receiver of a message send in
2189 /// Objective-C++ either as a type or as an expression. Note that this
2190 /// routine must not be called to parse a send to 'super', since it
2191 /// has no way to return such a result.
2193 /// \param IsExpr Whether the receiver was parsed as an expression.
2195 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2196 /// IsExpr is true), the parsed expression. If the receiver was parsed
2197 /// as a type (\c IsExpr is false), the parsed type.
2199 /// \returns True if an error occurred during parsing or semantic
2200 /// analysis, in which case the arguments do not have valid
2201 /// values. Otherwise, returns false for a successful parse.
2203 /// objc-receiver: [C++]
2204 /// 'super' [not parsed here]
2206 /// simple-type-specifier
2207 /// typename-specifier
2208 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2209 InMessageExpressionRAIIObject InMessage(*this, true);
2211 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2212 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2213 TryAnnotateTypeOrScopeToken();
2215 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2218 ExprResult Receiver = ParseExpression();
2219 if (Receiver.isInvalid())
2223 TypeOrExpr = Receiver.take();
2228 // typename-specifier
2229 // simple-type-specifier
2230 // expression (that starts with one of the above)
2231 DeclSpec DS(AttrFactory);
2232 ParseCXXSimpleTypeSpecifier(DS);
2234 if (Tok.is(tok::l_paren)) {
2235 // If we see an opening parentheses at this point, we are
2236 // actually parsing an expression that starts with a
2237 // function-style cast, e.g.,
2239 // postfix-expression:
2240 // simple-type-specifier ( expression-list [opt] )
2241 // typename-specifier ( expression-list [opt] )
2243 // Parse the remainder of this case, then the (optional)
2244 // postfix-expression suffix, followed by the (optional)
2245 // right-hand side of the binary expression. We have an
2247 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2248 if (!Receiver.isInvalid())
2249 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
2250 if (!Receiver.isInvalid())
2251 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
2252 if (Receiver.isInvalid())
2256 TypeOrExpr = Receiver.take();
2260 // We have a class message. Turn the simple-type-specifier or
2261 // typename-specifier we parsed into a type and parse the
2262 // remainder of the class message.
2263 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2264 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2265 if (Type.isInvalid())
2269 TypeOrExpr = Type.get().getAsOpaquePtr();
2273 /// \brief Determine whether the parser is currently referring to a an
2274 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2276 /// This routine will only return true for a subset of valid message-send
2278 bool Parser::isSimpleObjCMessageExpression() {
2279 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2280 "Incorrect start for isSimpleObjCMessageExpression");
2281 return GetLookAheadToken(1).is(tok::identifier) &&
2282 GetLookAheadToken(2).is(tok::identifier);
2285 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2286 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2287 InMessageExpression)
2293 if (Tok.is(tok::annot_typename))
2294 Type = getTypeAnnotation(Tok);
2295 else if (Tok.is(tok::identifier))
2296 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2301 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2302 const Token &AfterNext = GetLookAheadToken(2);
2303 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2304 if (Tok.is(tok::identifier))
2305 TryAnnotateTypeOrScopeToken();
2307 return Tok.is(tok::annot_typename);
2314 /// objc-message-expr:
2315 /// '[' objc-receiver objc-message-args ']'
2317 /// objc-receiver: [C]
2323 ExprResult Parser::ParseObjCMessageExpression() {
2324 assert(Tok.is(tok::l_square) && "'[' expected");
2325 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2327 if (Tok.is(tok::code_completion)) {
2328 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2333 InMessageExpressionRAIIObject InMessage(*this, true);
2335 if (getLangOpts().CPlusPlus) {
2336 // We completely separate the C and C++ cases because C++ requires
2337 // more complicated (read: slower) parsing.
2339 // Handle send to super.
2340 // FIXME: This doesn't benefit from the same typo-correction we
2341 // get in Objective-C.
2342 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2343 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2344 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2347 // Parse the receiver, which is either a type or an expression.
2349 void *TypeOrExpr = NULL;
2350 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2351 SkipUntil(tok::r_square);
2356 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2358 static_cast<Expr*>(TypeOrExpr));
2360 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2361 ParsedType::getFromOpaquePtr(TypeOrExpr),
2365 if (Tok.is(tok::identifier)) {
2366 IdentifierInfo *Name = Tok.getIdentifierInfo();
2367 SourceLocation NameLoc = Tok.getLocation();
2368 ParsedType ReceiverType;
2369 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2370 Name == Ident_super,
2371 NextToken().is(tok::period),
2373 case Sema::ObjCSuperMessage:
2374 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2377 case Sema::ObjCClassMessage:
2378 if (!ReceiverType) {
2379 SkipUntil(tok::r_square);
2383 ConsumeToken(); // the type name
2385 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2388 case Sema::ObjCInstanceMessage:
2389 // Fall through to parse an expression.
2394 // Otherwise, an arbitrary expression can be the receiver of a send.
2395 ExprResult Res(ParseExpression());
2396 if (Res.isInvalid()) {
2397 SkipUntil(tok::r_square);
2401 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2402 ParsedType(), Res.take());
2405 /// \brief Parse the remainder of an Objective-C message following the
2406 /// '[' objc-receiver.
2408 /// This routine handles sends to super, class messages (sent to a
2409 /// class name), and instance messages (sent to an object), and the
2410 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2411 /// ReceiverExpr, respectively. Only one of these parameters may have
2414 /// \param LBracLoc The location of the opening '['.
2416 /// \param SuperLoc If this is a send to 'super', the location of the
2417 /// 'super' keyword that indicates a send to the superclass.
2419 /// \param ReceiverType If this is a class message, the type of the
2420 /// class we are sending a message to.
2422 /// \param ReceiverExpr If this is an instance message, the expression
2423 /// used to compute the receiver object.
2425 /// objc-message-args:
2427 /// objc-keywordarg-list
2429 /// objc-keywordarg-list:
2431 /// objc-keywordarg-list objc-keywordarg
2433 /// objc-keywordarg:
2434 /// selector-name[opt] ':' objc-keywordexpr
2436 /// objc-keywordexpr:
2437 /// nonempty-expr-list
2439 /// nonempty-expr-list:
2440 /// assignment-expression
2441 /// nonempty-expr-list , assignment-expression
2444 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2445 SourceLocation SuperLoc,
2446 ParsedType ReceiverType,
2447 ExprArg ReceiverExpr) {
2448 InMessageExpressionRAIIObject InMessage(*this, true);
2450 if (Tok.is(tok::code_completion)) {
2451 if (SuperLoc.isValid())
2452 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2454 else if (ReceiverType)
2455 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2458 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2464 // Parse objc-selector
2466 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2468 SmallVector<IdentifierInfo *, 12> KeyIdents;
2469 SmallVector<SourceLocation, 12> KeyLocs;
2470 ExprVector KeyExprs;
2472 if (Tok.is(tok::colon)) {
2474 // Each iteration parses a single keyword argument.
2475 KeyIdents.push_back(selIdent);
2476 KeyLocs.push_back(Loc);
2478 if (Tok.isNot(tok::colon)) {
2479 Diag(Tok, diag::err_expected_colon);
2480 // We must manually skip to a ']', otherwise the expression skipper will
2481 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2482 // the enclosing expression.
2483 SkipUntil(tok::r_square);
2487 ConsumeToken(); // Eat the ':'.
2488 /// Parse the expression after ':'
2490 if (Tok.is(tok::code_completion)) {
2491 if (SuperLoc.isValid())
2492 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2495 /*AtArgumentEpression=*/true);
2496 else if (ReceiverType)
2497 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2500 /*AtArgumentEpression=*/true);
2502 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);
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,
2536 /*AtArgumentEpression=*/false);
2537 else if (ReceiverType)
2538 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2541 /*AtArgumentEpression=*/false);
2543 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2546 /*AtArgumentEpression=*/false);
2551 // Check for another keyword selector.
2552 selIdent = ParseObjCSelectorPiece(Loc);
2553 if (!selIdent && Tok.isNot(tok::colon))
2555 // We have a selector or a colon, continue parsing.
2557 // Parse the, optional, argument list, comma separated.
2558 while (Tok.is(tok::comma)) {
2559 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2560 /// Parse the expression after ','
2561 ExprResult Res(ParseAssignmentExpression());
2562 if (Res.isInvalid()) {
2563 if (Tok.is(tok::colon)) {
2564 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2565 FixItHint::CreateRemoval(commaLoc);
2567 // We must manually skip to a ']', otherwise the expression skipper will
2568 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2569 // the enclosing expression.
2570 SkipUntil(tok::r_square);
2574 // We have a valid expression.
2575 KeyExprs.push_back(Res.release());
2577 } else if (!selIdent) {
2578 Diag(Tok, diag::err_expected_ident); // missing selector name.
2580 // We must manually skip to a ']', otherwise the expression skipper will
2581 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2582 // the enclosing expression.
2583 SkipUntil(tok::r_square);
2587 if (Tok.isNot(tok::r_square)) {
2588 if (Tok.is(tok::identifier))
2589 Diag(Tok, diag::err_expected_colon);
2591 Diag(Tok, diag::err_expected_rsquare);
2592 // We must manually skip to a ']', otherwise the expression skipper will
2593 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2594 // the enclosing expression.
2595 SkipUntil(tok::r_square);
2599 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2601 unsigned nKeys = KeyIdents.size();
2603 KeyIdents.push_back(selIdent);
2604 KeyLocs.push_back(Loc);
2606 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2608 if (SuperLoc.isValid())
2609 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2610 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2611 else if (ReceiverType)
2612 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2613 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2614 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2615 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2618 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2619 ExprResult Res(ParseStringLiteralExpression());
2620 if (Res.isInvalid()) return Res;
2622 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2623 // expressions. At this point, we know that the only valid thing that starts
2624 // with '@' is an @"".
2625 SmallVector<SourceLocation, 4> AtLocs;
2626 ExprVector AtStrings;
2627 AtLocs.push_back(AtLoc);
2628 AtStrings.push_back(Res.release());
2630 while (Tok.is(tok::at)) {
2631 AtLocs.push_back(ConsumeToken()); // eat the @.
2633 // Invalid unless there is a string literal.
2634 if (!isTokenStringLiteral())
2635 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2637 ExprResult Lit(ParseStringLiteralExpression());
2638 if (Lit.isInvalid())
2641 AtStrings.push_back(Lit.release());
2644 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2648 /// ParseObjCBooleanLiteral -
2649 /// objc-scalar-literal : '@' boolean-keyword
2651 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2653 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2655 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2656 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2659 /// ParseObjCCharacterLiteral -
2660 /// objc-scalar-literal : '@' character-literal
2662 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2663 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2664 if (Lit.isInvalid()) {
2667 ConsumeToken(); // Consume the literal token.
2668 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take());
2671 /// ParseObjCNumericLiteral -
2672 /// objc-scalar-literal : '@' scalar-literal
2674 /// scalar-literal : | numeric-constant /* any numeric constant. */
2676 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2677 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2678 if (Lit.isInvalid()) {
2681 ConsumeToken(); // Consume the literal token.
2682 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.take());
2685 /// ParseObjCBoxedExpr -
2686 /// objc-box-expression:
2687 /// @( assignment-expression )
2689 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2690 if (Tok.isNot(tok::l_paren))
2691 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2693 BalancedDelimiterTracker T(*this, tok::l_paren);
2695 ExprResult ValueExpr(ParseAssignmentExpression());
2696 if (T.consumeClose())
2699 if (ValueExpr.isInvalid())
2702 // Wrap the sub-expression in a parenthesized expression, to distinguish
2703 // a boxed expression from a literal.
2704 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2705 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.take());
2706 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2710 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2711 ExprVector ElementExprs; // array elements.
2712 ConsumeBracket(); // consume the l_square.
2714 while (Tok.isNot(tok::r_square)) {
2715 // Parse list of array element expressions (all must be id types).
2716 ExprResult Res(ParseAssignmentExpression());
2717 if (Res.isInvalid()) {
2718 // We must manually skip to a ']', otherwise the expression skipper will
2719 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2720 // the enclosing expression.
2721 SkipUntil(tok::r_square);
2725 // Parse the ellipsis that indicates a pack expansion.
2726 if (Tok.is(tok::ellipsis))
2727 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2728 if (Res.isInvalid())
2731 ElementExprs.push_back(Res.release());
2733 if (Tok.is(tok::comma))
2734 ConsumeToken(); // Eat the ','.
2735 else if (Tok.isNot(tok::r_square))
2736 return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
2738 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2739 MultiExprArg Args(ElementExprs);
2740 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
2743 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2744 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2745 ConsumeBrace(); // consume the l_square.
2746 while (Tok.isNot(tok::r_brace)) {
2747 // Parse the comma separated key : value expressions.
2750 ColonProtectionRAIIObject X(*this);
2751 KeyExpr = ParseAssignmentExpression();
2752 if (KeyExpr.isInvalid()) {
2753 // We must manually skip to a '}', otherwise the expression skipper will
2754 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2755 // the enclosing expression.
2756 SkipUntil(tok::r_brace);
2761 if (Tok.is(tok::colon)) {
2764 Diag(Tok, diag::err_expected_colon);
2765 SkipUntil(tok::r_brace);
2769 ExprResult ValueExpr(ParseAssignmentExpression());
2770 if (ValueExpr.isInvalid()) {
2771 // We must manually skip to a '}', otherwise the expression skipper will
2772 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2773 // the enclosing expression.
2774 SkipUntil(tok::r_brace);
2778 // Parse the ellipsis that designates this as a pack expansion.
2779 SourceLocation EllipsisLoc;
2780 if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
2781 EllipsisLoc = ConsumeToken();
2783 // We have a valid expression. Collect it in a vector so we can
2784 // build the argument list.
2785 ObjCDictionaryElement Element = {
2786 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
2788 Elements.push_back(Element);
2790 if (Tok.is(tok::comma))
2791 ConsumeToken(); // Eat the ','.
2792 else if (Tok.isNot(tok::r_brace))
2793 return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
2795 SourceLocation EndLoc = ConsumeBrace();
2797 // Create the ObjCDictionaryLiteral.
2798 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2799 Elements.data(), Elements.size());
2802 /// objc-encode-expression:
2803 /// \@encode ( type-name )
2805 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2806 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2808 SourceLocation EncLoc = ConsumeToken();
2810 if (Tok.isNot(tok::l_paren))
2811 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2813 BalancedDelimiterTracker T(*this, tok::l_paren);
2816 TypeResult Ty = ParseTypeName();
2823 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
2824 Ty.get(), T.getCloseLocation());
2827 /// objc-protocol-expression
2828 /// \@protocol ( protocol-name )
2830 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2831 SourceLocation ProtoLoc = ConsumeToken();
2833 if (Tok.isNot(tok::l_paren))
2834 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2836 BalancedDelimiterTracker T(*this, tok::l_paren);
2839 if (Tok.isNot(tok::identifier))
2840 return ExprError(Diag(Tok, diag::err_expected_ident));
2842 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2843 SourceLocation ProtoIdLoc = ConsumeToken();
2847 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2848 T.getOpenLocation(), ProtoIdLoc,
2849 T.getCloseLocation());
2852 /// objc-selector-expression
2853 /// @selector '(' objc-keyword-selector ')'
2854 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2855 SourceLocation SelectorLoc = ConsumeToken();
2857 if (Tok.isNot(tok::l_paren))
2858 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2860 SmallVector<IdentifierInfo *, 12> KeyIdents;
2861 SourceLocation sLoc;
2863 BalancedDelimiterTracker T(*this, tok::l_paren);
2866 if (Tok.is(tok::code_completion)) {
2867 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2873 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2874 if (!SelIdent && // missing selector name.
2875 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2876 return ExprError(Diag(Tok, diag::err_expected_ident));
2878 KeyIdents.push_back(SelIdent);
2879 unsigned nColons = 0;
2880 if (Tok.isNot(tok::r_paren)) {
2882 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2884 KeyIdents.push_back(0);
2885 } else if (Tok.isNot(tok::colon))
2886 return ExprError(Diag(Tok, diag::err_expected_colon));
2889 ConsumeToken(); // Eat the ':' or '::'.
2890 if (Tok.is(tok::r_paren))
2893 if (Tok.is(tok::code_completion)) {
2894 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2900 // Check for another keyword selector.
2902 SelIdent = ParseObjCSelectorPiece(Loc);
2903 KeyIdents.push_back(SelIdent);
2904 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2909 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2910 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2911 T.getOpenLocation(),
2912 T.getCloseLocation());
2915 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2916 // MCDecl might be null due to error in method or c-function prototype, etc.
2917 Decl *MCDecl = LM.D;
2918 bool skip = MCDecl &&
2919 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2920 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2924 // Save the current token position.
2925 SourceLocation OrigLoc = Tok.getLocation();
2927 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2928 // Append the current token at the end of the new token stream so that it
2929 // doesn't get lost.
2930 LM.Toks.push_back(Tok);
2931 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2933 // Consume the previously pushed token.
2934 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
2936 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2937 Tok.is(tok::colon)) &&
2938 "Inline objective-c method not starting with '{' or 'try' or ':'");
2939 // Enter a scope for the method or c-fucntion body.
2940 ParseScope BodyScope(this,
2942 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2943 : Scope::FnScope|Scope::DeclScope);
2945 // Tell the actions module that we have entered a method or c-function definition
2946 // with the specified Declarator for the method/function.
2948 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2950 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2951 if (Tok.is(tok::kw_try))
2952 MCDecl = ParseFunctionTryBlock(MCDecl, BodyScope);
2954 if (Tok.is(tok::colon))
2955 ParseConstructorInitializer(MCDecl);
2956 MCDecl = ParseFunctionStatementBody(MCDecl, BodyScope);
2959 if (Tok.getLocation() != OrigLoc) {
2960 // Due to parsing error, we either went over the cached tokens or
2961 // there are still cached tokens left. If it's the latter case skip the
2963 // Since this is an uncommon situation that should be avoided, use the
2964 // expensive isBeforeInTranslationUnit call.
2965 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2967 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))