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();
55 Decl *SingleDecl = nullptr;
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 || getLangOpts().DebuggerSupport)
83 return ParseModuleImport(AtLoc);
84 Diag(AtLoc, diag::err_atimport);
86 return Actions.ConvertDeclToDeclGroup(nullptr);
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) << tok::identifier;
111 SkipUntil(tok::semi);
112 return Actions.ConvertDeclToDeclGroup(nullptr);
114 ClassNames.push_back(Tok.getIdentifierInfo());
115 ClassLocs.push_back(Tok.getLocation());
118 if (!TryConsumeToken(tok::comma))
123 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class"))
124 return Actions.ConvertDeclToDeclGroup(nullptr);
126 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
131 void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
133 Sema::ObjCContainerKind ock = Actions.getObjCContainerKind();
134 if (ock == Sema::OCK_None)
137 Decl *Decl = Actions.getObjCDeclContext();
138 if (CurParsedObjCImpl) {
139 CurParsedObjCImpl->finish(AtLoc);
141 Actions.ActOnAtEnd(getCurScope(), AtLoc);
143 Diag(AtLoc, diag::err_objc_missing_end)
144 << FixItHint::CreateInsertion(AtLoc, "@end\n");
146 Diag(Decl->getLocStart(), diag::note_objc_container_start)
152 /// objc-class-interface-attributes[opt] objc-class-interface
153 /// objc-category-interface
155 /// objc-class-interface:
156 /// '@' 'interface' identifier objc-superclass[opt]
157 /// objc-protocol-refs[opt]
158 /// objc-class-instance-variables[opt]
159 /// objc-interface-decl-list
162 /// objc-category-interface:
163 /// '@' 'interface' identifier '(' identifier[opt] ')'
164 /// objc-protocol-refs[opt]
165 /// objc-interface-decl-list
171 /// objc-class-interface-attributes:
172 /// __attribute__((visibility("default")))
173 /// __attribute__((visibility("hidden")))
174 /// __attribute__((deprecated))
175 /// __attribute__((unavailable))
176 /// __attribute__((objc_exception)) - used by NSException on 64-bit
177 /// __attribute__((objc_root_class))
179 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
180 ParsedAttributes &attrs) {
181 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
182 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
183 CheckNestedObjCContexts(AtLoc);
184 ConsumeToken(); // the "interface" identifier
186 // Code completion after '@interface'.
187 if (Tok.is(tok::code_completion)) {
188 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
193 MaybeSkipAttributes(tok::objc_interface);
195 if (Tok.isNot(tok::identifier)) {
196 Diag(Tok, diag::err_expected)
197 << tok::identifier; // missing class or category name.
201 // We have a class or category name - consume it.
202 IdentifierInfo *nameId = Tok.getIdentifierInfo();
203 SourceLocation nameLoc = ConsumeToken();
204 if (Tok.is(tok::l_paren) &&
205 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
207 BalancedDelimiterTracker T(*this, tok::l_paren);
210 SourceLocation categoryLoc;
211 IdentifierInfo *categoryId = nullptr;
212 if (Tok.is(tok::code_completion)) {
213 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
218 // For ObjC2, the category name is optional (not an error).
219 if (Tok.is(tok::identifier)) {
220 categoryId = Tok.getIdentifierInfo();
221 categoryLoc = ConsumeToken();
223 else if (!getLangOpts().ObjC2) {
224 Diag(Tok, diag::err_expected)
225 << tok::identifier; // 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, 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 = nullptr;
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)
278 << tok::identifier; // missing super class name.
281 superClassId = Tok.getIdentifierInfo();
282 superClassLoc = ConsumeToken();
284 // Next, we need to check for any protocol references.
285 SmallVector<Decl *, 8> ProtocolRefs;
286 SmallVector<SourceLocation, 8> ProtocolLocs;
287 SourceLocation LAngleLoc, EndProtoLoc;
288 if (Tok.is(tok::less) &&
289 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true,
290 LAngleLoc, EndProtoLoc))
293 if (Tok.isNot(tok::less))
294 Actions.ActOnTypedefedProtocols(ProtocolRefs, superClassId, superClassLoc);
297 Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
298 superClassId, superClassLoc,
299 ProtocolRefs.data(), ProtocolRefs.size(),
301 EndProtoLoc, attrs.getList());
303 if (Tok.is(tok::l_brace))
304 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
306 ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
310 /// objc-interface-decl-list:
312 /// objc-interface-decl-list objc-property-decl [OBJC2]
313 /// objc-interface-decl-list objc-method-requirement [OBJC2]
314 /// objc-interface-decl-list objc-method-proto ';'
315 /// objc-interface-decl-list declaration
316 /// objc-interface-decl-list ';'
318 /// objc-method-requirement: [OBJC2]
322 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
324 SmallVector<Decl *, 32> allMethods;
325 SmallVector<Decl *, 16> allProperties;
326 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
327 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
332 // If this is a method prototype, parse it.
333 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
334 if (Decl *methodPrototype =
335 ParseObjCMethodPrototype(MethodImplKind, false))
336 allMethods.push_back(methodPrototype);
337 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
338 // method definitions.
339 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
340 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
341 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
342 if (Tok.is(tok::semi))
347 if (Tok.is(tok::l_paren)) {
348 Diag(Tok, diag::err_expected_minus_or_plus);
349 ParseObjCMethodDecl(Tok.getLocation(),
351 MethodImplKind, false);
354 // Ignore excess semicolons.
355 if (Tok.is(tok::semi)) {
360 // If we got to the end of the file, exit the loop.
364 // Code completion within an Objective-C interface.
365 if (Tok.is(tok::code_completion)) {
366 Actions.CodeCompleteOrdinaryName(getCurScope(),
367 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
368 : Sema::PCC_ObjCInterface);
369 return cutOffParsing();
372 // If we don't have an @ directive, parse it as a function definition.
373 if (Tok.isNot(tok::at)) {
374 // The code below does not consume '}'s because it is afraid of eating the
375 // end of a namespace. Because of the way this code is structured, an
376 // erroneous r_brace would cause an infinite loop if not handled here.
377 if (Tok.is(tok::r_brace))
379 ParsedAttributesWithRange attrs(AttrFactory);
380 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
384 // Otherwise, we have an @ directive, eat the @.
385 SourceLocation AtLoc = ConsumeToken(); // the "@"
386 if (Tok.is(tok::code_completion)) {
387 Actions.CodeCompleteObjCAtDirective(getCurScope());
388 return cutOffParsing();
391 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
393 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
394 AtEnd.setBegin(AtLoc);
395 AtEnd.setEnd(Tok.getLocation());
397 } else if (DirectiveKind == tok::objc_not_keyword) {
398 Diag(Tok, diag::err_objc_unknown_at);
399 SkipUntil(tok::semi);
403 // Eat the identifier.
406 switch (DirectiveKind) {
408 // FIXME: If someone forgets an @end on a protocol, this loop will
409 // continue to eat up tons of stuff and spew lots of nonsense errors. It
410 // would probably be better to bail out if we saw an @class or @interface
411 // or something like that.
412 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
413 // Skip until we see an '@' or '}' or ';'.
414 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
417 case tok::objc_implementation:
418 case tok::objc_interface:
419 Diag(AtLoc, diag::err_objc_missing_end)
420 << FixItHint::CreateInsertion(AtLoc, "@end\n");
421 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
422 << (int) Actions.getObjCContainerKind();
426 case tok::objc_required:
427 case tok::objc_optional:
428 // This is only valid on protocols.
429 // FIXME: Should this check for ObjC2 being enabled?
430 if (contextKey != tok::objc_protocol)
431 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
433 MethodImplKind = DirectiveKind;
436 case tok::objc_property:
437 if (!getLangOpts().ObjC2)
438 Diag(AtLoc, diag::err_objc_properties_require_objc2);
441 SourceLocation LParenLoc;
442 // Parse property attribute list, if any.
443 if (Tok.is(tok::l_paren)) {
444 LParenLoc = Tok.getLocation();
445 ParseObjCPropertyAttribute(OCDS);
448 auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) {
449 if (FD.D.getIdentifier() == nullptr) {
450 Diag(AtLoc, diag::err_objc_property_requires_field_name)
451 << FD.D.getSourceRange();
454 if (FD.BitfieldSize) {
455 Diag(AtLoc, diag::err_objc_property_bitfield)
456 << FD.D.getSourceRange();
460 // Install the property declarator into interfaceDecl.
461 IdentifierInfo *SelName =
462 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
464 Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName);
465 IdentifierInfo *SetterName = OCDS.getSetterName();
468 SetterSel = PP.getSelectorTable().getSelector(1, &SetterName);
470 SetterSel = SelectorTable::constructSetterSelector(
471 PP.getIdentifierTable(), PP.getSelectorTable(),
472 FD.D.getIdentifier());
473 bool isOverridingProperty = false;
474 Decl *Property = Actions.ActOnProperty(
475 getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel,
476 &isOverridingProperty, MethodImplKind);
477 if (!isOverridingProperty)
478 allProperties.push_back(Property);
480 FD.complete(Property);
483 // Parse all the comma separated declarators.
484 ParsingDeclSpec DS(*this);
485 ParseStructDeclaration(DS, ObjCPropertyCallback);
487 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
492 // We break out of the big loop in two cases: when we see @end or when we see
493 // EOF. In the former case, eat the @end. In the later case, emit an error.
494 if (Tok.is(tok::code_completion)) {
495 Actions.CodeCompleteObjCAtDirective(getCurScope());
496 return cutOffParsing();
497 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
498 ConsumeToken(); // the "end" identifier
500 Diag(Tok, diag::err_objc_missing_end)
501 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
502 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
503 << (int) Actions.getObjCContainerKind();
504 AtEnd.setBegin(Tok.getLocation());
505 AtEnd.setEnd(Tok.getLocation());
508 // Insert collected methods declarations into the @interface object.
509 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
510 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
513 /// Parse property attribute declarations.
515 /// property-attr-decl: '(' property-attrlist ')'
516 /// property-attrlist:
517 /// property-attribute
518 /// property-attrlist ',' property-attribute
519 /// property-attribute:
520 /// getter '=' identifier
521 /// setter '=' identifier ':'
531 /// unsafe_unretained
533 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
534 assert(Tok.getKind() == tok::l_paren);
535 BalancedDelimiterTracker T(*this, tok::l_paren);
539 if (Tok.is(tok::code_completion)) {
540 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
541 return cutOffParsing();
543 const IdentifierInfo *II = Tok.getIdentifierInfo();
545 // If this is not an identifier at all, bail out early.
551 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
553 if (II->isStr("readonly"))
554 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
555 else if (II->isStr("assign"))
556 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
557 else if (II->isStr("unsafe_unretained"))
558 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
559 else if (II->isStr("readwrite"))
560 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
561 else if (II->isStr("retain"))
562 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
563 else if (II->isStr("strong"))
564 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
565 else if (II->isStr("copy"))
566 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
567 else if (II->isStr("nonatomic"))
568 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
569 else if (II->isStr("atomic"))
570 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
571 else if (II->isStr("weak"))
572 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
573 else if (II->isStr("getter") || II->isStr("setter")) {
574 bool IsSetter = II->getNameStart()[0] == 's';
576 // getter/setter require extra treatment.
577 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
578 diag::err_objc_expected_equal_for_getter;
580 if (ExpectAndConsume(tok::equal, DiagID)) {
581 SkipUntil(tok::r_paren, StopAtSemi);
585 if (Tok.is(tok::code_completion)) {
587 Actions.CodeCompleteObjCPropertySetter(getCurScope());
589 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
590 return cutOffParsing();
594 SourceLocation SelLoc;
595 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
598 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
600 SkipUntil(tok::r_paren, StopAtSemi);
605 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
606 DS.setSetterName(SelIdent);
608 if (ExpectAndConsume(tok::colon,
609 diag::err_expected_colon_after_setter_name)) {
610 SkipUntil(tok::r_paren, StopAtSemi);
614 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
615 DS.setGetterName(SelIdent);
618 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
619 SkipUntil(tok::r_paren, StopAtSemi);
623 if (Tok.isNot(tok::comma))
632 /// objc-method-proto:
633 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
634 /// objc-class-method objc-method-decl objc-method-attributes[opt]
636 /// objc-instance-method: '-'
637 /// objc-class-method: '+'
639 /// objc-method-attributes: [OBJC2]
640 /// __attribute__((deprecated))
642 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
643 bool MethodDefinition) {
644 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
646 tok::TokenKind methodType = Tok.getKind();
647 SourceLocation mLoc = ConsumeToken();
648 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
650 // Since this rule is used for both method declarations and definitions,
651 // the caller is (optionally) responsible for consuming the ';'.
658 /// enum struct union if else while do for switch case default
659 /// break continue return goto asm sizeof typeof __alignof
660 /// unsigned long const short volatile signed restrict _Complex
661 /// in out inout bycopy byref oneway int char float double void _Bool
663 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
665 switch (Tok.getKind()) {
674 case tok::exclaimequal:
678 case tok::caretequal: {
679 std::string ThisTok(PP.getSpelling(Tok));
680 if (isLetter(ThisTok[0])) {
681 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
682 Tok.setKind(tok::identifier);
683 SelectorLoc = ConsumeToken();
689 case tok::identifier:
699 case tok::kw_const_cast:
700 case tok::kw_continue:
701 case tok::kw_default:
705 case tok::kw_dynamic_cast:
708 case tok::kw_explicit:
720 case tok::kw_mutable:
721 case tok::kw_namespace:
723 case tok::kw_operator:
724 case tok::kw_private:
725 case tok::kw_protected:
727 case tok::kw_register:
728 case tok::kw_reinterpret_cast:
729 case tok::kw_restrict:
735 case tok::kw_static_cast:
738 case tok::kw_template:
743 case tok::kw_typedef:
745 case tok::kw_typename:
748 case tok::kw_unsigned:
750 case tok::kw_virtual:
752 case tok::kw_volatile:
753 case tok::kw_wchar_t:
756 case tok::kw__Complex:
757 case tok::kw___alignof:
758 IdentifierInfo *II = Tok.getIdentifierInfo();
759 SelectorLoc = ConsumeToken();
764 /// objc-for-collection-in: 'in'
766 bool Parser::isTokIdentifier_in() const {
767 // FIXME: May have to do additional look-ahead to only allow for
768 // valid tokens following an 'in'; such as an identifier, unary operators,
770 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
771 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
774 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
775 /// qualifier list and builds their bitmask representation in the input
778 /// objc-type-qualifiers:
779 /// objc-type-qualifier
780 /// objc-type-qualifiers objc-type-qualifier
782 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
783 Declarator::TheContext Context) {
784 assert(Context == Declarator::ObjCParameterContext ||
785 Context == Declarator::ObjCResultContext);
788 if (Tok.is(tok::code_completion)) {
789 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
790 Context == Declarator::ObjCParameterContext);
791 return cutOffParsing();
794 if (Tok.isNot(tok::identifier))
797 const IdentifierInfo *II = Tok.getIdentifierInfo();
798 for (unsigned i = 0; i != objc_NumQuals; ++i) {
799 if (II != ObjCTypeQuals[i])
802 ObjCDeclSpec::ObjCDeclQualifier Qual;
804 default: llvm_unreachable("Unknown decl qualifier");
805 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
806 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
807 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
808 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
809 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
810 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
812 DS.setObjCDeclQualifier(Qual);
818 // If this wasn't a recognized qualifier, bail out.
823 /// Take all the decl attributes out of the given list and add
824 /// them to the given attribute set.
825 static void takeDeclAttributes(ParsedAttributes &attrs,
826 AttributeList *list) {
828 AttributeList *cur = list;
829 list = cur->getNext();
831 if (!cur->isUsedAsTypeAttr()) {
832 // Clear out the next pointer. We're really completely
833 // destroying the internal invariants of the declarator here,
834 // but it doesn't matter because we're done with it.
835 cur->setNext(nullptr);
841 /// takeDeclAttributes - Take all the decl attributes from the given
842 /// declarator and add them to the given list.
843 static void takeDeclAttributes(ParsedAttributes &attrs,
845 // First, take ownership of all attributes.
846 attrs.getPool().takeAllFrom(D.getAttributePool());
847 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
849 // Now actually move the attributes over.
850 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
851 takeDeclAttributes(attrs, D.getAttributes());
852 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
853 takeDeclAttributes(attrs,
854 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
858 /// '(' objc-type-qualifiers[opt] type-name ')'
859 /// '(' objc-type-qualifiers[opt] ')'
861 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
862 Declarator::TheContext context,
863 ParsedAttributes *paramAttrs) {
864 assert(context == Declarator::ObjCParameterContext ||
865 context == Declarator::ObjCResultContext);
866 assert((paramAttrs != nullptr) ==
867 (context == Declarator::ObjCParameterContext));
869 assert(Tok.is(tok::l_paren) && "expected (");
871 BalancedDelimiterTracker T(*this, tok::l_paren);
874 SourceLocation TypeStartLoc = Tok.getLocation();
875 ObjCDeclContextSwitch ObjCDC(*this);
877 // Parse type qualifiers, in, inout, etc.
878 ParseObjCTypeQualifierList(DS, context);
881 if (isTypeSpecifierQualifier()) {
882 // Parse an abstract declarator.
883 DeclSpec declSpec(AttrFactory);
884 declSpec.setObjCQualifiers(&DS);
885 ParseSpecifierQualifierList(declSpec);
886 declSpec.SetRangeEnd(Tok.getLocation());
887 Declarator declarator(declSpec, context);
888 ParseDeclarator(declarator);
890 // If that's not invalid, extract a type.
891 if (!declarator.isInvalidType()) {
892 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
893 if (!type.isInvalid())
896 // If we're parsing a parameter, steal all the decl attributes
897 // and add them to the decl spec.
898 if (context == Declarator::ObjCParameterContext)
899 takeDeclAttributes(*paramAttrs, declarator);
901 } else if (context == Declarator::ObjCResultContext &&
902 Tok.is(tok::identifier)) {
903 if (!Ident_instancetype)
904 Ident_instancetype = PP.getIdentifierInfo("instancetype");
906 if (Tok.getIdentifierInfo() == Ident_instancetype) {
907 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
912 if (Tok.is(tok::r_paren))
914 else if (Tok.getLocation() == TypeStartLoc) {
915 // If we didn't eat any tokens, then this isn't a type.
916 Diag(Tok, diag::err_expected_type);
917 SkipUntil(tok::r_paren, StopAtSemi);
919 // Otherwise, we found *something*, but didn't get a ')' in the right
920 // place. Emit an error then return what we have as the type.
926 /// objc-method-decl:
928 /// objc-keyword-selector objc-parmlist[opt]
929 /// objc-type-name objc-selector
930 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
932 /// objc-keyword-selector:
933 /// objc-keyword-decl
934 /// objc-keyword-selector objc-keyword-decl
936 /// objc-keyword-decl:
937 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
938 /// objc-selector ':' objc-keyword-attributes[opt] identifier
939 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
940 /// ':' objc-keyword-attributes[opt] identifier
943 /// objc-parms objc-ellipsis[opt]
946 /// objc-parms , parameter-declaration
951 /// objc-keyword-attributes: [OBJC2]
952 /// __attribute__((unused))
954 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
955 tok::TokenKind mType,
956 tok::ObjCKeywordKind MethodImplKind,
957 bool MethodDefinition) {
958 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
960 if (Tok.is(tok::code_completion)) {
961 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
962 /*ReturnType=*/ ParsedType());
967 // Parse the return type if present.
968 ParsedType ReturnType;
970 if (Tok.is(tok::l_paren))
971 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
974 // If attributes exist before the method, parse them.
975 ParsedAttributes methodAttrs(AttrFactory);
976 if (getLangOpts().ObjC2)
977 MaybeParseGNUAttributes(methodAttrs);
979 if (Tok.is(tok::code_completion)) {
980 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
986 // Now parse the selector.
987 SourceLocation selLoc;
988 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
990 // An unnamed colon is valid.
991 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
992 Diag(Tok, diag::err_expected_selector_for_method)
993 << SourceRange(mLoc, Tok.getLocation());
994 // Skip until we get a ; or @.
995 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
999 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1000 if (Tok.isNot(tok::colon)) {
1001 // If attributes exist after the method, parse them.
1002 if (getLangOpts().ObjC2)
1003 MaybeParseGNUAttributes(methodAttrs);
1005 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1007 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1008 mType, DSRet, ReturnType,
1009 selLoc, Sel, nullptr,
1010 CParamInfo.data(), CParamInfo.size(),
1011 methodAttrs.getList(), MethodImplKind,
1012 false, MethodDefinition);
1013 PD.complete(Result);
1017 SmallVector<IdentifierInfo *, 12> KeyIdents;
1018 SmallVector<SourceLocation, 12> KeyLocs;
1019 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1020 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1021 Scope::FunctionDeclarationScope | Scope::DeclScope);
1023 AttributePool allParamAttrs(AttrFactory);
1025 ParsedAttributes paramAttrs(AttrFactory);
1026 Sema::ObjCArgInfo ArgInfo;
1028 // Each iteration parses a single keyword argument.
1029 if (ExpectAndConsume(tok::colon))
1032 ArgInfo.Type = ParsedType();
1033 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1034 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1035 Declarator::ObjCParameterContext,
1038 // If attributes exist before the argument name, parse them.
1039 // Regardless, collect all the attributes we've parsed so far.
1040 ArgInfo.ArgAttrs = nullptr;
1041 if (getLangOpts().ObjC2) {
1042 MaybeParseGNUAttributes(paramAttrs);
1043 ArgInfo.ArgAttrs = paramAttrs.getList();
1046 // Code completion for the next piece of the selector.
1047 if (Tok.is(tok::code_completion)) {
1048 KeyIdents.push_back(SelIdent);
1049 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1050 mType == tok::minus,
1051 /*AtParameterName=*/true,
1052 ReturnType, KeyIdents);
1057 if (Tok.isNot(tok::identifier)) {
1058 Diag(Tok, diag::err_expected)
1059 << tok::identifier; // missing argument name.
1063 ArgInfo.Name = Tok.getIdentifierInfo();
1064 ArgInfo.NameLoc = Tok.getLocation();
1065 ConsumeToken(); // Eat the identifier.
1067 ArgInfos.push_back(ArgInfo);
1068 KeyIdents.push_back(SelIdent);
1069 KeyLocs.push_back(selLoc);
1071 // Make sure the attributes persist.
1072 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1074 // Code completion for the next piece of the selector.
1075 if (Tok.is(tok::code_completion)) {
1076 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1077 mType == tok::minus,
1078 /*AtParameterName=*/false,
1079 ReturnType, KeyIdents);
1084 // Check for another keyword selector.
1085 SelIdent = ParseObjCSelectorPiece(selLoc);
1086 if (!SelIdent && Tok.isNot(tok::colon))
1089 SourceLocation ColonLoc = Tok.getLocation();
1090 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1091 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1092 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1093 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1096 // We have a selector or a colon, continue parsing.
1099 bool isVariadic = false;
1100 bool cStyleParamWarned = false;
1101 // Parse the (optional) parameter list.
1102 while (Tok.is(tok::comma)) {
1104 if (Tok.is(tok::ellipsis)) {
1109 if (!cStyleParamWarned) {
1110 Diag(Tok, diag::warn_cstyle_param);
1111 cStyleParamWarned = true;
1113 DeclSpec DS(AttrFactory);
1114 ParseDeclarationSpecifiers(DS);
1115 // Parse the declarator.
1116 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1117 ParseDeclarator(ParmDecl);
1118 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1119 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1120 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1121 ParmDecl.getIdentifierLoc(),
1126 // FIXME: Add support for optional parameter list...
1127 // If attributes exist after the method, parse them.
1128 if (getLangOpts().ObjC2)
1129 MaybeParseGNUAttributes(methodAttrs);
1131 if (KeyIdents.size() == 0)
1134 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1137 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1138 mType, DSRet, ReturnType,
1139 KeyLocs, Sel, &ArgInfos[0],
1140 CParamInfo.data(), CParamInfo.size(),
1141 methodAttrs.getList(),
1142 MethodImplKind, isVariadic, MethodDefinition);
1144 PD.complete(Result);
1148 /// objc-protocol-refs:
1149 /// '<' identifier-list '>'
1152 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1153 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1154 bool WarnOnDeclarations, bool ForObjCContainer,
1155 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1156 assert(Tok.is(tok::less) && "expected <");
1158 LAngleLoc = ConsumeToken(); // the "<"
1160 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1163 if (Tok.is(tok::code_completion)) {
1164 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1165 ProtocolIdents.size());
1170 if (Tok.isNot(tok::identifier)) {
1171 Diag(Tok, diag::err_expected) << tok::identifier;
1172 SkipUntil(tok::greater, StopAtSemi);
1175 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1176 Tok.getLocation()));
1177 ProtocolLocs.push_back(Tok.getLocation());
1180 if (!TryConsumeToken(tok::comma))
1185 if (ParseGreaterThanInTemplateList(EndLoc, /*ConsumeLastToken=*/true))
1188 // Convert the list of protocols identifiers into a list of protocol decls.
1189 Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer,
1190 &ProtocolIdents[0], ProtocolIdents.size(),
1195 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1196 /// in a decl-specifier-seq, starting at the '<'.
1197 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1198 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1199 assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1200 SourceLocation LAngleLoc, EndProtoLoc;
1201 SmallVector<Decl *, 8> ProtocolDecl;
1202 SmallVector<SourceLocation, 8> ProtocolLocs;
1203 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1205 LAngleLoc, EndProtoLoc);
1206 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1207 ProtocolLocs.data(), LAngleLoc);
1208 if (EndProtoLoc.isValid())
1209 DS.SetRangeEnd(EndProtoLoc);
1213 void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc,
1214 BalancedDelimiterTracker &T,
1215 SmallVectorImpl<Decl *> &AllIvarDecls,
1216 bool RBraceMissing) {
1220 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1221 Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls);
1222 Actions.ActOnObjCContainerFinishDefinition();
1223 // Call ActOnFields() even if we don't have any decls. This is useful
1224 // for code rewriting tools that need to be aware of the empty list.
1225 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1227 T.getOpenLocation(), T.getCloseLocation(), nullptr);
1230 /// objc-class-instance-variables:
1231 /// '{' objc-instance-variable-decl-list[opt] '}'
1233 /// objc-instance-variable-decl-list:
1234 /// objc-visibility-spec
1235 /// objc-instance-variable-decl ';'
1237 /// objc-instance-variable-decl-list objc-visibility-spec
1238 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1239 /// objc-instance-variable-decl-list ';'
1241 /// objc-visibility-spec:
1245 /// @package [OBJC2]
1247 /// objc-instance-variable-decl:
1248 /// struct-declaration
1250 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1251 tok::ObjCKeywordKind visibility,
1252 SourceLocation atLoc) {
1253 assert(Tok.is(tok::l_brace) && "expected {");
1254 SmallVector<Decl *, 32> AllIvarDecls;
1256 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1257 ObjCDeclContextSwitch ObjCDC(*this);
1259 BalancedDelimiterTracker T(*this, tok::l_brace);
1261 // While we still have something to read, read the instance variables.
1262 while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
1263 // Each iteration of this loop reads one objc-instance-variable-decl.
1265 // Check for extraneous top-level semicolon.
1266 if (Tok.is(tok::semi)) {
1267 ConsumeExtraSemi(InstanceVariableList);
1271 // Set the default visibility to private.
1272 if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1273 if (Tok.is(tok::code_completion)) {
1274 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1275 return cutOffParsing();
1278 switch (Tok.getObjCKeywordID()) {
1279 case tok::objc_private:
1280 case tok::objc_public:
1281 case tok::objc_protected:
1282 case tok::objc_package:
1283 visibility = Tok.getObjCKeywordID();
1288 Diag(Tok, diag::err_objc_unexpected_atend);
1289 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1290 Tok.setKind(tok::at);
1293 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1294 T, AllIvarDecls, true);
1298 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1303 if (Tok.is(tok::code_completion)) {
1304 Actions.CodeCompleteOrdinaryName(getCurScope(),
1305 Sema::PCC_ObjCInstanceVariableList);
1306 return cutOffParsing();
1309 auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) {
1310 Actions.ActOnObjCContainerStartDefinition(interfaceDecl);
1311 // Install the declarator into the interface decl.
1312 Decl *Field = Actions.ActOnIvar(
1313 getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D,
1314 FD.BitfieldSize, visibility);
1315 Actions.ActOnObjCContainerFinishDefinition();
1317 AllIvarDecls.push_back(Field);
1321 // Parse all the comma separated declarators.
1322 ParsingDeclSpec DS(*this);
1323 ParseStructDeclaration(DS, ObjCIvarCallback);
1325 if (Tok.is(tok::semi)) {
1328 Diag(Tok, diag::err_expected_semi_decl_list);
1329 // Skip to end of block or statement
1330 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1333 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1334 T, AllIvarDecls, false);
1338 /// objc-protocol-declaration:
1339 /// objc-protocol-definition
1340 /// objc-protocol-forward-reference
1342 /// objc-protocol-definition:
1343 /// \@protocol identifier
1344 /// objc-protocol-refs[opt]
1345 /// objc-interface-decl-list
1348 /// objc-protocol-forward-reference:
1349 /// \@protocol identifier-list ';'
1351 /// "\@protocol identifier ;" should be resolved as "\@protocol
1352 /// identifier-list ;": objc-interface-decl-list may not start with a
1353 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1354 Parser::DeclGroupPtrTy
1355 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1356 ParsedAttributes &attrs) {
1357 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1358 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1359 ConsumeToken(); // the "protocol" identifier
1361 if (Tok.is(tok::code_completion)) {
1362 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1364 return DeclGroupPtrTy();
1367 MaybeSkipAttributes(tok::objc_protocol);
1369 if (Tok.isNot(tok::identifier)) {
1370 Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name.
1371 return DeclGroupPtrTy();
1373 // Save the protocol name, then consume it.
1374 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1375 SourceLocation nameLoc = ConsumeToken();
1377 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
1378 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1379 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1383 CheckNestedObjCContexts(AtLoc);
1385 if (Tok.is(tok::comma)) { // list of forward declarations.
1386 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1387 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1389 // Parse the list of forward declarations.
1391 ConsumeToken(); // the ','
1392 if (Tok.isNot(tok::identifier)) {
1393 Diag(Tok, diag::err_expected) << tok::identifier;
1394 SkipUntil(tok::semi);
1395 return DeclGroupPtrTy();
1397 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1398 Tok.getLocation()));
1399 ConsumeToken(); // the identifier
1401 if (Tok.isNot(tok::comma))
1405 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
1406 return DeclGroupPtrTy();
1408 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1410 ProtocolRefs.size(),
1414 // Last, and definitely not least, parse a protocol declaration.
1415 SourceLocation LAngleLoc, EndProtoLoc;
1417 SmallVector<Decl *, 8> ProtocolRefs;
1418 SmallVector<SourceLocation, 8> ProtocolLocs;
1419 if (Tok.is(tok::less) &&
1420 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true,
1421 LAngleLoc, EndProtoLoc))
1422 return DeclGroupPtrTy();
1425 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1426 ProtocolRefs.data(),
1427 ProtocolRefs.size(),
1428 ProtocolLocs.data(),
1429 EndProtoLoc, attrs.getList());
1431 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1432 return Actions.ConvertDeclToDeclGroup(ProtoType);
1435 /// objc-implementation:
1436 /// objc-class-implementation-prologue
1437 /// objc-category-implementation-prologue
1439 /// objc-class-implementation-prologue:
1440 /// @implementation identifier objc-superclass[opt]
1441 /// objc-class-instance-variables[opt]
1443 /// objc-category-implementation-prologue:
1444 /// @implementation identifier ( identifier )
1445 Parser::DeclGroupPtrTy
1446 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1447 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1448 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1449 CheckNestedObjCContexts(AtLoc);
1450 ConsumeToken(); // the "implementation" identifier
1452 // Code completion after '@implementation'.
1453 if (Tok.is(tok::code_completion)) {
1454 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1456 return DeclGroupPtrTy();
1459 MaybeSkipAttributes(tok::objc_implementation);
1461 if (Tok.isNot(tok::identifier)) {
1462 Diag(Tok, diag::err_expected)
1463 << tok::identifier; // missing class or category name.
1464 return DeclGroupPtrTy();
1466 // We have a class or category name - consume it.
1467 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1468 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1469 Decl *ObjCImpDecl = nullptr;
1471 if (Tok.is(tok::l_paren)) {
1472 // we have a category implementation.
1474 SourceLocation categoryLoc, rparenLoc;
1475 IdentifierInfo *categoryId = nullptr;
1477 if (Tok.is(tok::code_completion)) {
1478 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1480 return DeclGroupPtrTy();
1483 if (Tok.is(tok::identifier)) {
1484 categoryId = Tok.getIdentifierInfo();
1485 categoryLoc = ConsumeToken();
1487 Diag(Tok, diag::err_expected)
1488 << tok::identifier; // missing category name.
1489 return DeclGroupPtrTy();
1491 if (Tok.isNot(tok::r_paren)) {
1492 Diag(Tok, diag::err_expected) << tok::r_paren;
1493 SkipUntil(tok::r_paren); // don't stop at ';'
1494 return DeclGroupPtrTy();
1496 rparenLoc = ConsumeParen();
1497 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1498 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1499 AttributeFactory attr;
1501 (void)ParseObjCProtocolQualifiers(DS);
1503 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1504 AtLoc, nameId, nameLoc, categoryId,
1508 // We have a class implementation
1509 SourceLocation superClassLoc;
1510 IdentifierInfo *superClassId = nullptr;
1511 if (TryConsumeToken(tok::colon)) {
1512 // We have a super class
1513 if (Tok.isNot(tok::identifier)) {
1514 Diag(Tok, diag::err_expected)
1515 << tok::identifier; // missing super class name.
1516 return DeclGroupPtrTy();
1518 superClassId = Tok.getIdentifierInfo();
1519 superClassLoc = ConsumeToken(); // Consume super class name
1521 ObjCImpDecl = Actions.ActOnStartClassImplementation(
1522 AtLoc, nameId, nameLoc,
1523 superClassId, superClassLoc);
1525 if (Tok.is(tok::l_brace)) // we have ivars
1526 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
1527 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1528 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1530 AttributeFactory attr;
1532 (void)ParseObjCProtocolQualifiers(DS);
1535 assert(ObjCImpDecl);
1537 SmallVector<Decl *, 8> DeclsInGroup;
1540 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1541 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
1542 ParsedAttributesWithRange attrs(AttrFactory);
1543 MaybeParseCXX11Attributes(attrs);
1544 MaybeParseMicrosoftAttributes(attrs);
1545 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1546 DeclGroupRef DG = DGP.get();
1547 DeclsInGroup.append(DG.begin(), DG.end());
1552 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1555 Parser::DeclGroupPtrTy
1556 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1557 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1558 "ParseObjCAtEndDeclaration(): Expected @end");
1559 ConsumeToken(); // the "end" identifier
1560 if (CurParsedObjCImpl)
1561 CurParsedObjCImpl->finish(atEnd);
1563 // missing @implementation
1564 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1565 return DeclGroupPtrTy();
1568 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1570 finish(P.Tok.getLocation());
1571 if (P.isEofOrEom()) {
1572 P.Diag(P.Tok, diag::err_objc_missing_end)
1573 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1574 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1575 << Sema::OCK_Implementation;
1578 P.CurParsedObjCImpl = nullptr;
1579 assert(LateParsedObjCMethods.empty());
1582 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1584 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1585 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1586 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1589 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1592 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1593 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1594 false/*c-functions*/);
1596 /// \brief Clear and free the cached objc methods.
1597 for (LateParsedObjCMethodContainer::iterator
1598 I = LateParsedObjCMethods.begin(),
1599 E = LateParsedObjCMethods.end(); I != E; ++I)
1601 LateParsedObjCMethods.clear();
1606 /// compatibility-alias-decl:
1607 /// @compatibility_alias alias-name class-name ';'
1609 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1610 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1611 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1612 ConsumeToken(); // consume compatibility_alias
1613 if (Tok.isNot(tok::identifier)) {
1614 Diag(Tok, diag::err_expected) << tok::identifier;
1617 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1618 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1619 if (Tok.isNot(tok::identifier)) {
1620 Diag(Tok, diag::err_expected) << tok::identifier;
1623 IdentifierInfo *classId = Tok.getIdentifierInfo();
1624 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1625 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
1626 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1630 /// property-synthesis:
1631 /// @synthesize property-ivar-list ';'
1633 /// property-ivar-list:
1635 /// property-ivar-list ',' property-ivar
1639 /// identifier '=' identifier
1641 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1642 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1643 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
1644 ConsumeToken(); // consume synthesize
1647 if (Tok.is(tok::code_completion)) {
1648 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1653 if (Tok.isNot(tok::identifier)) {
1654 Diag(Tok, diag::err_synthesized_property_name);
1655 SkipUntil(tok::semi);
1659 IdentifierInfo *propertyIvar = nullptr;
1660 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1661 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1662 SourceLocation propertyIvarLoc;
1663 if (TryConsumeToken(tok::equal)) {
1664 // property '=' ivar-name
1665 if (Tok.is(tok::code_completion)) {
1666 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1671 if (Tok.isNot(tok::identifier)) {
1672 Diag(Tok, diag::err_expected) << tok::identifier;
1675 propertyIvar = Tok.getIdentifierInfo();
1676 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1678 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1679 propertyId, propertyIvar, propertyIvarLoc);
1680 if (Tok.isNot(tok::comma))
1682 ConsumeToken(); // consume ','
1684 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
1688 /// property-dynamic:
1689 /// @dynamic property-list
1693 /// property-list ',' identifier
1695 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1696 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1697 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1698 ConsumeToken(); // consume dynamic
1700 if (Tok.is(tok::code_completion)) {
1701 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1706 if (Tok.isNot(tok::identifier)) {
1707 Diag(Tok, diag::err_expected) << tok::identifier;
1708 SkipUntil(tok::semi);
1712 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1713 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1714 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1715 propertyId, nullptr, SourceLocation());
1717 if (Tok.isNot(tok::comma))
1719 ConsumeToken(); // consume ','
1721 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
1725 /// objc-throw-statement:
1726 /// throw expression[opt];
1728 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1730 ConsumeToken(); // consume throw
1731 if (Tok.isNot(tok::semi)) {
1732 Res = ParseExpression();
1733 if (Res.isInvalid()) {
1734 SkipUntil(tok::semi);
1739 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
1740 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
1743 /// objc-synchronized-statement:
1744 /// @synchronized '(' expression ')' compound-statement
1747 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1748 ConsumeToken(); // consume synchronized
1749 if (Tok.isNot(tok::l_paren)) {
1750 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1754 // The operand is surrounded with parentheses.
1755 ConsumeParen(); // '('
1756 ExprResult operand(ParseExpression());
1758 if (Tok.is(tok::r_paren)) {
1759 ConsumeParen(); // ')'
1761 if (!operand.isInvalid())
1762 Diag(Tok, diag::err_expected) << tok::r_paren;
1764 // Skip forward until we see a left brace, but don't consume it.
1765 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1768 // Require a compound statement.
1769 if (Tok.isNot(tok::l_brace)) {
1770 if (!operand.isInvalid())
1771 Diag(Tok, diag::err_expected) << tok::l_brace;
1775 // Check the @synchronized operand now.
1776 if (!operand.isInvalid())
1777 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
1779 // Parse the compound statement within a new scope.
1780 ParseScope bodyScope(this, Scope::DeclScope);
1781 StmtResult body(ParseCompoundStatementBody());
1784 // If there was a semantic or parse error earlier with the
1785 // operand, fail now.
1786 if (operand.isInvalid())
1789 if (body.isInvalid())
1790 body = Actions.ActOnNullStmt(Tok.getLocation());
1792 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1795 /// objc-try-catch-statement:
1796 /// @try compound-statement objc-catch-list[opt]
1797 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1799 /// objc-catch-list:
1800 /// @catch ( parameter-declaration ) compound-statement
1801 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1802 /// catch-parameter-declaration:
1803 /// parameter-declaration
1806 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1807 bool catch_or_finally_seen = false;
1809 ConsumeToken(); // consume try
1810 if (Tok.isNot(tok::l_brace)) {
1811 Diag(Tok, diag::err_expected) << tok::l_brace;
1814 StmtVector CatchStmts;
1815 StmtResult FinallyStmt;
1816 ParseScope TryScope(this, Scope::DeclScope);
1817 StmtResult TryBody(ParseCompoundStatementBody());
1819 if (TryBody.isInvalid())
1820 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1822 while (Tok.is(tok::at)) {
1823 // At this point, we need to lookahead to determine if this @ is the start
1824 // of an @catch or @finally. We don't want to consume the @ token if this
1825 // is an @try or @encode or something else.
1826 Token AfterAt = GetLookAheadToken(1);
1827 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1828 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1831 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1832 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1833 Decl *FirstPart = nullptr;
1834 ConsumeToken(); // consume catch
1835 if (Tok.is(tok::l_paren)) {
1837 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1838 if (Tok.isNot(tok::ellipsis)) {
1839 DeclSpec DS(AttrFactory);
1840 ParseDeclarationSpecifiers(DS);
1841 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1842 ParseDeclarator(ParmDecl);
1844 // Inform the actions module about the declarator, so it
1845 // gets added to the current scope.
1846 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1848 ConsumeToken(); // consume '...'
1850 SourceLocation RParenLoc;
1852 if (Tok.is(tok::r_paren))
1853 RParenLoc = ConsumeParen();
1854 else // Skip over garbage, until we get to ')'. Eat the ')'.
1855 SkipUntil(tok::r_paren, StopAtSemi);
1857 StmtResult CatchBody(true);
1858 if (Tok.is(tok::l_brace))
1859 CatchBody = ParseCompoundStatementBody();
1861 Diag(Tok, diag::err_expected) << tok::l_brace;
1862 if (CatchBody.isInvalid())
1863 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1865 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1869 if (!Catch.isInvalid())
1870 CatchStmts.push_back(Catch.get());
1873 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1877 catch_or_finally_seen = true;
1879 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1880 ConsumeToken(); // consume finally
1881 ParseScope FinallyScope(this, Scope::DeclScope);
1883 StmtResult FinallyBody(true);
1884 if (Tok.is(tok::l_brace))
1885 FinallyBody = ParseCompoundStatementBody();
1887 Diag(Tok, diag::err_expected) << tok::l_brace;
1888 if (FinallyBody.isInvalid())
1889 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1890 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1892 catch_or_finally_seen = true;
1896 if (!catch_or_finally_seen) {
1897 Diag(atLoc, diag::err_missing_catch_finally);
1901 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
1906 /// objc-autoreleasepool-statement:
1907 /// @autoreleasepool compound-statement
1910 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1911 ConsumeToken(); // consume autoreleasepool
1912 if (Tok.isNot(tok::l_brace)) {
1913 Diag(Tok, diag::err_expected) << tok::l_brace;
1916 // Enter a scope to hold everything within the compound stmt. Compound
1917 // statements can always hold declarations.
1918 ParseScope BodyScope(this, Scope::DeclScope);
1920 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1923 if (AutoreleasePoolBody.isInvalid())
1924 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1925 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1926 AutoreleasePoolBody.get());
1929 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1930 /// for later parsing.
1931 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1932 LexedMethod* LM = new LexedMethod(this, MDecl);
1933 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1934 CachedTokens &Toks = LM->Toks;
1935 // Begin by storing the '{' or 'try' or ':' token.
1936 Toks.push_back(Tok);
1937 if (Tok.is(tok::kw_try)) {
1939 if (Tok.is(tok::colon)) {
1940 Toks.push_back(Tok);
1942 while (Tok.isNot(tok::l_brace)) {
1943 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1944 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1947 Toks.push_back(Tok); // also store '{'
1949 else if (Tok.is(tok::colon)) {
1951 while (Tok.isNot(tok::l_brace)) {
1952 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1953 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1955 Toks.push_back(Tok); // also store '{'
1958 // Consume everything up to (and including) the matching right brace.
1959 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1960 while (Tok.is(tok::kw_catch)) {
1961 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1962 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1966 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1968 Decl *Parser::ParseObjCMethodDefinition() {
1969 Decl *MDecl = ParseObjCMethodPrototype();
1971 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1972 "parsing Objective-C method");
1974 // parse optional ';'
1975 if (Tok.is(tok::semi)) {
1976 if (CurParsedObjCImpl) {
1977 Diag(Tok, diag::warn_semicolon_before_method_body)
1978 << FixItHint::CreateRemoval(Tok.getLocation());
1983 // We should have an opening brace now.
1984 if (Tok.isNot(tok::l_brace)) {
1985 Diag(Tok, diag::err_expected_method_body);
1987 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1988 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1990 // If we didn't find the '{', bail out.
1991 if (Tok.isNot(tok::l_brace))
1997 SkipUntil(tok::r_brace);
2001 // Allow the rest of sema to find private method decl implementations.
2002 Actions.AddAnyMethodToGlobalPool(MDecl);
2003 assert (CurParsedObjCImpl
2004 && "ParseObjCMethodDefinition - Method out of @implementation");
2005 // Consume the tokens and store them for later parsing.
2006 StashAwayMethodOrFunctionBodyTokens(MDecl);
2010 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2011 if (Tok.is(tok::code_completion)) {
2012 Actions.CodeCompleteObjCAtStatement(getCurScope());
2017 if (Tok.isObjCAtKeyword(tok::objc_try))
2018 return ParseObjCTryStmt(AtLoc);
2020 if (Tok.isObjCAtKeyword(tok::objc_throw))
2021 return ParseObjCThrowStmt(AtLoc);
2023 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2024 return ParseObjCSynchronizedStmt(AtLoc);
2026 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2027 return ParseObjCAutoreleasePoolStmt(AtLoc);
2029 if (Tok.isObjCAtKeyword(tok::objc_import) &&
2030 getLangOpts().DebuggerSupport) {
2031 SkipUntil(tok::semi);
2032 return Actions.ActOnNullStmt(Tok.getLocation());
2035 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2036 if (Res.isInvalid()) {
2037 // If the expression is invalid, skip ahead to the next semicolon. Not
2038 // doing this opens us up to the possibility of infinite loops if
2039 // ParseExpression does not consume any tokens.
2040 SkipUntil(tok::semi);
2044 // Otherwise, eat the semicolon.
2045 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2046 return Actions.ActOnExprStmt(Res);
2049 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2050 switch (Tok.getKind()) {
2051 case tok::code_completion:
2052 Actions.CodeCompleteObjCAtExpression(getCurScope());
2058 tok::TokenKind Kind = Tok.getKind();
2059 SourceLocation OpLoc = ConsumeToken();
2061 if (!Tok.is(tok::numeric_constant)) {
2062 const char *Symbol = nullptr;
2064 case tok::minus: Symbol = "-"; break;
2065 case tok::plus: Symbol = "+"; break;
2066 default: llvm_unreachable("missing unary operator case");
2068 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2073 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2074 if (Lit.isInvalid()) {
2077 ConsumeToken(); // Consume the literal token.
2079 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2080 if (Lit.isInvalid())
2083 return ParsePostfixExpressionSuffix(
2084 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2087 case tok::string_literal: // primary-expression: string-literal
2088 case tok::wide_string_literal:
2089 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2091 case tok::char_constant:
2092 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2094 case tok::numeric_constant:
2095 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2097 case tok::kw_true: // Objective-C++, etc.
2098 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2099 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2100 case tok::kw_false: // Objective-C++, etc.
2101 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2102 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2105 // Objective-C array literal
2106 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2109 // Objective-C dictionary literal
2110 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2113 // Objective-C boxed expression
2114 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2117 if (Tok.getIdentifierInfo() == nullptr)
2118 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2120 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2121 case tok::objc_encode:
2122 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2123 case tok::objc_protocol:
2124 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2125 case tok::objc_selector:
2126 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2128 const char *str = nullptr;
2129 if (GetLookAheadToken(1).is(tok::l_brace)) {
2130 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2133 : (ch == 'f' ? "finally"
2134 : (ch == 'a' ? "autoreleasepool" : nullptr));
2137 SourceLocation kwLoc = Tok.getLocation();
2138 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2139 FixItHint::CreateReplacement(kwLoc, str));
2142 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2148 /// \brief Parse the receiver of an Objective-C++ message send.
2150 /// This routine parses the receiver of a message send in
2151 /// Objective-C++ either as a type or as an expression. Note that this
2152 /// routine must not be called to parse a send to 'super', since it
2153 /// has no way to return such a result.
2155 /// \param IsExpr Whether the receiver was parsed as an expression.
2157 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2158 /// IsExpr is true), the parsed expression. If the receiver was parsed
2159 /// as a type (\c IsExpr is false), the parsed type.
2161 /// \returns True if an error occurred during parsing or semantic
2162 /// analysis, in which case the arguments do not have valid
2163 /// values. Otherwise, returns false for a successful parse.
2165 /// objc-receiver: [C++]
2166 /// 'super' [not parsed here]
2168 /// simple-type-specifier
2169 /// typename-specifier
2170 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2171 InMessageExpressionRAIIObject InMessage(*this, true);
2173 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2174 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2175 TryAnnotateTypeOrScopeToken();
2177 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2180 // Make sure any typos in the receiver are corrected or diagnosed, so that
2181 // proper recovery can happen. FIXME: Perhaps filter the corrected expr to
2182 // only the things that are valid ObjC receivers?
2183 ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2184 if (Receiver.isInvalid())
2188 TypeOrExpr = Receiver.get();
2193 // typename-specifier
2194 // simple-type-specifier
2195 // expression (that starts with one of the above)
2196 DeclSpec DS(AttrFactory);
2197 ParseCXXSimpleTypeSpecifier(DS);
2199 if (Tok.is(tok::l_paren)) {
2200 // If we see an opening parentheses at this point, we are
2201 // actually parsing an expression that starts with a
2202 // function-style cast, e.g.,
2204 // postfix-expression:
2205 // simple-type-specifier ( expression-list [opt] )
2206 // typename-specifier ( expression-list [opt] )
2208 // Parse the remainder of this case, then the (optional)
2209 // postfix-expression suffix, followed by the (optional)
2210 // right-hand side of the binary expression. We have an
2212 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2213 if (!Receiver.isInvalid())
2214 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2215 if (!Receiver.isInvalid())
2216 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2217 if (Receiver.isInvalid())
2221 TypeOrExpr = Receiver.get();
2225 // We have a class message. Turn the simple-type-specifier or
2226 // typename-specifier we parsed into a type and parse the
2227 // remainder of the class message.
2228 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2229 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2230 if (Type.isInvalid())
2234 TypeOrExpr = Type.get().getAsOpaquePtr();
2238 /// \brief Determine whether the parser is currently referring to a an
2239 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2241 /// This routine will only return true for a subset of valid message-send
2243 bool Parser::isSimpleObjCMessageExpression() {
2244 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2245 "Incorrect start for isSimpleObjCMessageExpression");
2246 return GetLookAheadToken(1).is(tok::identifier) &&
2247 GetLookAheadToken(2).is(tok::identifier);
2250 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2251 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2252 InMessageExpression)
2258 if (Tok.is(tok::annot_typename))
2259 Type = getTypeAnnotation(Tok);
2260 else if (Tok.is(tok::identifier))
2261 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2266 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2267 const Token &AfterNext = GetLookAheadToken(2);
2268 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2269 if (Tok.is(tok::identifier))
2270 TryAnnotateTypeOrScopeToken();
2272 return Tok.is(tok::annot_typename);
2279 /// objc-message-expr:
2280 /// '[' objc-receiver objc-message-args ']'
2282 /// objc-receiver: [C]
2288 ExprResult Parser::ParseObjCMessageExpression() {
2289 assert(Tok.is(tok::l_square) && "'[' expected");
2290 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2292 if (Tok.is(tok::code_completion)) {
2293 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2298 InMessageExpressionRAIIObject InMessage(*this, true);
2300 if (getLangOpts().CPlusPlus) {
2301 // We completely separate the C and C++ cases because C++ requires
2302 // more complicated (read: slower) parsing.
2304 // Handle send to super.
2305 // FIXME: This doesn't benefit from the same typo-correction we
2306 // get in Objective-C.
2307 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2308 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2309 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2310 ParsedType(), nullptr);
2312 // Parse the receiver, which is either a type or an expression.
2314 void *TypeOrExpr = nullptr;
2315 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2316 SkipUntil(tok::r_square, StopAtSemi);
2321 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2323 static_cast<Expr*>(TypeOrExpr));
2325 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2326 ParsedType::getFromOpaquePtr(TypeOrExpr),
2330 if (Tok.is(tok::identifier)) {
2331 IdentifierInfo *Name = Tok.getIdentifierInfo();
2332 SourceLocation NameLoc = Tok.getLocation();
2333 ParsedType ReceiverType;
2334 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2335 Name == Ident_super,
2336 NextToken().is(tok::period),
2338 case Sema::ObjCSuperMessage:
2339 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2340 ParsedType(), nullptr);
2342 case Sema::ObjCClassMessage:
2343 if (!ReceiverType) {
2344 SkipUntil(tok::r_square, StopAtSemi);
2348 ConsumeToken(); // the type name
2350 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2351 ReceiverType, nullptr);
2353 case Sema::ObjCInstanceMessage:
2354 // Fall through to parse an expression.
2359 // Otherwise, an arbitrary expression can be the receiver of a send.
2360 ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2361 if (Res.isInvalid()) {
2362 SkipUntil(tok::r_square, StopAtSemi);
2366 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2367 ParsedType(), Res.get());
2370 /// \brief Parse the remainder of an Objective-C message following the
2371 /// '[' objc-receiver.
2373 /// This routine handles sends to super, class messages (sent to a
2374 /// class name), and instance messages (sent to an object), and the
2375 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2376 /// ReceiverExpr, respectively. Only one of these parameters may have
2379 /// \param LBracLoc The location of the opening '['.
2381 /// \param SuperLoc If this is a send to 'super', the location of the
2382 /// 'super' keyword that indicates a send to the superclass.
2384 /// \param ReceiverType If this is a class message, the type of the
2385 /// class we are sending a message to.
2387 /// \param ReceiverExpr If this is an instance message, the expression
2388 /// used to compute the receiver object.
2390 /// objc-message-args:
2392 /// objc-keywordarg-list
2394 /// objc-keywordarg-list:
2396 /// objc-keywordarg-list objc-keywordarg
2398 /// objc-keywordarg:
2399 /// selector-name[opt] ':' objc-keywordexpr
2401 /// objc-keywordexpr:
2402 /// nonempty-expr-list
2404 /// nonempty-expr-list:
2405 /// assignment-expression
2406 /// nonempty-expr-list , assignment-expression
2409 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2410 SourceLocation SuperLoc,
2411 ParsedType ReceiverType,
2412 Expr *ReceiverExpr) {
2413 InMessageExpressionRAIIObject InMessage(*this, true);
2415 if (Tok.is(tok::code_completion)) {
2416 if (SuperLoc.isValid())
2417 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
2419 else if (ReceiverType)
2420 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
2423 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2429 // Parse objc-selector
2431 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2433 SmallVector<IdentifierInfo *, 12> KeyIdents;
2434 SmallVector<SourceLocation, 12> KeyLocs;
2435 ExprVector KeyExprs;
2437 if (Tok.is(tok::colon)) {
2439 // Each iteration parses a single keyword argument.
2440 KeyIdents.push_back(selIdent);
2441 KeyLocs.push_back(Loc);
2443 if (ExpectAndConsume(tok::colon)) {
2444 // We must manually skip to a ']', otherwise the expression skipper will
2445 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2446 // the enclosing expression.
2447 SkipUntil(tok::r_square, StopAtSemi);
2451 /// Parse the expression after ':'
2453 if (Tok.is(tok::code_completion)) {
2454 if (SuperLoc.isValid())
2455 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2457 /*AtArgumentEpression=*/true);
2458 else if (ReceiverType)
2459 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2461 /*AtArgumentEpression=*/true);
2463 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2465 /*AtArgumentEpression=*/true);
2472 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2473 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2474 Expr = ParseBraceInitializer();
2476 Expr = ParseAssignmentExpression();
2478 ExprResult Res(Expr);
2479 if (Res.isInvalid()) {
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, StopAtSemi);
2487 // We have a valid expression.
2488 KeyExprs.push_back(Res.get());
2490 // Code completion after each argument.
2491 if (Tok.is(tok::code_completion)) {
2492 if (SuperLoc.isValid())
2493 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2495 /*AtArgumentEpression=*/false);
2496 else if (ReceiverType)
2497 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2499 /*AtArgumentEpression=*/false);
2501 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2503 /*AtArgumentEpression=*/false);
2508 // Check for another keyword selector.
2509 selIdent = ParseObjCSelectorPiece(Loc);
2510 if (!selIdent && Tok.isNot(tok::colon))
2512 // We have a selector or a colon, continue parsing.
2514 // Parse the, optional, argument list, comma separated.
2515 while (Tok.is(tok::comma)) {
2516 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2517 /// Parse the expression after ','
2518 ExprResult Res(ParseAssignmentExpression());
2519 if (Tok.is(tok::colon))
2520 Res = Actions.CorrectDelayedTyposInExpr(Res);
2521 if (Res.isInvalid()) {
2522 if (Tok.is(tok::colon)) {
2523 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2524 FixItHint::CreateRemoval(commaLoc);
2526 // We must manually skip to a ']', otherwise the expression skipper will
2527 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2528 // the enclosing expression.
2529 SkipUntil(tok::r_square, StopAtSemi);
2533 // We have a valid expression.
2534 KeyExprs.push_back(Res.get());
2536 } else if (!selIdent) {
2537 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
2539 // We must manually skip to a ']', otherwise the expression skipper will
2540 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2541 // the enclosing expression.
2542 SkipUntil(tok::r_square, StopAtSemi);
2546 if (Tok.isNot(tok::r_square)) {
2547 Diag(Tok, diag::err_expected)
2548 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
2549 // We must manually skip to a ']', otherwise the expression skipper will
2550 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2551 // the enclosing expression.
2552 SkipUntil(tok::r_square, StopAtSemi);
2556 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2558 unsigned nKeys = KeyIdents.size();
2560 KeyIdents.push_back(selIdent);
2561 KeyLocs.push_back(Loc);
2563 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2565 if (SuperLoc.isValid())
2566 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2567 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2568 else if (ReceiverType)
2569 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2570 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2571 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2572 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2575 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2576 ExprResult Res(ParseStringLiteralExpression());
2577 if (Res.isInvalid()) return Res;
2579 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2580 // expressions. At this point, we know that the only valid thing that starts
2581 // with '@' is an @"".
2582 SmallVector<SourceLocation, 4> AtLocs;
2583 ExprVector AtStrings;
2584 AtLocs.push_back(AtLoc);
2585 AtStrings.push_back(Res.get());
2587 while (Tok.is(tok::at)) {
2588 AtLocs.push_back(ConsumeToken()); // eat the @.
2590 // Invalid unless there is a string literal.
2591 if (!isTokenStringLiteral())
2592 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2594 ExprResult Lit(ParseStringLiteralExpression());
2595 if (Lit.isInvalid())
2598 AtStrings.push_back(Lit.get());
2601 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2605 /// ParseObjCBooleanLiteral -
2606 /// objc-scalar-literal : '@' boolean-keyword
2608 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2610 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2612 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2613 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2616 /// ParseObjCCharacterLiteral -
2617 /// objc-scalar-literal : '@' character-literal
2619 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2620 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2621 if (Lit.isInvalid()) {
2624 ConsumeToken(); // Consume the literal token.
2625 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
2628 /// ParseObjCNumericLiteral -
2629 /// objc-scalar-literal : '@' scalar-literal
2631 /// scalar-literal : | numeric-constant /* any numeric constant. */
2633 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2634 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2635 if (Lit.isInvalid()) {
2638 ConsumeToken(); // Consume the literal token.
2639 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
2642 /// ParseObjCBoxedExpr -
2643 /// objc-box-expression:
2644 /// @( assignment-expression )
2646 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2647 if (Tok.isNot(tok::l_paren))
2648 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2650 BalancedDelimiterTracker T(*this, tok::l_paren);
2652 ExprResult ValueExpr(ParseAssignmentExpression());
2653 if (T.consumeClose())
2656 if (ValueExpr.isInvalid())
2659 // Wrap the sub-expression in a parenthesized expression, to distinguish
2660 // a boxed expression from a literal.
2661 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2662 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
2663 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2667 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2668 ExprVector ElementExprs; // array elements.
2669 ConsumeBracket(); // consume the l_square.
2671 while (Tok.isNot(tok::r_square)) {
2672 // Parse list of array element expressions (all must be id types).
2673 ExprResult Res(ParseAssignmentExpression());
2674 if (Res.isInvalid()) {
2675 // We must manually skip to a ']', otherwise the expression skipper will
2676 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2677 // the enclosing expression.
2678 SkipUntil(tok::r_square, StopAtSemi);
2682 // Parse the ellipsis that indicates a pack expansion.
2683 if (Tok.is(tok::ellipsis))
2684 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2685 if (Res.isInvalid())
2688 ElementExprs.push_back(Res.get());
2690 if (Tok.is(tok::comma))
2691 ConsumeToken(); // Eat the ','.
2692 else if (Tok.isNot(tok::r_square))
2693 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
2696 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2697 MultiExprArg Args(ElementExprs);
2698 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
2701 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2702 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2703 ConsumeBrace(); // consume the l_square.
2704 while (Tok.isNot(tok::r_brace)) {
2705 // Parse the comma separated key : value expressions.
2708 ColonProtectionRAIIObject X(*this);
2709 KeyExpr = ParseAssignmentExpression();
2710 if (KeyExpr.isInvalid()) {
2711 // We must manually skip to a '}', otherwise the expression skipper will
2712 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2713 // the enclosing expression.
2714 SkipUntil(tok::r_brace, StopAtSemi);
2719 if (ExpectAndConsume(tok::colon)) {
2720 SkipUntil(tok::r_brace, StopAtSemi);
2724 ExprResult ValueExpr(ParseAssignmentExpression());
2725 if (ValueExpr.isInvalid()) {
2726 // We must manually skip to a '}', otherwise the expression skipper will
2727 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2728 // the enclosing expression.
2729 SkipUntil(tok::r_brace, StopAtSemi);
2733 // Parse the ellipsis that designates this as a pack expansion.
2734 SourceLocation EllipsisLoc;
2735 if (getLangOpts().CPlusPlus)
2736 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2738 // We have a valid expression. Collect it in a vector so we can
2739 // build the argument list.
2740 ObjCDictionaryElement Element = {
2741 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
2743 Elements.push_back(Element);
2745 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
2746 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
2749 SourceLocation EndLoc = ConsumeBrace();
2751 // Create the ObjCDictionaryLiteral.
2752 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2753 Elements.data(), Elements.size());
2756 /// objc-encode-expression:
2757 /// \@encode ( type-name )
2759 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2760 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2762 SourceLocation EncLoc = ConsumeToken();
2764 if (Tok.isNot(tok::l_paren))
2765 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2767 BalancedDelimiterTracker T(*this, tok::l_paren);
2770 TypeResult Ty = ParseTypeName();
2777 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
2778 Ty.get(), T.getCloseLocation());
2781 /// objc-protocol-expression
2782 /// \@protocol ( protocol-name )
2784 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2785 SourceLocation ProtoLoc = ConsumeToken();
2787 if (Tok.isNot(tok::l_paren))
2788 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2790 BalancedDelimiterTracker T(*this, tok::l_paren);
2793 if (Tok.isNot(tok::identifier))
2794 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
2796 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2797 SourceLocation ProtoIdLoc = ConsumeToken();
2801 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2802 T.getOpenLocation(), ProtoIdLoc,
2803 T.getCloseLocation());
2806 /// objc-selector-expression
2807 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
2808 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2809 SourceLocation SelectorLoc = ConsumeToken();
2811 if (Tok.isNot(tok::l_paren))
2812 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2814 SmallVector<IdentifierInfo *, 12> KeyIdents;
2815 SourceLocation sLoc;
2817 BalancedDelimiterTracker T(*this, tok::l_paren);
2819 bool HasOptionalParen = Tok.is(tok::l_paren);
2820 if (HasOptionalParen)
2823 if (Tok.is(tok::code_completion)) {
2824 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2829 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2830 if (!SelIdent && // missing selector name.
2831 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2832 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
2834 KeyIdents.push_back(SelIdent);
2836 unsigned nColons = 0;
2837 if (Tok.isNot(tok::r_paren)) {
2839 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
2841 KeyIdents.push_back(nullptr);
2842 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
2846 if (Tok.is(tok::r_paren))
2849 if (Tok.is(tok::code_completion)) {
2850 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2855 // Check for another keyword selector.
2857 SelIdent = ParseObjCSelectorPiece(Loc);
2858 KeyIdents.push_back(SelIdent);
2859 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2863 if (HasOptionalParen && Tok.is(tok::r_paren))
2864 ConsumeParen(); // ')'
2866 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2867 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2868 T.getOpenLocation(),
2869 T.getCloseLocation(),
2873 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2874 // MCDecl might be null due to error in method or c-function prototype, etc.
2875 Decl *MCDecl = LM.D;
2876 bool skip = MCDecl &&
2877 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2878 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2882 // Save the current token position.
2883 SourceLocation OrigLoc = Tok.getLocation();
2885 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2886 // Append the current token at the end of the new token stream so that it
2887 // doesn't get lost.
2888 LM.Toks.push_back(Tok);
2889 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2891 // Consume the previously pushed token.
2892 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
2894 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2895 Tok.is(tok::colon)) &&
2896 "Inline objective-c method not starting with '{' or 'try' or ':'");
2897 // Enter a scope for the method or c-function body.
2898 ParseScope BodyScope(this,
2900 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2901 : Scope::FnScope|Scope::DeclScope);
2903 // Tell the actions module that we have entered a method or c-function definition
2904 // with the specified Declarator for the method/function.
2906 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2908 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2909 if (Tok.is(tok::kw_try))
2910 ParseFunctionTryBlock(MCDecl, BodyScope);
2912 if (Tok.is(tok::colon))
2913 ParseConstructorInitializer(MCDecl);
2914 ParseFunctionStatementBody(MCDecl, BodyScope);
2917 if (Tok.getLocation() != OrigLoc) {
2918 // Due to parsing error, we either went over the cached tokens or
2919 // there are still cached tokens left. If it's the latter case skip the
2921 // Since this is an uncommon situation that should be avoided, use the
2922 // expensive isBeforeInTranslationUnit call.
2923 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2925 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))