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)
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,
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,
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 /// The Objective-C property callback. This should be defined where
311 /// it's used, but instead it's been lifted to here to support VS2005.
312 struct Parser::ObjCPropertyCallback : FieldCallback {
314 virtual void anchor();
317 SmallVectorImpl<Decl *> &Props;
319 SourceLocation AtLoc;
320 SourceLocation LParenLoc;
321 tok::ObjCKeywordKind MethodImplKind;
323 ObjCPropertyCallback(Parser &P,
324 SmallVectorImpl<Decl *> &Props,
325 ObjCDeclSpec &OCDS, SourceLocation AtLoc,
326 SourceLocation LParenLoc,
327 tok::ObjCKeywordKind MethodImplKind) :
328 P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
329 MethodImplKind(MethodImplKind) {
332 void invoke(ParsingFieldDeclarator &FD) override {
333 if (FD.D.getIdentifier() == nullptr) {
334 P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
335 << FD.D.getSourceRange();
338 if (FD.BitfieldSize) {
339 P.Diag(AtLoc, diag::err_objc_property_bitfield)
340 << FD.D.getSourceRange();
344 // Install the property declarator into interfaceDecl.
345 IdentifierInfo *SelName =
346 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
349 P.PP.getSelectorTable().getNullarySelector(SelName);
350 IdentifierInfo *SetterName = OCDS.getSetterName();
353 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
356 SelectorTable::constructSetterSelector(P.PP.getIdentifierTable(),
357 P.PP.getSelectorTable(),
358 FD.D.getIdentifier());
359 bool isOverridingProperty = false;
361 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
363 GetterSel, SetterSel,
364 &isOverridingProperty,
366 if (!isOverridingProperty)
367 Props.push_back(Property);
369 FD.complete(Property);
373 void Parser::ObjCPropertyCallback::anchor() {
376 /// objc-interface-decl-list:
378 /// objc-interface-decl-list objc-property-decl [OBJC2]
379 /// objc-interface-decl-list objc-method-requirement [OBJC2]
380 /// objc-interface-decl-list objc-method-proto ';'
381 /// objc-interface-decl-list declaration
382 /// objc-interface-decl-list ';'
384 /// objc-method-requirement: [OBJC2]
388 void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
390 SmallVector<Decl *, 32> allMethods;
391 SmallVector<Decl *, 16> allProperties;
392 SmallVector<DeclGroupPtrTy, 8> allTUVariables;
393 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
398 // If this is a method prototype, parse it.
399 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
400 if (Decl *methodPrototype =
401 ParseObjCMethodPrototype(MethodImplKind, false))
402 allMethods.push_back(methodPrototype);
403 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
404 // method definitions.
405 if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) {
406 // We didn't find a semi and we error'ed out. Skip until a ';' or '@'.
407 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
408 if (Tok.is(tok::semi))
413 if (Tok.is(tok::l_paren)) {
414 Diag(Tok, diag::err_expected_minus_or_plus);
415 ParseObjCMethodDecl(Tok.getLocation(),
417 MethodImplKind, false);
420 // Ignore excess semicolons.
421 if (Tok.is(tok::semi)) {
426 // If we got to the end of the file, exit the loop.
430 // Code completion within an Objective-C interface.
431 if (Tok.is(tok::code_completion)) {
432 Actions.CodeCompleteOrdinaryName(getCurScope(),
433 CurParsedObjCImpl? Sema::PCC_ObjCImplementation
434 : Sema::PCC_ObjCInterface);
435 return cutOffParsing();
438 // If we don't have an @ directive, parse it as a function definition.
439 if (Tok.isNot(tok::at)) {
440 // The code below does not consume '}'s because it is afraid of eating the
441 // end of a namespace. Because of the way this code is structured, an
442 // erroneous r_brace would cause an infinite loop if not handled here.
443 if (Tok.is(tok::r_brace))
445 ParsedAttributesWithRange attrs(AttrFactory);
446 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
450 // Otherwise, we have an @ directive, eat the @.
451 SourceLocation AtLoc = ConsumeToken(); // the "@"
452 if (Tok.is(tok::code_completion)) {
453 Actions.CodeCompleteObjCAtDirective(getCurScope());
454 return cutOffParsing();
457 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
459 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
460 AtEnd.setBegin(AtLoc);
461 AtEnd.setEnd(Tok.getLocation());
463 } else if (DirectiveKind == tok::objc_not_keyword) {
464 Diag(Tok, diag::err_objc_unknown_at);
465 SkipUntil(tok::semi);
469 // Eat the identifier.
472 switch (DirectiveKind) {
474 // FIXME: If someone forgets an @end on a protocol, this loop will
475 // continue to eat up tons of stuff and spew lots of nonsense errors. It
476 // would probably be better to bail out if we saw an @class or @interface
477 // or something like that.
478 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
479 // Skip until we see an '@' or '}' or ';'.
480 SkipUntil(tok::r_brace, tok::at, StopAtSemi);
483 case tok::objc_implementation:
484 case tok::objc_interface:
485 Diag(AtLoc, diag::err_objc_missing_end)
486 << FixItHint::CreateInsertion(AtLoc, "@end\n");
487 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
488 << (int) Actions.getObjCContainerKind();
492 case tok::objc_required:
493 case tok::objc_optional:
494 // This is only valid on protocols.
495 // FIXME: Should this check for ObjC2 being enabled?
496 if (contextKey != tok::objc_protocol)
497 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
499 MethodImplKind = DirectiveKind;
502 case tok::objc_property:
503 if (!getLangOpts().ObjC2)
504 Diag(AtLoc, diag::err_objc_properties_require_objc2);
507 SourceLocation LParenLoc;
508 // Parse property attribute list, if any.
509 if (Tok.is(tok::l_paren)) {
510 LParenLoc = Tok.getLocation();
511 ParseObjCPropertyAttribute(OCDS);
514 ObjCPropertyCallback Callback(*this, allProperties,
515 OCDS, AtLoc, LParenLoc, MethodImplKind);
517 // Parse all the comma separated declarators.
518 ParsingDeclSpec DS(*this);
519 ParseStructDeclaration(DS, Callback);
521 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
526 // We break out of the big loop in two cases: when we see @end or when we see
527 // EOF. In the former case, eat the @end. In the later case, emit an error.
528 if (Tok.is(tok::code_completion)) {
529 Actions.CodeCompleteObjCAtDirective(getCurScope());
530 return cutOffParsing();
531 } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
532 ConsumeToken(); // the "end" identifier
534 Diag(Tok, diag::err_objc_missing_end)
535 << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n");
536 Diag(CDecl->getLocStart(), diag::note_objc_container_start)
537 << (int) Actions.getObjCContainerKind();
538 AtEnd.setBegin(Tok.getLocation());
539 AtEnd.setEnd(Tok.getLocation());
542 // Insert collected methods declarations into the @interface object.
543 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
544 Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables);
547 /// Parse property attribute declarations.
549 /// property-attr-decl: '(' property-attrlist ')'
550 /// property-attrlist:
551 /// property-attribute
552 /// property-attrlist ',' property-attribute
553 /// property-attribute:
554 /// getter '=' identifier
555 /// setter '=' identifier ':'
565 /// unsafe_unretained
567 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) {
568 assert(Tok.getKind() == tok::l_paren);
569 BalancedDelimiterTracker T(*this, tok::l_paren);
573 if (Tok.is(tok::code_completion)) {
574 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
575 return cutOffParsing();
577 const IdentifierInfo *II = Tok.getIdentifierInfo();
579 // If this is not an identifier at all, bail out early.
585 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
587 if (II->isStr("readonly"))
588 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
589 else if (II->isStr("assign"))
590 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
591 else if (II->isStr("unsafe_unretained"))
592 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
593 else if (II->isStr("readwrite"))
594 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
595 else if (II->isStr("retain"))
596 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
597 else if (II->isStr("strong"))
598 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
599 else if (II->isStr("copy"))
600 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
601 else if (II->isStr("nonatomic"))
602 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
603 else if (II->isStr("atomic"))
604 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
605 else if (II->isStr("weak"))
606 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
607 else if (II->isStr("getter") || II->isStr("setter")) {
608 bool IsSetter = II->getNameStart()[0] == 's';
610 // getter/setter require extra treatment.
611 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
612 diag::err_objc_expected_equal_for_getter;
614 if (ExpectAndConsume(tok::equal, DiagID)) {
615 SkipUntil(tok::r_paren, StopAtSemi);
619 if (Tok.is(tok::code_completion)) {
621 Actions.CodeCompleteObjCPropertySetter(getCurScope());
623 Actions.CodeCompleteObjCPropertyGetter(getCurScope());
624 return cutOffParsing();
628 SourceLocation SelLoc;
629 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
632 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
634 SkipUntil(tok::r_paren, StopAtSemi);
639 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
640 DS.setSetterName(SelIdent);
642 if (ExpectAndConsume(tok::colon,
643 diag::err_expected_colon_after_setter_name)) {
644 SkipUntil(tok::r_paren, StopAtSemi);
648 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
649 DS.setGetterName(SelIdent);
652 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
653 SkipUntil(tok::r_paren, StopAtSemi);
657 if (Tok.isNot(tok::comma))
666 /// objc-method-proto:
667 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
668 /// objc-class-method objc-method-decl objc-method-attributes[opt]
670 /// objc-instance-method: '-'
671 /// objc-class-method: '+'
673 /// objc-method-attributes: [OBJC2]
674 /// __attribute__((deprecated))
676 Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind,
677 bool MethodDefinition) {
678 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
680 tok::TokenKind methodType = Tok.getKind();
681 SourceLocation mLoc = ConsumeToken();
682 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind,
684 // Since this rule is used for both method declarations and definitions,
685 // the caller is (optionally) responsible for consuming the ';'.
692 /// enum struct union if else while do for switch case default
693 /// break continue return goto asm sizeof typeof __alignof
694 /// unsigned long const short volatile signed restrict _Complex
695 /// in out inout bycopy byref oneway int char float double void _Bool
697 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
699 switch (Tok.getKind()) {
708 case tok::exclaimequal:
712 case tok::caretequal: {
713 std::string ThisTok(PP.getSpelling(Tok));
714 if (isLetter(ThisTok[0])) {
715 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
716 Tok.setKind(tok::identifier);
717 SelectorLoc = ConsumeToken();
723 case tok::identifier:
733 case tok::kw_const_cast:
734 case tok::kw_continue:
735 case tok::kw_default:
739 case tok::kw_dynamic_cast:
742 case tok::kw_explicit:
754 case tok::kw_mutable:
755 case tok::kw_namespace:
757 case tok::kw_operator:
758 case tok::kw_private:
759 case tok::kw_protected:
761 case tok::kw_register:
762 case tok::kw_reinterpret_cast:
763 case tok::kw_restrict:
769 case tok::kw_static_cast:
772 case tok::kw_template:
777 case tok::kw_typedef:
779 case tok::kw_typename:
782 case tok::kw_unsigned:
784 case tok::kw_virtual:
786 case tok::kw_volatile:
787 case tok::kw_wchar_t:
790 case tok::kw__Complex:
791 case tok::kw___alignof:
792 IdentifierInfo *II = Tok.getIdentifierInfo();
793 SelectorLoc = ConsumeToken();
798 /// objc-for-collection-in: 'in'
800 bool Parser::isTokIdentifier_in() const {
801 // FIXME: May have to do additional look-ahead to only allow for
802 // valid tokens following an 'in'; such as an identifier, unary operators,
804 return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
805 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
808 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
809 /// qualifier list and builds their bitmask representation in the input
812 /// objc-type-qualifiers:
813 /// objc-type-qualifier
814 /// objc-type-qualifiers objc-type-qualifier
816 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
817 Declarator::TheContext Context) {
818 assert(Context == Declarator::ObjCParameterContext ||
819 Context == Declarator::ObjCResultContext);
822 if (Tok.is(tok::code_completion)) {
823 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
824 Context == Declarator::ObjCParameterContext);
825 return cutOffParsing();
828 if (Tok.isNot(tok::identifier))
831 const IdentifierInfo *II = Tok.getIdentifierInfo();
832 for (unsigned i = 0; i != objc_NumQuals; ++i) {
833 if (II != ObjCTypeQuals[i])
836 ObjCDeclSpec::ObjCDeclQualifier Qual;
838 default: llvm_unreachable("Unknown decl qualifier");
839 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
840 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
841 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
842 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
843 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
844 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
846 DS.setObjCDeclQualifier(Qual);
852 // If this wasn't a recognized qualifier, bail out.
857 /// Take all the decl attributes out of the given list and add
858 /// them to the given attribute set.
859 static void takeDeclAttributes(ParsedAttributes &attrs,
860 AttributeList *list) {
862 AttributeList *cur = list;
863 list = cur->getNext();
865 if (!cur->isUsedAsTypeAttr()) {
866 // Clear out the next pointer. We're really completely
867 // destroying the internal invariants of the declarator here,
868 // but it doesn't matter because we're done with it.
869 cur->setNext(nullptr);
875 /// takeDeclAttributes - Take all the decl attributes from the given
876 /// declarator and add them to the given list.
877 static void takeDeclAttributes(ParsedAttributes &attrs,
879 // First, take ownership of all attributes.
880 attrs.getPool().takeAllFrom(D.getAttributePool());
881 attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool());
883 // Now actually move the attributes over.
884 takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList());
885 takeDeclAttributes(attrs, D.getAttributes());
886 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
887 takeDeclAttributes(attrs,
888 const_cast<AttributeList*>(D.getTypeObject(i).getAttrs()));
892 /// '(' objc-type-qualifiers[opt] type-name ')'
893 /// '(' objc-type-qualifiers[opt] ')'
895 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
896 Declarator::TheContext context,
897 ParsedAttributes *paramAttrs) {
898 assert(context == Declarator::ObjCParameterContext ||
899 context == Declarator::ObjCResultContext);
900 assert((paramAttrs != nullptr) ==
901 (context == Declarator::ObjCParameterContext));
903 assert(Tok.is(tok::l_paren) && "expected (");
905 BalancedDelimiterTracker T(*this, tok::l_paren);
908 SourceLocation TypeStartLoc = Tok.getLocation();
909 ObjCDeclContextSwitch ObjCDC(*this);
911 // Parse type qualifiers, in, inout, etc.
912 ParseObjCTypeQualifierList(DS, context);
915 if (isTypeSpecifierQualifier()) {
916 // Parse an abstract declarator.
917 DeclSpec declSpec(AttrFactory);
918 declSpec.setObjCQualifiers(&DS);
919 ParseSpecifierQualifierList(declSpec);
920 declSpec.SetRangeEnd(Tok.getLocation());
921 Declarator declarator(declSpec, context);
922 ParseDeclarator(declarator);
924 // If that's not invalid, extract a type.
925 if (!declarator.isInvalidType()) {
926 TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator);
927 if (!type.isInvalid())
930 // If we're parsing a parameter, steal all the decl attributes
931 // and add them to the decl spec.
932 if (context == Declarator::ObjCParameterContext)
933 takeDeclAttributes(*paramAttrs, declarator);
935 } else if (context == Declarator::ObjCResultContext &&
936 Tok.is(tok::identifier)) {
937 if (!Ident_instancetype)
938 Ident_instancetype = PP.getIdentifierInfo("instancetype");
940 if (Tok.getIdentifierInfo() == Ident_instancetype) {
941 Ty = Actions.ActOnObjCInstanceType(Tok.getLocation());
946 if (Tok.is(tok::r_paren))
948 else if (Tok.getLocation() == TypeStartLoc) {
949 // If we didn't eat any tokens, then this isn't a type.
950 Diag(Tok, diag::err_expected_type);
951 SkipUntil(tok::r_paren, StopAtSemi);
953 // Otherwise, we found *something*, but didn't get a ')' in the right
954 // place. Emit an error then return what we have as the type.
960 /// objc-method-decl:
962 /// objc-keyword-selector objc-parmlist[opt]
963 /// objc-type-name objc-selector
964 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
966 /// objc-keyword-selector:
967 /// objc-keyword-decl
968 /// objc-keyword-selector objc-keyword-decl
970 /// objc-keyword-decl:
971 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
972 /// objc-selector ':' objc-keyword-attributes[opt] identifier
973 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
974 /// ':' objc-keyword-attributes[opt] identifier
977 /// objc-parms objc-ellipsis[opt]
980 /// objc-parms , parameter-declaration
985 /// objc-keyword-attributes: [OBJC2]
986 /// __attribute__((unused))
988 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
989 tok::TokenKind mType,
990 tok::ObjCKeywordKind MethodImplKind,
991 bool MethodDefinition) {
992 ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
994 if (Tok.is(tok::code_completion)) {
995 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
996 /*ReturnType=*/ ParsedType());
1001 // Parse the return type if present.
1002 ParsedType ReturnType;
1004 if (Tok.is(tok::l_paren))
1005 ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext,
1008 // If attributes exist before the method, parse them.
1009 ParsedAttributes methodAttrs(AttrFactory);
1010 if (getLangOpts().ObjC2)
1011 MaybeParseGNUAttributes(methodAttrs);
1013 if (Tok.is(tok::code_completion)) {
1014 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
1020 // Now parse the selector.
1021 SourceLocation selLoc;
1022 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
1024 // An unnamed colon is valid.
1025 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
1026 Diag(Tok, diag::err_expected_selector_for_method)
1027 << SourceRange(mLoc, Tok.getLocation());
1028 // Skip until we get a ; or @.
1029 SkipUntil(tok::at, StopAtSemi | StopBeforeMatch);
1033 SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
1034 if (Tok.isNot(tok::colon)) {
1035 // If attributes exist after the method, parse them.
1036 if (getLangOpts().ObjC2)
1037 MaybeParseGNUAttributes(methodAttrs);
1039 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
1041 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1042 mType, DSRet, ReturnType,
1043 selLoc, Sel, nullptr,
1044 CParamInfo.data(), CParamInfo.size(),
1045 methodAttrs.getList(), MethodImplKind,
1046 false, MethodDefinition);
1047 PD.complete(Result);
1051 SmallVector<IdentifierInfo *, 12> KeyIdents;
1052 SmallVector<SourceLocation, 12> KeyLocs;
1053 SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
1054 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1055 Scope::FunctionDeclarationScope | Scope::DeclScope);
1057 AttributePool allParamAttrs(AttrFactory);
1059 ParsedAttributes paramAttrs(AttrFactory);
1060 Sema::ObjCArgInfo ArgInfo;
1062 // Each iteration parses a single keyword argument.
1063 if (ExpectAndConsume(tok::colon))
1066 ArgInfo.Type = ParsedType();
1067 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
1068 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec,
1069 Declarator::ObjCParameterContext,
1072 // If attributes exist before the argument name, parse them.
1073 // Regardless, collect all the attributes we've parsed so far.
1074 ArgInfo.ArgAttrs = nullptr;
1075 if (getLangOpts().ObjC2) {
1076 MaybeParseGNUAttributes(paramAttrs);
1077 ArgInfo.ArgAttrs = paramAttrs.getList();
1080 // Code completion for the next piece of the selector.
1081 if (Tok.is(tok::code_completion)) {
1082 KeyIdents.push_back(SelIdent);
1083 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1084 mType == tok::minus,
1085 /*AtParameterName=*/true,
1086 ReturnType, KeyIdents);
1091 if (Tok.isNot(tok::identifier)) {
1092 Diag(Tok, diag::err_expected)
1093 << tok::identifier; // missing argument name.
1097 ArgInfo.Name = Tok.getIdentifierInfo();
1098 ArgInfo.NameLoc = Tok.getLocation();
1099 ConsumeToken(); // Eat the identifier.
1101 ArgInfos.push_back(ArgInfo);
1102 KeyIdents.push_back(SelIdent);
1103 KeyLocs.push_back(selLoc);
1105 // Make sure the attributes persist.
1106 allParamAttrs.takeAllFrom(paramAttrs.getPool());
1108 // Code completion for the next piece of the selector.
1109 if (Tok.is(tok::code_completion)) {
1110 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
1111 mType == tok::minus,
1112 /*AtParameterName=*/false,
1113 ReturnType, KeyIdents);
1118 // Check for another keyword selector.
1119 SelIdent = ParseObjCSelectorPiece(selLoc);
1120 if (!SelIdent && Tok.isNot(tok::colon))
1123 SourceLocation ColonLoc = Tok.getLocation();
1124 if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) {
1125 Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name;
1126 Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name;
1127 Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name;
1130 // We have a selector or a colon, continue parsing.
1133 bool isVariadic = false;
1134 bool cStyleParamWarned = false;
1135 // Parse the (optional) parameter list.
1136 while (Tok.is(tok::comma)) {
1138 if (Tok.is(tok::ellipsis)) {
1143 if (!cStyleParamWarned) {
1144 Diag(Tok, diag::warn_cstyle_param);
1145 cStyleParamWarned = true;
1147 DeclSpec DS(AttrFactory);
1148 ParseDeclarationSpecifiers(DS);
1149 // Parse the declarator.
1150 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1151 ParseDeclarator(ParmDecl);
1152 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
1153 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
1154 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
1155 ParmDecl.getIdentifierLoc(),
1160 // FIXME: Add support for optional parameter list...
1161 // If attributes exist after the method, parse them.
1162 if (getLangOpts().ObjC2)
1163 MaybeParseGNUAttributes(methodAttrs);
1165 if (KeyIdents.size() == 0)
1168 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1171 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1172 mType, DSRet, ReturnType,
1173 KeyLocs, Sel, &ArgInfos[0],
1174 CParamInfo.data(), CParamInfo.size(),
1175 methodAttrs.getList(),
1176 MethodImplKind, isVariadic, MethodDefinition);
1178 PD.complete(Result);
1182 /// objc-protocol-refs:
1183 /// '<' identifier-list '>'
1186 ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols,
1187 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1188 bool WarnOnDeclarations,
1189 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1190 assert(Tok.is(tok::less) && "expected <");
1192 LAngleLoc = ConsumeToken(); // the "<"
1194 SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1197 if (Tok.is(tok::code_completion)) {
1198 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1199 ProtocolIdents.size());
1204 if (Tok.isNot(tok::identifier)) {
1205 Diag(Tok, diag::err_expected) << tok::identifier;
1206 SkipUntil(tok::greater, StopAtSemi);
1209 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1210 Tok.getLocation()));
1211 ProtocolLocs.push_back(Tok.getLocation());
1214 if (!TryConsumeToken(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(), nullptr);
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) && !isEofOrEom()) {
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 (TryConsumeToken(tok::at)) { // parse objc-visibility-spec
1306 if (Tok.is(tok::code_completion)) {
1307 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1308 return cutOffParsing();
1311 switch (Tok.getObjCKeywordID()) {
1312 case tok::objc_private:
1313 case tok::objc_public:
1314 case tok::objc_protected:
1315 case tok::objc_package:
1316 visibility = Tok.getObjCKeywordID();
1321 Diag(Tok, diag::err_objc_unexpected_atend);
1322 Tok.setLocation(Tok.getLocation().getLocWithOffset(-1));
1323 Tok.setKind(tok::at);
1326 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1327 T, AllIvarDecls, true);
1331 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1336 if (Tok.is(tok::code_completion)) {
1337 Actions.CodeCompleteOrdinaryName(getCurScope(),
1338 Sema::PCC_ObjCInstanceVariableList);
1339 return cutOffParsing();
1342 struct ObjCIvarCallback : FieldCallback {
1345 tok::ObjCKeywordKind visibility;
1346 SmallVectorImpl<Decl *> &AllIvarDecls;
1348 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1349 SmallVectorImpl<Decl *> &AllIvarDecls) :
1350 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1353 void invoke(ParsingFieldDeclarator &FD) override {
1354 P.Actions.ActOnObjCContainerStartDefinition(IDecl);
1355 // Install the declarator into the interface decl.
1357 = P.Actions.ActOnIvar(P.getCurScope(),
1358 FD.D.getDeclSpec().getSourceRange().getBegin(),
1359 FD.D, FD.BitfieldSize, visibility);
1360 P.Actions.ActOnObjCContainerFinishDefinition();
1362 AllIvarDecls.push_back(Field);
1365 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1367 // Parse all the comma separated declarators.
1368 ParsingDeclSpec DS(*this);
1369 ParseStructDeclaration(DS, Callback);
1371 if (Tok.is(tok::semi)) {
1374 Diag(Tok, diag::err_expected_semi_decl_list);
1375 // Skip to end of block or statement
1376 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
1379 HelperActionsForIvarDeclarations(interfaceDecl, atLoc,
1380 T, AllIvarDecls, false);
1384 /// objc-protocol-declaration:
1385 /// objc-protocol-definition
1386 /// objc-protocol-forward-reference
1388 /// objc-protocol-definition:
1389 /// \@protocol identifier
1390 /// objc-protocol-refs[opt]
1391 /// objc-interface-decl-list
1394 /// objc-protocol-forward-reference:
1395 /// \@protocol identifier-list ';'
1397 /// "\@protocol identifier ;" should be resolved as "\@protocol
1398 /// identifier-list ;": objc-interface-decl-list may not start with a
1399 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1400 Parser::DeclGroupPtrTy
1401 Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1402 ParsedAttributes &attrs) {
1403 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1404 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1405 ConsumeToken(); // the "protocol" identifier
1407 if (Tok.is(tok::code_completion)) {
1408 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1410 return DeclGroupPtrTy();
1413 MaybeSkipAttributes(tok::objc_protocol);
1415 if (Tok.isNot(tok::identifier)) {
1416 Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name.
1417 return DeclGroupPtrTy();
1419 // Save the protocol name, then consume it.
1420 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1421 SourceLocation nameLoc = ConsumeToken();
1423 if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol.
1424 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1425 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1429 CheckNestedObjCContexts(AtLoc);
1431 if (Tok.is(tok::comma)) { // list of forward declarations.
1432 SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1433 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1435 // Parse the list of forward declarations.
1437 ConsumeToken(); // the ','
1438 if (Tok.isNot(tok::identifier)) {
1439 Diag(Tok, diag::err_expected) << tok::identifier;
1440 SkipUntil(tok::semi);
1441 return DeclGroupPtrTy();
1443 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1444 Tok.getLocation()));
1445 ConsumeToken(); // the identifier
1447 if (Tok.isNot(tok::comma))
1451 if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol"))
1452 return DeclGroupPtrTy();
1454 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1456 ProtocolRefs.size(),
1460 // Last, and definitely not least, parse a protocol declaration.
1461 SourceLocation LAngleLoc, EndProtoLoc;
1463 SmallVector<Decl *, 8> ProtocolRefs;
1464 SmallVector<SourceLocation, 8> ProtocolLocs;
1465 if (Tok.is(tok::less) &&
1466 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1467 LAngleLoc, EndProtoLoc))
1468 return DeclGroupPtrTy();
1471 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1472 ProtocolRefs.data(),
1473 ProtocolRefs.size(),
1474 ProtocolLocs.data(),
1475 EndProtoLoc, attrs.getList());
1477 ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
1478 return Actions.ConvertDeclToDeclGroup(ProtoType);
1481 /// objc-implementation:
1482 /// objc-class-implementation-prologue
1483 /// objc-category-implementation-prologue
1485 /// objc-class-implementation-prologue:
1486 /// @implementation identifier objc-superclass[opt]
1487 /// objc-class-instance-variables[opt]
1489 /// objc-category-implementation-prologue:
1490 /// @implementation identifier ( identifier )
1491 Parser::DeclGroupPtrTy
1492 Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
1493 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1494 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1495 CheckNestedObjCContexts(AtLoc);
1496 ConsumeToken(); // the "implementation" identifier
1498 // Code completion after '@implementation'.
1499 if (Tok.is(tok::code_completion)) {
1500 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1502 return DeclGroupPtrTy();
1505 MaybeSkipAttributes(tok::objc_implementation);
1507 if (Tok.isNot(tok::identifier)) {
1508 Diag(Tok, diag::err_expected)
1509 << tok::identifier; // missing class or category name.
1510 return DeclGroupPtrTy();
1512 // We have a class or category name - consume it.
1513 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1514 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1515 Decl *ObjCImpDecl = nullptr;
1517 if (Tok.is(tok::l_paren)) {
1518 // we have a category implementation.
1520 SourceLocation categoryLoc, rparenLoc;
1521 IdentifierInfo *categoryId = nullptr;
1523 if (Tok.is(tok::code_completion)) {
1524 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1526 return DeclGroupPtrTy();
1529 if (Tok.is(tok::identifier)) {
1530 categoryId = Tok.getIdentifierInfo();
1531 categoryLoc = ConsumeToken();
1533 Diag(Tok, diag::err_expected)
1534 << tok::identifier; // missing category name.
1535 return DeclGroupPtrTy();
1537 if (Tok.isNot(tok::r_paren)) {
1538 Diag(Tok, diag::err_expected) << tok::r_paren;
1539 SkipUntil(tok::r_paren); // don't stop at ';'
1540 return DeclGroupPtrTy();
1542 rparenLoc = ConsumeParen();
1543 if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1544 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1545 AttributeFactory attr;
1547 (void)ParseObjCProtocolQualifiers(DS);
1549 ObjCImpDecl = Actions.ActOnStartCategoryImplementation(
1550 AtLoc, nameId, nameLoc, categoryId,
1554 // We have a class implementation
1555 SourceLocation superClassLoc;
1556 IdentifierInfo *superClassId = nullptr;
1557 if (TryConsumeToken(tok::colon)) {
1558 // We have a super class
1559 if (Tok.isNot(tok::identifier)) {
1560 Diag(Tok, diag::err_expected)
1561 << tok::identifier; // missing super class name.
1562 return DeclGroupPtrTy();
1564 superClassId = Tok.getIdentifierInfo();
1565 superClassLoc = ConsumeToken(); // Consume super class name
1567 ObjCImpDecl = Actions.ActOnStartClassImplementation(
1568 AtLoc, nameId, nameLoc,
1569 superClassId, superClassLoc);
1571 if (Tok.is(tok::l_brace)) // we have ivars
1572 ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc);
1573 else if (Tok.is(tok::less)) { // we have illegal '<' try to recover
1574 Diag(Tok, diag::err_unexpected_protocol_qualifier);
1576 AttributeFactory attr;
1578 (void)ParseObjCProtocolQualifiers(DS);
1581 assert(ObjCImpDecl);
1583 SmallVector<Decl *, 8> DeclsInGroup;
1586 ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
1587 while (!ObjCImplParsing.isFinished() && !isEofOrEom()) {
1588 ParsedAttributesWithRange attrs(AttrFactory);
1589 MaybeParseCXX11Attributes(attrs);
1590 MaybeParseMicrosoftAttributes(attrs);
1591 if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) {
1592 DeclGroupRef DG = DGP.get();
1593 DeclsInGroup.append(DG.begin(), DG.end());
1598 return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
1601 Parser::DeclGroupPtrTy
1602 Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1603 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1604 "ParseObjCAtEndDeclaration(): Expected @end");
1605 ConsumeToken(); // the "end" identifier
1606 if (CurParsedObjCImpl)
1607 CurParsedObjCImpl->finish(atEnd);
1609 // missing @implementation
1610 Diag(atEnd.getBegin(), diag::err_expected_objc_container);
1611 return DeclGroupPtrTy();
1614 Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
1616 finish(P.Tok.getLocation());
1617 if (P.isEofOrEom()) {
1618 P.Diag(P.Tok, diag::err_objc_missing_end)
1619 << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n");
1620 P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
1621 << Sema::OCK_Implementation;
1624 P.CurParsedObjCImpl = nullptr;
1625 assert(LateParsedObjCMethods.empty());
1628 void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
1630 P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
1631 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1632 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1635 P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
1638 for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i)
1639 P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i],
1640 false/*c-functions*/);
1642 /// \brief Clear and free the cached objc methods.
1643 for (LateParsedObjCMethodContainer::iterator
1644 I = LateParsedObjCMethods.begin(),
1645 E = LateParsedObjCMethods.end(); I != E; ++I)
1647 LateParsedObjCMethods.clear();
1652 /// compatibility-alias-decl:
1653 /// @compatibility_alias alias-name class-name ';'
1655 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1656 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1657 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1658 ConsumeToken(); // consume compatibility_alias
1659 if (Tok.isNot(tok::identifier)) {
1660 Diag(Tok, diag::err_expected) << tok::identifier;
1663 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1664 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1665 if (Tok.isNot(tok::identifier)) {
1666 Diag(Tok, diag::err_expected) << tok::identifier;
1669 IdentifierInfo *classId = Tok.getIdentifierInfo();
1670 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1671 ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias");
1672 return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc,
1676 /// property-synthesis:
1677 /// @synthesize property-ivar-list ';'
1679 /// property-ivar-list:
1681 /// property-ivar-list ',' property-ivar
1685 /// identifier '=' identifier
1687 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1688 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1689 "ParseObjCPropertySynthesize(): Expected '@synthesize'");
1690 ConsumeToken(); // consume synthesize
1693 if (Tok.is(tok::code_completion)) {
1694 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1699 if (Tok.isNot(tok::identifier)) {
1700 Diag(Tok, diag::err_synthesized_property_name);
1701 SkipUntil(tok::semi);
1705 IdentifierInfo *propertyIvar = nullptr;
1706 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1707 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1708 SourceLocation propertyIvarLoc;
1709 if (TryConsumeToken(tok::equal)) {
1710 // property '=' ivar-name
1711 if (Tok.is(tok::code_completion)) {
1712 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId);
1717 if (Tok.isNot(tok::identifier)) {
1718 Diag(Tok, diag::err_expected) << tok::identifier;
1721 propertyIvar = Tok.getIdentifierInfo();
1722 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1724 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true,
1725 propertyId, propertyIvar, propertyIvarLoc);
1726 if (Tok.isNot(tok::comma))
1728 ConsumeToken(); // consume ','
1730 ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize");
1734 /// property-dynamic:
1735 /// @dynamic property-list
1739 /// property-list ',' identifier
1741 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1742 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1743 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1744 ConsumeToken(); // consume dynamic
1746 if (Tok.is(tok::code_completion)) {
1747 Actions.CodeCompleteObjCPropertyDefinition(getCurScope());
1752 if (Tok.isNot(tok::identifier)) {
1753 Diag(Tok, diag::err_expected) << tok::identifier;
1754 SkipUntil(tok::semi);
1758 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1759 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1760 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false,
1761 propertyId, nullptr, SourceLocation());
1763 if (Tok.isNot(tok::comma))
1765 ConsumeToken(); // consume ','
1767 ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic");
1771 /// objc-throw-statement:
1772 /// throw expression[opt];
1774 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1776 ConsumeToken(); // consume throw
1777 if (Tok.isNot(tok::semi)) {
1778 Res = ParseExpression();
1779 if (Res.isInvalid()) {
1780 SkipUntil(tok::semi);
1785 ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw");
1786 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope());
1789 /// objc-synchronized-statement:
1790 /// @synchronized '(' expression ')' compound-statement
1793 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1794 ConsumeToken(); // consume synchronized
1795 if (Tok.isNot(tok::l_paren)) {
1796 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1800 // The operand is surrounded with parentheses.
1801 ConsumeParen(); // '('
1802 ExprResult operand(ParseExpression());
1804 if (Tok.is(tok::r_paren)) {
1805 ConsumeParen(); // ')'
1807 if (!operand.isInvalid())
1808 Diag(Tok, diag::err_expected) << tok::r_paren;
1810 // Skip forward until we see a left brace, but don't consume it.
1811 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
1814 // Require a compound statement.
1815 if (Tok.isNot(tok::l_brace)) {
1816 if (!operand.isInvalid())
1817 Diag(Tok, diag::err_expected) << tok::l_brace;
1821 // Check the @synchronized operand now.
1822 if (!operand.isInvalid())
1823 operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get());
1825 // Parse the compound statement within a new scope.
1826 ParseScope bodyScope(this, Scope::DeclScope);
1827 StmtResult body(ParseCompoundStatementBody());
1830 // If there was a semantic or parse error earlier with the
1831 // operand, fail now.
1832 if (operand.isInvalid())
1835 if (body.isInvalid())
1836 body = Actions.ActOnNullStmt(Tok.getLocation());
1838 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get());
1841 /// objc-try-catch-statement:
1842 /// @try compound-statement objc-catch-list[opt]
1843 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1845 /// objc-catch-list:
1846 /// @catch ( parameter-declaration ) compound-statement
1847 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1848 /// catch-parameter-declaration:
1849 /// parameter-declaration
1852 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1853 bool catch_or_finally_seen = false;
1855 ConsumeToken(); // consume try
1856 if (Tok.isNot(tok::l_brace)) {
1857 Diag(Tok, diag::err_expected) << tok::l_brace;
1860 StmtVector CatchStmts;
1861 StmtResult FinallyStmt;
1862 ParseScope TryScope(this, Scope::DeclScope);
1863 StmtResult TryBody(ParseCompoundStatementBody());
1865 if (TryBody.isInvalid())
1866 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1868 while (Tok.is(tok::at)) {
1869 // At this point, we need to lookahead to determine if this @ is the start
1870 // of an @catch or @finally. We don't want to consume the @ token if this
1871 // is an @try or @encode or something else.
1872 Token AfterAt = GetLookAheadToken(1);
1873 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1874 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1877 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1878 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1879 Decl *FirstPart = nullptr;
1880 ConsumeToken(); // consume catch
1881 if (Tok.is(tok::l_paren)) {
1883 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1884 if (Tok.isNot(tok::ellipsis)) {
1885 DeclSpec DS(AttrFactory);
1886 ParseDeclarationSpecifiers(DS);
1887 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1888 ParseDeclarator(ParmDecl);
1890 // Inform the actions module about the declarator, so it
1891 // gets added to the current scope.
1892 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1894 ConsumeToken(); // consume '...'
1896 SourceLocation RParenLoc;
1898 if (Tok.is(tok::r_paren))
1899 RParenLoc = ConsumeParen();
1900 else // Skip over garbage, until we get to ')'. Eat the ')'.
1901 SkipUntil(tok::r_paren, StopAtSemi);
1903 StmtResult CatchBody(true);
1904 if (Tok.is(tok::l_brace))
1905 CatchBody = ParseCompoundStatementBody();
1907 Diag(Tok, diag::err_expected) << tok::l_brace;
1908 if (CatchBody.isInvalid())
1909 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1911 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1915 if (!Catch.isInvalid())
1916 CatchStmts.push_back(Catch.get());
1919 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1923 catch_or_finally_seen = true;
1925 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1926 ConsumeToken(); // consume finally
1927 ParseScope FinallyScope(this, Scope::DeclScope);
1929 StmtResult FinallyBody(true);
1930 if (Tok.is(tok::l_brace))
1931 FinallyBody = ParseCompoundStatementBody();
1933 Diag(Tok, diag::err_expected) << tok::l_brace;
1934 if (FinallyBody.isInvalid())
1935 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1936 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1938 catch_or_finally_seen = true;
1942 if (!catch_or_finally_seen) {
1943 Diag(atLoc, diag::err_missing_catch_finally);
1947 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(),
1952 /// objc-autoreleasepool-statement:
1953 /// @autoreleasepool compound-statement
1956 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1957 ConsumeToken(); // consume autoreleasepool
1958 if (Tok.isNot(tok::l_brace)) {
1959 Diag(Tok, diag::err_expected) << tok::l_brace;
1962 // Enter a scope to hold everything within the compound stmt. Compound
1963 // statements can always hold declarations.
1964 ParseScope BodyScope(this, Scope::DeclScope);
1966 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1969 if (AutoreleasePoolBody.isInvalid())
1970 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1971 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1972 AutoreleasePoolBody.get());
1975 /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them
1976 /// for later parsing.
1977 void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) {
1978 LexedMethod* LM = new LexedMethod(this, MDecl);
1979 CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
1980 CachedTokens &Toks = LM->Toks;
1981 // Begin by storing the '{' or 'try' or ':' token.
1982 Toks.push_back(Tok);
1983 if (Tok.is(tok::kw_try)) {
1985 if (Tok.is(tok::colon)) {
1986 Toks.push_back(Tok);
1988 while (Tok.isNot(tok::l_brace)) {
1989 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1990 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
1993 Toks.push_back(Tok); // also store '{'
1995 else if (Tok.is(tok::colon)) {
1997 while (Tok.isNot(tok::l_brace)) {
1998 ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false);
1999 ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false);
2001 Toks.push_back(Tok); // also store '{'
2004 // Consume everything up to (and including) the matching right brace.
2005 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2006 while (Tok.is(tok::kw_catch)) {
2007 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
2008 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
2012 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
2014 Decl *Parser::ParseObjCMethodDefinition() {
2015 Decl *MDecl = ParseObjCMethodPrototype();
2017 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
2018 "parsing Objective-C method");
2020 // parse optional ';'
2021 if (Tok.is(tok::semi)) {
2022 if (CurParsedObjCImpl) {
2023 Diag(Tok, diag::warn_semicolon_before_method_body)
2024 << FixItHint::CreateRemoval(Tok.getLocation());
2029 // We should have an opening brace now.
2030 if (Tok.isNot(tok::l_brace)) {
2031 Diag(Tok, diag::err_expected_method_body);
2033 // Skip over garbage, until we get to '{'. Don't eat the '{'.
2034 SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
2036 // If we didn't find the '{', bail out.
2037 if (Tok.isNot(tok::l_brace))
2043 SkipUntil(tok::r_brace);
2047 // Allow the rest of sema to find private method decl implementations.
2048 Actions.AddAnyMethodToGlobalPool(MDecl);
2049 assert (CurParsedObjCImpl
2050 && "ParseObjCMethodDefinition - Method out of @implementation");
2051 // Consume the tokens and store them for later parsing.
2052 StashAwayMethodOrFunctionBodyTokens(MDecl);
2056 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
2057 if (Tok.is(tok::code_completion)) {
2058 Actions.CodeCompleteObjCAtStatement(getCurScope());
2063 if (Tok.isObjCAtKeyword(tok::objc_try))
2064 return ParseObjCTryStmt(AtLoc);
2066 if (Tok.isObjCAtKeyword(tok::objc_throw))
2067 return ParseObjCThrowStmt(AtLoc);
2069 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
2070 return ParseObjCSynchronizedStmt(AtLoc);
2072 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
2073 return ParseObjCAutoreleasePoolStmt(AtLoc);
2075 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
2076 if (Res.isInvalid()) {
2077 // If the expression is invalid, skip ahead to the next semicolon. Not
2078 // doing this opens us up to the possibility of infinite loops if
2079 // ParseExpression does not consume any tokens.
2080 SkipUntil(tok::semi);
2084 // Otherwise, eat the semicolon.
2085 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
2086 return Actions.ActOnExprStmt(Res);
2089 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
2090 switch (Tok.getKind()) {
2091 case tok::code_completion:
2092 Actions.CodeCompleteObjCAtExpression(getCurScope());
2098 tok::TokenKind Kind = Tok.getKind();
2099 SourceLocation OpLoc = ConsumeToken();
2101 if (!Tok.is(tok::numeric_constant)) {
2102 const char *Symbol = nullptr;
2104 case tok::minus: Symbol = "-"; break;
2105 case tok::plus: Symbol = "+"; break;
2106 default: llvm_unreachable("missing unary operator case");
2108 Diag(Tok, diag::err_nsnumber_nonliteral_unary)
2113 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2114 if (Lit.isInvalid()) {
2117 ConsumeToken(); // Consume the literal token.
2119 Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get());
2120 if (Lit.isInvalid())
2123 return ParsePostfixExpressionSuffix(
2124 Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()));
2127 case tok::string_literal: // primary-expression: string-literal
2128 case tok::wide_string_literal:
2129 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
2131 case tok::char_constant:
2132 return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
2134 case tok::numeric_constant:
2135 return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
2137 case tok::kw_true: // Objective-C++, etc.
2138 case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
2139 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true));
2140 case tok::kw_false: // Objective-C++, etc.
2141 case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
2142 return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false));
2145 // Objective-C array literal
2146 return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
2149 // Objective-C dictionary literal
2150 return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
2153 // Objective-C boxed expression
2154 return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc));
2157 if (Tok.getIdentifierInfo() == nullptr)
2158 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2160 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
2161 case tok::objc_encode:
2162 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
2163 case tok::objc_protocol:
2164 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
2165 case tok::objc_selector:
2166 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
2168 const char *str = nullptr;
2169 if (GetLookAheadToken(1).is(tok::l_brace)) {
2170 char ch = Tok.getIdentifierInfo()->getNameStart()[0];
2173 : (ch == 'f' ? "finally"
2174 : (ch == 'a' ? "autoreleasepool" : nullptr));
2177 SourceLocation kwLoc = Tok.getLocation();
2178 return ExprError(Diag(AtLoc, diag::err_unexpected_at) <<
2179 FixItHint::CreateReplacement(kwLoc, str));
2182 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
2188 /// \brief Parse the receiver of an Objective-C++ message send.
2190 /// This routine parses the receiver of a message send in
2191 /// Objective-C++ either as a type or as an expression. Note that this
2192 /// routine must not be called to parse a send to 'super', since it
2193 /// has no way to return such a result.
2195 /// \param IsExpr Whether the receiver was parsed as an expression.
2197 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
2198 /// IsExpr is true), the parsed expression. If the receiver was parsed
2199 /// as a type (\c IsExpr is false), the parsed type.
2201 /// \returns True if an error occurred during parsing or semantic
2202 /// analysis, in which case the arguments do not have valid
2203 /// values. Otherwise, returns false for a successful parse.
2205 /// objc-receiver: [C++]
2206 /// 'super' [not parsed here]
2208 /// simple-type-specifier
2209 /// typename-specifier
2210 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
2211 InMessageExpressionRAIIObject InMessage(*this, true);
2213 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
2214 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
2215 TryAnnotateTypeOrScopeToken();
2217 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) {
2220 ExprResult Receiver = ParseExpression();
2221 if (Receiver.isInvalid())
2225 TypeOrExpr = Receiver.get();
2230 // typename-specifier
2231 // simple-type-specifier
2232 // expression (that starts with one of the above)
2233 DeclSpec DS(AttrFactory);
2234 ParseCXXSimpleTypeSpecifier(DS);
2236 if (Tok.is(tok::l_paren)) {
2237 // If we see an opening parentheses at this point, we are
2238 // actually parsing an expression that starts with a
2239 // function-style cast, e.g.,
2241 // postfix-expression:
2242 // simple-type-specifier ( expression-list [opt] )
2243 // typename-specifier ( expression-list [opt] )
2245 // Parse the remainder of this case, then the (optional)
2246 // postfix-expression suffix, followed by the (optional)
2247 // right-hand side of the binary expression. We have an
2249 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
2250 if (!Receiver.isInvalid())
2251 Receiver = ParsePostfixExpressionSuffix(Receiver.get());
2252 if (!Receiver.isInvalid())
2253 Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma);
2254 if (Receiver.isInvalid())
2258 TypeOrExpr = Receiver.get();
2262 // We have a class message. Turn the simple-type-specifier or
2263 // typename-specifier we parsed into a type and parse the
2264 // remainder of the class message.
2265 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2266 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2267 if (Type.isInvalid())
2271 TypeOrExpr = Type.get().getAsOpaquePtr();
2275 /// \brief Determine whether the parser is currently referring to a an
2276 /// Objective-C message send, using a simplified heuristic to avoid overhead.
2278 /// This routine will only return true for a subset of valid message-send
2280 bool Parser::isSimpleObjCMessageExpression() {
2281 assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
2282 "Incorrect start for isSimpleObjCMessageExpression");
2283 return GetLookAheadToken(1).is(tok::identifier) &&
2284 GetLookAheadToken(2).is(tok::identifier);
2287 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
2288 if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||
2289 InMessageExpression)
2295 if (Tok.is(tok::annot_typename))
2296 Type = getTypeAnnotation(Tok);
2297 else if (Tok.is(tok::identifier))
2298 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
2303 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
2304 const Token &AfterNext = GetLookAheadToken(2);
2305 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
2306 if (Tok.is(tok::identifier))
2307 TryAnnotateTypeOrScopeToken();
2309 return Tok.is(tok::annot_typename);
2316 /// objc-message-expr:
2317 /// '[' objc-receiver objc-message-args ']'
2319 /// objc-receiver: [C]
2325 ExprResult Parser::ParseObjCMessageExpression() {
2326 assert(Tok.is(tok::l_square) && "'[' expected");
2327 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
2329 if (Tok.is(tok::code_completion)) {
2330 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
2335 InMessageExpressionRAIIObject InMessage(*this, true);
2337 if (getLangOpts().CPlusPlus) {
2338 // We completely separate the C and C++ cases because C++ requires
2339 // more complicated (read: slower) parsing.
2341 // Handle send to super.
2342 // FIXME: This doesn't benefit from the same typo-correction we
2343 // get in Objective-C.
2344 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2345 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2346 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2347 ParsedType(), nullptr);
2349 // Parse the receiver, which is either a type or an expression.
2351 void *TypeOrExpr = nullptr;
2352 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2353 SkipUntil(tok::r_square, StopAtSemi);
2358 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2360 static_cast<Expr*>(TypeOrExpr));
2362 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2363 ParsedType::getFromOpaquePtr(TypeOrExpr),
2367 if (Tok.is(tok::identifier)) {
2368 IdentifierInfo *Name = Tok.getIdentifierInfo();
2369 SourceLocation NameLoc = Tok.getLocation();
2370 ParsedType ReceiverType;
2371 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2372 Name == Ident_super,
2373 NextToken().is(tok::period),
2375 case Sema::ObjCSuperMessage:
2376 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2377 ParsedType(), nullptr);
2379 case Sema::ObjCClassMessage:
2380 if (!ReceiverType) {
2381 SkipUntil(tok::r_square, StopAtSemi);
2385 ConsumeToken(); // the type name
2387 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2388 ReceiverType, nullptr);
2390 case Sema::ObjCInstanceMessage:
2391 // Fall through to parse an expression.
2396 // Otherwise, an arbitrary expression can be the receiver of a send.
2397 ExprResult Res(ParseExpression());
2398 if (Res.isInvalid()) {
2399 SkipUntil(tok::r_square, StopAtSemi);
2403 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2404 ParsedType(), Res.get());
2407 /// \brief Parse the remainder of an Objective-C message following the
2408 /// '[' objc-receiver.
2410 /// This routine handles sends to super, class messages (sent to a
2411 /// class name), and instance messages (sent to an object), and the
2412 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2413 /// ReceiverExpr, respectively. Only one of these parameters may have
2416 /// \param LBracLoc The location of the opening '['.
2418 /// \param SuperLoc If this is a send to 'super', the location of the
2419 /// 'super' keyword that indicates a send to the superclass.
2421 /// \param ReceiverType If this is a class message, the type of the
2422 /// class we are sending a message to.
2424 /// \param ReceiverExpr If this is an instance message, the expression
2425 /// used to compute the receiver object.
2427 /// objc-message-args:
2429 /// objc-keywordarg-list
2431 /// objc-keywordarg-list:
2433 /// objc-keywordarg-list objc-keywordarg
2435 /// objc-keywordarg:
2436 /// selector-name[opt] ':' objc-keywordexpr
2438 /// objc-keywordexpr:
2439 /// nonempty-expr-list
2441 /// nonempty-expr-list:
2442 /// assignment-expression
2443 /// nonempty-expr-list , assignment-expression
2446 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2447 SourceLocation SuperLoc,
2448 ParsedType ReceiverType,
2449 ExprArg ReceiverExpr) {
2450 InMessageExpressionRAIIObject InMessage(*this, true);
2452 if (Tok.is(tok::code_completion)) {
2453 if (SuperLoc.isValid())
2454 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None,
2456 else if (ReceiverType)
2457 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None,
2460 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2466 // Parse objc-selector
2468 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2470 SmallVector<IdentifierInfo *, 12> KeyIdents;
2471 SmallVector<SourceLocation, 12> KeyLocs;
2472 ExprVector KeyExprs;
2474 if (Tok.is(tok::colon)) {
2476 // Each iteration parses a single keyword argument.
2477 KeyIdents.push_back(selIdent);
2478 KeyLocs.push_back(Loc);
2480 if (ExpectAndConsume(tok::colon)) {
2481 // We must manually skip to a ']', otherwise the expression skipper will
2482 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2483 // the enclosing expression.
2484 SkipUntil(tok::r_square, StopAtSemi);
2488 /// Parse the expression after ':'
2490 if (Tok.is(tok::code_completion)) {
2491 if (SuperLoc.isValid())
2492 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2494 /*AtArgumentEpression=*/true);
2495 else if (ReceiverType)
2496 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2498 /*AtArgumentEpression=*/true);
2500 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2502 /*AtArgumentEpression=*/true);
2509 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2510 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2511 Expr = ParseBraceInitializer();
2513 Expr = ParseAssignmentExpression();
2515 ExprResult Res(Expr);
2516 if (Res.isInvalid()) {
2517 // We must manually skip to a ']', otherwise the expression skipper will
2518 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2519 // the enclosing expression.
2520 SkipUntil(tok::r_square, StopAtSemi);
2524 // We have a valid expression.
2525 KeyExprs.push_back(Res.get());
2527 // Code completion after each argument.
2528 if (Tok.is(tok::code_completion)) {
2529 if (SuperLoc.isValid())
2530 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2532 /*AtArgumentEpression=*/false);
2533 else if (ReceiverType)
2534 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2536 /*AtArgumentEpression=*/false);
2538 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2540 /*AtArgumentEpression=*/false);
2545 // Check for another keyword selector.
2546 selIdent = ParseObjCSelectorPiece(Loc);
2547 if (!selIdent && Tok.isNot(tok::colon))
2549 // We have a selector or a colon, continue parsing.
2551 // Parse the, optional, argument list, comma separated.
2552 while (Tok.is(tok::comma)) {
2553 SourceLocation commaLoc = ConsumeToken(); // Eat the ','.
2554 /// Parse the expression after ','
2555 ExprResult Res(ParseAssignmentExpression());
2556 if (Res.isInvalid()) {
2557 if (Tok.is(tok::colon)) {
2558 Diag(commaLoc, diag::note_extra_comma_message_arg) <<
2559 FixItHint::CreateRemoval(commaLoc);
2561 // We must manually skip to a ']', otherwise the expression skipper will
2562 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2563 // the enclosing expression.
2564 SkipUntil(tok::r_square, StopAtSemi);
2568 // We have a valid expression.
2569 KeyExprs.push_back(Res.get());
2571 } else if (!selIdent) {
2572 Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name.
2574 // We must manually skip to a ']', otherwise the expression skipper will
2575 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2576 // the enclosing expression.
2577 SkipUntil(tok::r_square, StopAtSemi);
2581 if (Tok.isNot(tok::r_square)) {
2582 Diag(Tok, diag::err_expected)
2583 << (Tok.is(tok::identifier) ? tok::colon : tok::r_square);
2584 // We must manually skip to a ']', otherwise the expression skipper will
2585 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2586 // the enclosing expression.
2587 SkipUntil(tok::r_square, StopAtSemi);
2591 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2593 unsigned nKeys = KeyIdents.size();
2595 KeyIdents.push_back(selIdent);
2596 KeyLocs.push_back(Loc);
2598 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2600 if (SuperLoc.isValid())
2601 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2602 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2603 else if (ReceiverType)
2604 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2605 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2606 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2607 LBracLoc, KeyLocs, RBracLoc, KeyExprs);
2610 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2611 ExprResult Res(ParseStringLiteralExpression());
2612 if (Res.isInvalid()) return Res;
2614 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2615 // expressions. At this point, we know that the only valid thing that starts
2616 // with '@' is an @"".
2617 SmallVector<SourceLocation, 4> AtLocs;
2618 ExprVector AtStrings;
2619 AtLocs.push_back(AtLoc);
2620 AtStrings.push_back(Res.get());
2622 while (Tok.is(tok::at)) {
2623 AtLocs.push_back(ConsumeToken()); // eat the @.
2625 // Invalid unless there is a string literal.
2626 if (!isTokenStringLiteral())
2627 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2629 ExprResult Lit(ParseStringLiteralExpression());
2630 if (Lit.isInvalid())
2633 AtStrings.push_back(Lit.get());
2636 return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(),
2640 /// ParseObjCBooleanLiteral -
2641 /// objc-scalar-literal : '@' boolean-keyword
2643 /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
2645 ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,
2647 SourceLocation EndLoc = ConsumeToken(); // consume the keyword.
2648 return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
2651 /// ParseObjCCharacterLiteral -
2652 /// objc-scalar-literal : '@' character-literal
2654 ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
2655 ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
2656 if (Lit.isInvalid()) {
2659 ConsumeToken(); // Consume the literal token.
2660 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
2663 /// ParseObjCNumericLiteral -
2664 /// objc-scalar-literal : '@' scalar-literal
2666 /// scalar-literal : | numeric-constant /* any numeric constant. */
2668 ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
2669 ExprResult Lit(Actions.ActOnNumericConstant(Tok));
2670 if (Lit.isInvalid()) {
2673 ConsumeToken(); // Consume the literal token.
2674 return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get());
2677 /// ParseObjCBoxedExpr -
2678 /// objc-box-expression:
2679 /// @( assignment-expression )
2681 Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) {
2682 if (Tok.isNot(tok::l_paren))
2683 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@");
2685 BalancedDelimiterTracker T(*this, tok::l_paren);
2687 ExprResult ValueExpr(ParseAssignmentExpression());
2688 if (T.consumeClose())
2691 if (ValueExpr.isInvalid())
2694 // Wrap the sub-expression in a parenthesized expression, to distinguish
2695 // a boxed expression from a literal.
2696 SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation();
2697 ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get());
2698 return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc),
2702 ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
2703 ExprVector ElementExprs; // array elements.
2704 ConsumeBracket(); // consume the l_square.
2706 while (Tok.isNot(tok::r_square)) {
2707 // Parse list of array element expressions (all must be id types).
2708 ExprResult Res(ParseAssignmentExpression());
2709 if (Res.isInvalid()) {
2710 // We must manually skip to a ']', otherwise the expression skipper will
2711 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2712 // the enclosing expression.
2713 SkipUntil(tok::r_square, StopAtSemi);
2717 // Parse the ellipsis that indicates a pack expansion.
2718 if (Tok.is(tok::ellipsis))
2719 Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken());
2720 if (Res.isInvalid())
2723 ElementExprs.push_back(Res.get());
2725 if (Tok.is(tok::comma))
2726 ConsumeToken(); // Eat the ','.
2727 else if (Tok.isNot(tok::r_square))
2728 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square
2731 SourceLocation EndLoc = ConsumeBracket(); // location of ']'
2732 MultiExprArg Args(ElementExprs);
2733 return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args);
2736 ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
2737 SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
2738 ConsumeBrace(); // consume the l_square.
2739 while (Tok.isNot(tok::r_brace)) {
2740 // Parse the comma separated key : value expressions.
2743 ColonProtectionRAIIObject X(*this);
2744 KeyExpr = ParseAssignmentExpression();
2745 if (KeyExpr.isInvalid()) {
2746 // We must manually skip to a '}', otherwise the expression skipper will
2747 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2748 // the enclosing expression.
2749 SkipUntil(tok::r_brace, StopAtSemi);
2754 if (ExpectAndConsume(tok::colon)) {
2755 SkipUntil(tok::r_brace, StopAtSemi);
2759 ExprResult ValueExpr(ParseAssignmentExpression());
2760 if (ValueExpr.isInvalid()) {
2761 // We must manually skip to a '}', otherwise the expression skipper will
2762 // stop at the '}' when it skips to the ';'. We want it to skip beyond
2763 // the enclosing expression.
2764 SkipUntil(tok::r_brace, StopAtSemi);
2768 // Parse the ellipsis that designates this as a pack expansion.
2769 SourceLocation EllipsisLoc;
2770 if (getLangOpts().CPlusPlus)
2771 TryConsumeToken(tok::ellipsis, EllipsisLoc);
2773 // We have a valid expression. Collect it in a vector so we can
2774 // build the argument list.
2775 ObjCDictionaryElement Element = {
2776 KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None
2778 Elements.push_back(Element);
2780 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace))
2781 return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace
2784 SourceLocation EndLoc = ConsumeBrace();
2786 // Create the ObjCDictionaryLiteral.
2787 return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc),
2788 Elements.data(), Elements.size());
2791 /// objc-encode-expression:
2792 /// \@encode ( type-name )
2794 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2795 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2797 SourceLocation EncLoc = ConsumeToken();
2799 if (Tok.isNot(tok::l_paren))
2800 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2802 BalancedDelimiterTracker T(*this, tok::l_paren);
2805 TypeResult Ty = ParseTypeName();
2812 return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(),
2813 Ty.get(), T.getCloseLocation());
2816 /// objc-protocol-expression
2817 /// \@protocol ( protocol-name )
2819 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2820 SourceLocation ProtoLoc = ConsumeToken();
2822 if (Tok.isNot(tok::l_paren))
2823 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2825 BalancedDelimiterTracker T(*this, tok::l_paren);
2828 if (Tok.isNot(tok::identifier))
2829 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
2831 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2832 SourceLocation ProtoIdLoc = ConsumeToken();
2836 return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2837 T.getOpenLocation(), ProtoIdLoc,
2838 T.getCloseLocation());
2841 /// objc-selector-expression
2842 /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')'
2843 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2844 SourceLocation SelectorLoc = ConsumeToken();
2846 if (Tok.isNot(tok::l_paren))
2847 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2849 SmallVector<IdentifierInfo *, 12> KeyIdents;
2850 SourceLocation sLoc;
2852 BalancedDelimiterTracker T(*this, tok::l_paren);
2854 bool HasOptionalParen = Tok.is(tok::l_paren);
2855 if (HasOptionalParen)
2858 if (Tok.is(tok::code_completion)) {
2859 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2864 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2865 if (!SelIdent && // missing selector name.
2866 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2867 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
2869 KeyIdents.push_back(SelIdent);
2871 unsigned nColons = 0;
2872 if (Tok.isNot(tok::r_paren)) {
2874 if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++.
2876 KeyIdents.push_back(nullptr);
2877 } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'.
2881 if (Tok.is(tok::r_paren))
2884 if (Tok.is(tok::code_completion)) {
2885 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents);
2890 // Check for another keyword selector.
2892 SelIdent = ParseObjCSelectorPiece(Loc);
2893 KeyIdents.push_back(SelIdent);
2894 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2898 if (HasOptionalParen && Tok.is(tok::r_paren))
2899 ConsumeParen(); // ')'
2901 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2902 return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2903 T.getOpenLocation(),
2904 T.getCloseLocation(),
2908 void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) {
2909 // MCDecl might be null due to error in method or c-function prototype, etc.
2910 Decl *MCDecl = LM.D;
2911 bool skip = MCDecl &&
2912 ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) ||
2913 (!parseMethod && Actions.isObjCMethodDecl(MCDecl)));
2917 // Save the current token position.
2918 SourceLocation OrigLoc = Tok.getLocation();
2920 assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
2921 // Append the current token at the end of the new token stream so that it
2922 // doesn't get lost.
2923 LM.Toks.push_back(Tok);
2924 PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false);
2926 // Consume the previously pushed token.
2927 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
2929 assert((Tok.is(tok::l_brace) || Tok.is(tok::kw_try) ||
2930 Tok.is(tok::colon)) &&
2931 "Inline objective-c method not starting with '{' or 'try' or ':'");
2932 // Enter a scope for the method or c-function body.
2933 ParseScope BodyScope(this,
2935 ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope
2936 : Scope::FnScope|Scope::DeclScope);
2938 // Tell the actions module that we have entered a method or c-function definition
2939 // with the specified Declarator for the method/function.
2941 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl);
2943 Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl);
2944 if (Tok.is(tok::kw_try))
2945 ParseFunctionTryBlock(MCDecl, BodyScope);
2947 if (Tok.is(tok::colon))
2948 ParseConstructorInitializer(MCDecl);
2949 ParseFunctionStatementBody(MCDecl, BodyScope);
2952 if (Tok.getLocation() != OrigLoc) {
2953 // Due to parsing error, we either went over the cached tokens or
2954 // there are still cached tokens left. If it's the latter case skip the
2956 // Since this is an uncommon situation that should be avoided, use the
2957 // expensive isBeforeInTranslationUnit call.
2958 if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
2960 while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))