[Heikki Kultala] This patch contains the ABI changes for the TCE target.
[clang.git] / lib / Parse / ParseObjc.cpp
blobf32a322f024ad7142b8a1350508c7899a0063973
1 //===--- ParseObjC.cpp - Objective C Parsing ------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Objective-C portions of the Parser interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/ParseDiagnostic.h"
15 #include "clang/Parse/Parser.h"
16 #include "RAIIObjectsForParser.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/PrettyDeclStackTrace.h"
19 #include "clang/Sema/Scope.h"
20 #include "llvm/ADT/SmallVector.h"
21 using namespace clang;
24 /// ParseObjCAtDirectives - Handle parts of the external-declaration production:
25 /// external-declaration: [C99 6.9]
26 /// [OBJC] objc-class-definition
27 /// [OBJC] objc-class-declaration
28 /// [OBJC] objc-alias-declaration
29 /// [OBJC] objc-protocol-definition
30 /// [OBJC] objc-method-definition
31 /// [OBJC] '@' 'end'
32 Decl *Parser::ParseObjCAtDirectives() {
33 SourceLocation AtLoc = ConsumeToken(); // the "@"
35 if (Tok.is(tok::code_completion)) {
36 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, false);
37 ConsumeCodeCompletionToken();
40 switch (Tok.getObjCKeywordID()) {
41 case tok::objc_class:
42 return ParseObjCAtClassDeclaration(AtLoc);
43 case tok::objc_interface: {
44 ParsedAttributes attrs;
45 return ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
47 case tok::objc_protocol: {
48 ParsedAttributes attrs;
49 return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
51 case tok::objc_implementation:
52 return ParseObjCAtImplementationDeclaration(AtLoc);
53 case tok::objc_end:
54 return ParseObjCAtEndDeclaration(AtLoc);
55 case tok::objc_compatibility_alias:
56 return ParseObjCAtAliasDeclaration(AtLoc);
57 case tok::objc_synthesize:
58 return ParseObjCPropertySynthesize(AtLoc);
59 case tok::objc_dynamic:
60 return ParseObjCPropertyDynamic(AtLoc);
61 default:
62 Diag(AtLoc, diag::err_unexpected_at);
63 SkipUntil(tok::semi);
64 return 0;
68 ///
69 /// objc-class-declaration:
70 /// '@' 'class' identifier-list ';'
71 ///
72 Decl *Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
73 ConsumeToken(); // the identifier "class"
74 llvm::SmallVector<IdentifierInfo *, 8> ClassNames;
75 llvm::SmallVector<SourceLocation, 8> ClassLocs;
78 while (1) {
79 if (Tok.isNot(tok::identifier)) {
80 Diag(Tok, diag::err_expected_ident);
81 SkipUntil(tok::semi);
82 return 0;
84 ClassNames.push_back(Tok.getIdentifierInfo());
85 ClassLocs.push_back(Tok.getLocation());
86 ConsumeToken();
88 if (Tok.isNot(tok::comma))
89 break;
91 ConsumeToken();
94 // Consume the ';'.
95 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
96 return 0;
98 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
99 ClassLocs.data(),
100 ClassNames.size());
104 /// objc-interface:
105 /// objc-class-interface-attributes[opt] objc-class-interface
106 /// objc-category-interface
108 /// objc-class-interface:
109 /// '@' 'interface' identifier objc-superclass[opt]
110 /// objc-protocol-refs[opt]
111 /// objc-class-instance-variables[opt]
112 /// objc-interface-decl-list
113 /// @end
115 /// objc-category-interface:
116 /// '@' 'interface' identifier '(' identifier[opt] ')'
117 /// objc-protocol-refs[opt]
118 /// objc-interface-decl-list
119 /// @end
121 /// objc-superclass:
122 /// ':' identifier
124 /// objc-class-interface-attributes:
125 /// __attribute__((visibility("default")))
126 /// __attribute__((visibility("hidden")))
127 /// __attribute__((deprecated))
128 /// __attribute__((unavailable))
129 /// __attribute__((objc_exception)) - used by NSException on 64-bit
131 Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
132 ParsedAttributes &attrs) {
133 assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
134 "ParseObjCAtInterfaceDeclaration(): Expected @interface");
135 ConsumeToken(); // the "interface" identifier
137 // Code completion after '@interface'.
138 if (Tok.is(tok::code_completion)) {
139 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
140 ConsumeCodeCompletionToken();
143 if (Tok.isNot(tok::identifier)) {
144 Diag(Tok, diag::err_expected_ident); // missing class or category name.
145 return 0;
148 // We have a class or category name - consume it.
149 IdentifierInfo *nameId = Tok.getIdentifierInfo();
150 SourceLocation nameLoc = ConsumeToken();
151 if (Tok.is(tok::l_paren) &&
152 !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category.
153 // TODO(dgregor): Use the return value from the next line to provide better
154 // recovery.
155 ConsumeParen();
156 SourceLocation categoryLoc, rparenLoc;
157 IdentifierInfo *categoryId = 0;
158 if (Tok.is(tok::code_completion)) {
159 Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc);
160 ConsumeCodeCompletionToken();
163 // For ObjC2, the category name is optional (not an error).
164 if (Tok.is(tok::identifier)) {
165 categoryId = Tok.getIdentifierInfo();
166 categoryLoc = ConsumeToken();
168 else if (!getLang().ObjC2) {
169 Diag(Tok, diag::err_expected_ident); // missing category name.
170 return 0;
172 if (Tok.isNot(tok::r_paren)) {
173 Diag(Tok, diag::err_expected_rparen);
174 SkipUntil(tok::r_paren, false); // don't stop at ';'
175 return 0;
177 rparenLoc = ConsumeParen();
178 // Next, we need to check for any protocol references.
179 SourceLocation LAngleLoc, EndProtoLoc;
180 llvm::SmallVector<Decl *, 8> ProtocolRefs;
181 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
182 if (Tok.is(tok::less) &&
183 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
184 LAngleLoc, EndProtoLoc))
185 return 0;
187 if (!attrs.empty()) // categories don't support attributes.
188 Diag(Tok, diag::err_objc_no_attributes_on_category);
190 Decl *CategoryType =
191 Actions.ActOnStartCategoryInterface(atLoc,
192 nameId, nameLoc,
193 categoryId, categoryLoc,
194 ProtocolRefs.data(),
195 ProtocolRefs.size(),
196 ProtocolLocs.data(),
197 EndProtoLoc);
198 if (Tok.is(tok::l_brace))
199 ParseObjCClassInstanceVariables(CategoryType, tok::objc_private,
200 atLoc);
202 ParseObjCInterfaceDeclList(CategoryType, tok::objc_not_keyword);
203 return CategoryType;
205 // Parse a class interface.
206 IdentifierInfo *superClassId = 0;
207 SourceLocation superClassLoc;
209 if (Tok.is(tok::colon)) { // a super class is specified.
210 ConsumeToken();
212 // Code completion of superclass names.
213 if (Tok.is(tok::code_completion)) {
214 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
215 ConsumeCodeCompletionToken();
218 if (Tok.isNot(tok::identifier)) {
219 Diag(Tok, diag::err_expected_ident); // missing super class name.
220 return 0;
222 superClassId = Tok.getIdentifierInfo();
223 superClassLoc = ConsumeToken();
225 // Next, we need to check for any protocol references.
226 llvm::SmallVector<Decl *, 8> ProtocolRefs;
227 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
228 SourceLocation LAngleLoc, EndProtoLoc;
229 if (Tok.is(tok::less) &&
230 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true,
231 LAngleLoc, EndProtoLoc))
232 return 0;
234 Decl *ClsType =
235 Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc,
236 superClassId, superClassLoc,
237 ProtocolRefs.data(), ProtocolRefs.size(),
238 ProtocolLocs.data(),
239 EndProtoLoc, attrs.getList());
241 if (Tok.is(tok::l_brace))
242 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, atLoc);
244 ParseObjCInterfaceDeclList(ClsType, tok::objc_interface);
245 return ClsType;
248 /// The Objective-C property callback. This should be defined where
249 /// it's used, but instead it's been lifted to here to support VS2005.
250 struct Parser::ObjCPropertyCallback : FieldCallback {
251 Parser &P;
252 Decl *IDecl;
253 llvm::SmallVectorImpl<Decl *> &Props;
254 ObjCDeclSpec &OCDS;
255 SourceLocation AtLoc;
256 tok::ObjCKeywordKind MethodImplKind;
258 ObjCPropertyCallback(Parser &P, Decl *IDecl,
259 llvm::SmallVectorImpl<Decl *> &Props,
260 ObjCDeclSpec &OCDS, SourceLocation AtLoc,
261 tok::ObjCKeywordKind MethodImplKind) :
262 P(P), IDecl(IDecl), Props(Props), OCDS(OCDS), AtLoc(AtLoc),
263 MethodImplKind(MethodImplKind) {
266 Decl *invoke(FieldDeclarator &FD) {
267 if (FD.D.getIdentifier() == 0) {
268 P.Diag(AtLoc, diag::err_objc_property_requires_field_name)
269 << FD.D.getSourceRange();
270 return 0;
272 if (FD.BitfieldSize) {
273 P.Diag(AtLoc, diag::err_objc_property_bitfield)
274 << FD.D.getSourceRange();
275 return 0;
278 // Install the property declarator into interfaceDecl.
279 IdentifierInfo *SelName =
280 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
282 Selector GetterSel =
283 P.PP.getSelectorTable().getNullarySelector(SelName);
284 IdentifierInfo *SetterName = OCDS.getSetterName();
285 Selector SetterSel;
286 if (SetterName)
287 SetterSel = P.PP.getSelectorTable().getSelector(1, &SetterName);
288 else
289 SetterSel = SelectorTable::constructSetterName(P.PP.getIdentifierTable(),
290 P.PP.getSelectorTable(),
291 FD.D.getIdentifier());
292 bool isOverridingProperty = false;
293 Decl *Property =
294 P.Actions.ActOnProperty(P.getCurScope(), AtLoc, FD, OCDS,
295 GetterSel, SetterSel, IDecl,
296 &isOverridingProperty,
297 MethodImplKind);
298 if (!isOverridingProperty)
299 Props.push_back(Property);
301 return Property;
305 /// objc-interface-decl-list:
306 /// empty
307 /// objc-interface-decl-list objc-property-decl [OBJC2]
308 /// objc-interface-decl-list objc-method-requirement [OBJC2]
309 /// objc-interface-decl-list objc-method-proto ';'
310 /// objc-interface-decl-list declaration
311 /// objc-interface-decl-list ';'
313 /// objc-method-requirement: [OBJC2]
314 /// @required
315 /// @optional
317 void Parser::ParseObjCInterfaceDeclList(Decl *interfaceDecl,
318 tok::ObjCKeywordKind contextKey) {
319 llvm::SmallVector<Decl *, 32> allMethods;
320 llvm::SmallVector<Decl *, 16> allProperties;
321 llvm::SmallVector<DeclGroupPtrTy, 8> allTUVariables;
322 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword;
324 SourceRange AtEnd;
326 while (1) {
327 // If this is a method prototype, parse it.
328 if (Tok.is(tok::minus) || Tok.is(tok::plus)) {
329 Decl *methodPrototype =
330 ParseObjCMethodPrototype(interfaceDecl, MethodImplKind);
331 allMethods.push_back(methodPrototype);
332 // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for
333 // method definitions.
334 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_method_proto,
335 "", tok::semi);
336 continue;
338 if (Tok.is(tok::l_paren)) {
339 Diag(Tok, diag::err_expected_minus_or_plus);
340 ParseObjCMethodDecl(Tok.getLocation(),
341 tok::minus,
342 interfaceDecl,
343 MethodImplKind);
344 continue;
346 // Ignore excess semicolons.
347 if (Tok.is(tok::semi)) {
348 ConsumeToken();
349 continue;
352 // If we got to the end of the file, exit the loop.
353 if (Tok.is(tok::eof))
354 break;
356 // Code completion within an Objective-C interface.
357 if (Tok.is(tok::code_completion)) {
358 Actions.CodeCompleteOrdinaryName(getCurScope(),
359 ObjCImpDecl? Sema::PCC_ObjCImplementation
360 : Sema::PCC_ObjCInterface);
361 ConsumeCodeCompletionToken();
364 // If we don't have an @ directive, parse it as a function definition.
365 if (Tok.isNot(tok::at)) {
366 // The code below does not consume '}'s because it is afraid of eating the
367 // end of a namespace. Because of the way this code is structured, an
368 // erroneous r_brace would cause an infinite loop if not handled here.
369 if (Tok.is(tok::r_brace))
370 break;
372 // FIXME: as the name implies, this rule allows function definitions.
373 // We could pass a flag or check for functions during semantic analysis.
374 ParsedAttributes attrs;
375 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
376 continue;
379 // Otherwise, we have an @ directive, eat the @.
380 SourceLocation AtLoc = ConsumeToken(); // the "@"
381 if (Tok.is(tok::code_completion)) {
382 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, true);
383 ConsumeCodeCompletionToken();
384 break;
387 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
389 if (DirectiveKind == tok::objc_end) { // @end -> terminate list
390 AtEnd.setBegin(AtLoc);
391 AtEnd.setEnd(Tok.getLocation());
392 break;
393 } else if (DirectiveKind == tok::objc_not_keyword) {
394 Diag(Tok, diag::err_objc_unknown_at);
395 SkipUntil(tok::semi);
396 continue;
399 // Eat the identifier.
400 ConsumeToken();
402 switch (DirectiveKind) {
403 default:
404 // FIXME: If someone forgets an @end on a protocol, this loop will
405 // continue to eat up tons of stuff and spew lots of nonsense errors. It
406 // would probably be better to bail out if we saw an @class or @interface
407 // or something like that.
408 Diag(AtLoc, diag::err_objc_illegal_interface_qual);
409 // Skip until we see an '@' or '}' or ';'.
410 SkipUntil(tok::r_brace, tok::at);
411 break;
413 case tok::objc_implementation:
414 case tok::objc_interface:
415 Diag(Tok, diag::err_objc_missing_end);
416 ConsumeToken();
417 break;
419 case tok::objc_required:
420 case tok::objc_optional:
421 // This is only valid on protocols.
422 // FIXME: Should this check for ObjC2 being enabled?
423 if (contextKey != tok::objc_protocol)
424 Diag(AtLoc, diag::err_objc_directive_only_in_protocol);
425 else
426 MethodImplKind = DirectiveKind;
427 break;
429 case tok::objc_property:
430 if (!getLang().ObjC2)
431 Diag(AtLoc, diag::err_objc_properties_require_objc2);
433 ObjCDeclSpec OCDS;
434 // Parse property attribute list, if any.
435 if (Tok.is(tok::l_paren))
436 ParseObjCPropertyAttribute(OCDS, interfaceDecl);
438 ObjCPropertyCallback Callback(*this, interfaceDecl, allProperties,
439 OCDS, AtLoc, MethodImplKind);
441 // Parse all the comma separated declarators.
442 DeclSpec DS;
443 ParseStructDeclaration(DS, Callback);
445 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list, "",
446 tok::at);
447 break;
451 // We break out of the big loop in two cases: when we see @end or when we see
452 // EOF. In the former case, eat the @end. In the later case, emit an error.
453 if (Tok.is(tok::code_completion)) {
454 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, true);
455 ConsumeCodeCompletionToken();
456 } else if (Tok.isObjCAtKeyword(tok::objc_end))
457 ConsumeToken(); // the "end" identifier
458 else
459 Diag(Tok, diag::err_objc_missing_end);
461 // Insert collected methods declarations into the @interface object.
462 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
463 Actions.ActOnAtEnd(getCurScope(), AtEnd, interfaceDecl,
464 allMethods.data(), allMethods.size(),
465 allProperties.data(), allProperties.size(),
466 allTUVariables.data(), allTUVariables.size());
469 /// Parse property attribute declarations.
471 /// property-attr-decl: '(' property-attrlist ')'
472 /// property-attrlist:
473 /// property-attribute
474 /// property-attrlist ',' property-attribute
475 /// property-attribute:
476 /// getter '=' identifier
477 /// setter '=' identifier ':'
478 /// readonly
479 /// readwrite
480 /// assign
481 /// retain
482 /// copy
483 /// nonatomic
485 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS, Decl *ClassDecl) {
486 assert(Tok.getKind() == tok::l_paren);
487 SourceLocation LHSLoc = ConsumeParen(); // consume '('
489 while (1) {
490 if (Tok.is(tok::code_completion)) {
491 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
492 ConsumeCodeCompletionToken();
494 const IdentifierInfo *II = Tok.getIdentifierInfo();
496 // If this is not an identifier at all, bail out early.
497 if (II == 0) {
498 MatchRHSPunctuation(tok::r_paren, LHSLoc);
499 return;
502 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
504 if (II->isStr("readonly"))
505 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
506 else if (II->isStr("assign"))
507 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
508 else if (II->isStr("readwrite"))
509 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
510 else if (II->isStr("retain"))
511 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
512 else if (II->isStr("copy"))
513 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
514 else if (II->isStr("nonatomic"))
515 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
516 else if (II->isStr("atomic"))
517 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
518 else if (II->isStr("getter") || II->isStr("setter")) {
519 bool IsSetter = II->getNameStart()[0] == 's';
521 // getter/setter require extra treatment.
522 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
523 diag::err_objc_expected_equal_for_getter;
525 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
526 return;
528 if (Tok.is(tok::code_completion)) {
529 if (IsSetter)
530 Actions.CodeCompleteObjCPropertySetter(getCurScope(), ClassDecl);
531 else
532 Actions.CodeCompleteObjCPropertyGetter(getCurScope(), ClassDecl);
533 ConsumeCodeCompletionToken();
537 SourceLocation SelLoc;
538 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
540 if (!SelIdent) {
541 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
542 << IsSetter;
543 SkipUntil(tok::r_paren);
544 return;
547 if (IsSetter) {
548 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
549 DS.setSetterName(SelIdent);
551 if (ExpectAndConsume(tok::colon,
552 diag::err_expected_colon_after_setter_name, "",
553 tok::r_paren))
554 return;
555 } else {
556 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
557 DS.setGetterName(SelIdent);
559 } else {
560 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
561 SkipUntil(tok::r_paren);
562 return;
565 if (Tok.isNot(tok::comma))
566 break;
568 ConsumeToken();
571 MatchRHSPunctuation(tok::r_paren, LHSLoc);
574 /// objc-method-proto:
575 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
576 /// objc-class-method objc-method-decl objc-method-attributes[opt]
578 /// objc-instance-method: '-'
579 /// objc-class-method: '+'
581 /// objc-method-attributes: [OBJC2]
582 /// __attribute__((deprecated))
584 Decl *Parser::ParseObjCMethodPrototype(Decl *IDecl,
585 tok::ObjCKeywordKind MethodImplKind) {
586 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
588 tok::TokenKind methodType = Tok.getKind();
589 SourceLocation mLoc = ConsumeToken();
590 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, IDecl,MethodImplKind);
591 // Since this rule is used for both method declarations and definitions,
592 // the caller is (optionally) responsible for consuming the ';'.
593 return MDecl;
596 /// objc-selector:
597 /// identifier
598 /// one of
599 /// enum struct union if else while do for switch case default
600 /// break continue return goto asm sizeof typeof __alignof
601 /// unsigned long const short volatile signed restrict _Complex
602 /// in out inout bycopy byref oneway int char float double void _Bool
604 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
606 switch (Tok.getKind()) {
607 default:
608 return 0;
609 case tok::ampamp:
610 case tok::ampequal:
611 case tok::amp:
612 case tok::pipe:
613 case tok::tilde:
614 case tok::exclaim:
615 case tok::exclaimequal:
616 case tok::pipepipe:
617 case tok::pipeequal:
618 case tok::caret:
619 case tok::caretequal: {
620 std::string ThisTok(PP.getSpelling(Tok));
621 if (isalpha(ThisTok[0])) {
622 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
623 Tok.setKind(tok::identifier);
624 SelectorLoc = ConsumeToken();
625 return II;
627 return 0;
630 case tok::identifier:
631 case tok::kw_asm:
632 case tok::kw_auto:
633 case tok::kw_bool:
634 case tok::kw_break:
635 case tok::kw_case:
636 case tok::kw_catch:
637 case tok::kw_char:
638 case tok::kw_class:
639 case tok::kw_const:
640 case tok::kw_const_cast:
641 case tok::kw_continue:
642 case tok::kw_default:
643 case tok::kw_delete:
644 case tok::kw_do:
645 case tok::kw_double:
646 case tok::kw_dynamic_cast:
647 case tok::kw_else:
648 case tok::kw_enum:
649 case tok::kw_explicit:
650 case tok::kw_export:
651 case tok::kw_extern:
652 case tok::kw_false:
653 case tok::kw_float:
654 case tok::kw_for:
655 case tok::kw_friend:
656 case tok::kw_goto:
657 case tok::kw_if:
658 case tok::kw_inline:
659 case tok::kw_int:
660 case tok::kw_long:
661 case tok::kw_mutable:
662 case tok::kw_namespace:
663 case tok::kw_new:
664 case tok::kw_operator:
665 case tok::kw_private:
666 case tok::kw_protected:
667 case tok::kw_public:
668 case tok::kw_register:
669 case tok::kw_reinterpret_cast:
670 case tok::kw_restrict:
671 case tok::kw_return:
672 case tok::kw_short:
673 case tok::kw_signed:
674 case tok::kw_sizeof:
675 case tok::kw_static:
676 case tok::kw_static_cast:
677 case tok::kw_struct:
678 case tok::kw_switch:
679 case tok::kw_template:
680 case tok::kw_this:
681 case tok::kw_throw:
682 case tok::kw_true:
683 case tok::kw_try:
684 case tok::kw_typedef:
685 case tok::kw_typeid:
686 case tok::kw_typename:
687 case tok::kw_typeof:
688 case tok::kw_union:
689 case tok::kw_unsigned:
690 case tok::kw_using:
691 case tok::kw_virtual:
692 case tok::kw_void:
693 case tok::kw_volatile:
694 case tok::kw_wchar_t:
695 case tok::kw_while:
696 case tok::kw__Bool:
697 case tok::kw__Complex:
698 case tok::kw___alignof:
699 IdentifierInfo *II = Tok.getIdentifierInfo();
700 SelectorLoc = ConsumeToken();
701 return II;
705 /// objc-for-collection-in: 'in'
707 bool Parser::isTokIdentifier_in() const {
708 // FIXME: May have to do additional look-ahead to only allow for
709 // valid tokens following an 'in'; such as an identifier, unary operators,
710 // '[' etc.
711 return (getLang().ObjC2 && Tok.is(tok::identifier) &&
712 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
715 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
716 /// qualifier list and builds their bitmask representation in the input
717 /// argument.
719 /// objc-type-qualifiers:
720 /// objc-type-qualifier
721 /// objc-type-qualifiers objc-type-qualifier
723 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, bool IsParameter) {
724 while (1) {
725 if (Tok.is(tok::code_completion)) {
726 Actions.CodeCompleteObjCPassingType(getCurScope(), DS, IsParameter);
727 ConsumeCodeCompletionToken();
730 if (Tok.isNot(tok::identifier))
731 return;
733 const IdentifierInfo *II = Tok.getIdentifierInfo();
734 for (unsigned i = 0; i != objc_NumQuals; ++i) {
735 if (II != ObjCTypeQuals[i])
736 continue;
738 ObjCDeclSpec::ObjCDeclQualifier Qual;
739 switch (i) {
740 default: assert(0 && "Unknown decl qualifier");
741 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
742 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
743 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
744 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
745 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
746 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
748 DS.setObjCDeclQualifier(Qual);
749 ConsumeToken();
750 II = 0;
751 break;
754 // If this wasn't a recognized qualifier, bail out.
755 if (II) return;
759 /// objc-type-name:
760 /// '(' objc-type-qualifiers[opt] type-name ')'
761 /// '(' objc-type-qualifiers[opt] ')'
763 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, bool IsParameter) {
764 assert(Tok.is(tok::l_paren) && "expected (");
766 SourceLocation LParenLoc = ConsumeParen();
767 SourceLocation TypeStartLoc = Tok.getLocation();
769 // Parse type qualifiers, in, inout, etc.
770 ParseObjCTypeQualifierList(DS, IsParameter);
772 ParsedType Ty;
773 if (isTypeSpecifierQualifier()) {
774 TypeResult TypeSpec = ParseTypeName();
775 if (!TypeSpec.isInvalid())
776 Ty = TypeSpec.get();
779 if (Tok.is(tok::r_paren))
780 ConsumeParen();
781 else if (Tok.getLocation() == TypeStartLoc) {
782 // If we didn't eat any tokens, then this isn't a type.
783 Diag(Tok, diag::err_expected_type);
784 SkipUntil(tok::r_paren);
785 } else {
786 // Otherwise, we found *something*, but didn't get a ')' in the right
787 // place. Emit an error then return what we have as the type.
788 MatchRHSPunctuation(tok::r_paren, LParenLoc);
790 return Ty;
793 /// objc-method-decl:
794 /// objc-selector
795 /// objc-keyword-selector objc-parmlist[opt]
796 /// objc-type-name objc-selector
797 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
799 /// objc-keyword-selector:
800 /// objc-keyword-decl
801 /// objc-keyword-selector objc-keyword-decl
803 /// objc-keyword-decl:
804 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
805 /// objc-selector ':' objc-keyword-attributes[opt] identifier
806 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
807 /// ':' objc-keyword-attributes[opt] identifier
809 /// objc-parmlist:
810 /// objc-parms objc-ellipsis[opt]
812 /// objc-parms:
813 /// objc-parms , parameter-declaration
815 /// objc-ellipsis:
816 /// , ...
818 /// objc-keyword-attributes: [OBJC2]
819 /// __attribute__((unused))
821 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
822 tok::TokenKind mType,
823 Decl *IDecl,
824 tok::ObjCKeywordKind MethodImplKind) {
825 ParsingDeclRAIIObject PD(*this);
827 if (Tok.is(tok::code_completion)) {
828 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
829 /*ReturnType=*/ ParsedType(), IDecl);
830 ConsumeCodeCompletionToken();
833 // Parse the return type if present.
834 ParsedType ReturnType;
835 ObjCDeclSpec DSRet;
836 if (Tok.is(tok::l_paren))
837 ReturnType = ParseObjCTypeName(DSRet, false);
839 // If attributes exist before the method, parse them.
840 ParsedAttributes attrs;
841 if (getLang().ObjC2)
842 MaybeParseGNUAttributes(attrs);
844 if (Tok.is(tok::code_completion)) {
845 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
846 ReturnType, IDecl);
847 ConsumeCodeCompletionToken();
850 // Now parse the selector.
851 SourceLocation selLoc;
852 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
854 // An unnamed colon is valid.
855 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
856 Diag(Tok, diag::err_expected_selector_for_method)
857 << SourceRange(mLoc, Tok.getLocation());
858 // Skip until we get a ; or {}.
859 SkipUntil(tok::r_brace);
860 return 0;
863 llvm::SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
864 if (Tok.isNot(tok::colon)) {
865 // If attributes exist after the method, parse them.
866 if (getLang().ObjC2)
867 MaybeParseGNUAttributes(attrs);
869 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
870 Decl *Result
871 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
872 mType, IDecl, DSRet, ReturnType, Sel,
874 CParamInfo.data(), CParamInfo.size(),
875 attrs.getList(), MethodImplKind);
876 PD.complete(Result);
877 return Result;
880 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
881 llvm::SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
882 ParseScope PrototypeScope(this,
883 Scope::FunctionPrototypeScope|Scope::DeclScope);
885 while (1) {
886 Sema::ObjCArgInfo ArgInfo;
888 // Each iteration parses a single keyword argument.
889 if (Tok.isNot(tok::colon)) {
890 Diag(Tok, diag::err_expected_colon);
891 break;
893 ConsumeToken(); // Eat the ':'.
895 ArgInfo.Type = ParsedType();
896 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
897 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, true);
899 // If attributes exist before the argument name, parse them.
900 ArgInfo.ArgAttrs = 0;
901 if (getLang().ObjC2) {
902 ParsedAttributes attrs;
903 MaybeParseGNUAttributes(attrs);
904 ArgInfo.ArgAttrs = attrs.getList();
907 // Code completion for the next piece of the selector.
908 if (Tok.is(tok::code_completion)) {
909 ConsumeCodeCompletionToken();
910 KeyIdents.push_back(SelIdent);
911 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
912 mType == tok::minus,
913 /*AtParameterName=*/true,
914 ReturnType,
915 KeyIdents.data(),
916 KeyIdents.size());
917 KeyIdents.pop_back();
918 break;
921 if (Tok.isNot(tok::identifier)) {
922 Diag(Tok, diag::err_expected_ident); // missing argument name.
923 break;
926 ArgInfo.Name = Tok.getIdentifierInfo();
927 ArgInfo.NameLoc = Tok.getLocation();
928 ConsumeToken(); // Eat the identifier.
930 ArgInfos.push_back(ArgInfo);
931 KeyIdents.push_back(SelIdent);
933 // Code completion for the next piece of the selector.
934 if (Tok.is(tok::code_completion)) {
935 ConsumeCodeCompletionToken();
936 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
937 mType == tok::minus,
938 /*AtParameterName=*/false,
939 ReturnType,
940 KeyIdents.data(),
941 KeyIdents.size());
942 break;
945 // Check for another keyword selector.
946 SourceLocation Loc;
947 SelIdent = ParseObjCSelectorPiece(Loc);
948 if (!SelIdent && Tok.isNot(tok::colon))
949 break;
950 // We have a selector or a colon, continue parsing.
953 bool isVariadic = false;
955 // Parse the (optional) parameter list.
956 while (Tok.is(tok::comma)) {
957 ConsumeToken();
958 if (Tok.is(tok::ellipsis)) {
959 isVariadic = true;
960 ConsumeToken();
961 break;
963 DeclSpec DS;
964 ParseDeclarationSpecifiers(DS);
965 // Parse the declarator.
966 Declarator ParmDecl(DS, Declarator::PrototypeContext);
967 ParseDeclarator(ParmDecl);
968 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
969 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
970 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
971 ParmDecl.getIdentifierLoc(),
972 Param,
973 0));
977 // FIXME: Add support for optional parameter list...
978 // If attributes exist after the method, parse them.
979 if (getLang().ObjC2)
980 MaybeParseGNUAttributes(attrs);
982 if (KeyIdents.size() == 0) {
983 // Leave prototype scope.
984 PrototypeScope.Exit();
985 return 0;
988 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
989 &KeyIdents[0]);
990 Decl *Result
991 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
992 mType, IDecl, DSRet, ReturnType, Sel,
993 &ArgInfos[0],
994 CParamInfo.data(), CParamInfo.size(),
995 attrs.getList(),
996 MethodImplKind, isVariadic);
997 // Leave prototype scope.
998 PrototypeScope.Exit();
1000 PD.complete(Result);
1001 return Result;
1004 /// objc-protocol-refs:
1005 /// '<' identifier-list '>'
1007 bool Parser::
1008 ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl *> &Protocols,
1009 llvm::SmallVectorImpl<SourceLocation> &ProtocolLocs,
1010 bool WarnOnDeclarations,
1011 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1012 assert(Tok.is(tok::less) && "expected <");
1014 LAngleLoc = ConsumeToken(); // the "<"
1016 llvm::SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1018 while (1) {
1019 if (Tok.is(tok::code_completion)) {
1020 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1021 ProtocolIdents.size());
1022 ConsumeCodeCompletionToken();
1025 if (Tok.isNot(tok::identifier)) {
1026 Diag(Tok, diag::err_expected_ident);
1027 SkipUntil(tok::greater);
1028 return true;
1030 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1031 Tok.getLocation()));
1032 ProtocolLocs.push_back(Tok.getLocation());
1033 ConsumeToken();
1035 if (Tok.isNot(tok::comma))
1036 break;
1037 ConsumeToken();
1040 // Consume the '>'.
1041 if (Tok.isNot(tok::greater)) {
1042 Diag(Tok, diag::err_expected_greater);
1043 return true;
1046 EndLoc = ConsumeAnyToken();
1048 // Convert the list of protocols identifiers into a list of protocol decls.
1049 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1050 &ProtocolIdents[0], ProtocolIdents.size(),
1051 Protocols);
1052 return false;
1055 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1056 /// in a decl-specifier-seq, starting at the '<'.
1057 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1058 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1059 assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1060 SourceLocation LAngleLoc, EndProtoLoc;
1061 llvm::SmallVector<Decl *, 8> ProtocolDecl;
1062 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1063 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1064 LAngleLoc, EndProtoLoc);
1065 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1066 ProtocolLocs.data(), LAngleLoc);
1067 if (EndProtoLoc.isValid())
1068 DS.SetRangeEnd(EndProtoLoc);
1069 return Result;
1073 /// objc-class-instance-variables:
1074 /// '{' objc-instance-variable-decl-list[opt] '}'
1076 /// objc-instance-variable-decl-list:
1077 /// objc-visibility-spec
1078 /// objc-instance-variable-decl ';'
1079 /// ';'
1080 /// objc-instance-variable-decl-list objc-visibility-spec
1081 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1082 /// objc-instance-variable-decl-list ';'
1084 /// objc-visibility-spec:
1085 /// @private
1086 /// @protected
1087 /// @public
1088 /// @package [OBJC2]
1090 /// objc-instance-variable-decl:
1091 /// struct-declaration
1093 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1094 tok::ObjCKeywordKind visibility,
1095 SourceLocation atLoc) {
1096 assert(Tok.is(tok::l_brace) && "expected {");
1097 llvm::SmallVector<Decl *, 32> AllIvarDecls;
1099 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1101 SourceLocation LBraceLoc = ConsumeBrace(); // the "{"
1103 // While we still have something to read, read the instance variables.
1104 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1105 // Each iteration of this loop reads one objc-instance-variable-decl.
1107 // Check for extraneous top-level semicolon.
1108 if (Tok.is(tok::semi)) {
1109 Diag(Tok, diag::ext_extra_ivar_semi)
1110 << FixItHint::CreateRemoval(Tok.getLocation());
1111 ConsumeToken();
1112 continue;
1115 // Set the default visibility to private.
1116 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1117 ConsumeToken(); // eat the @ sign
1119 if (Tok.is(tok::code_completion)) {
1120 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1121 ConsumeCodeCompletionToken();
1124 switch (Tok.getObjCKeywordID()) {
1125 case tok::objc_private:
1126 case tok::objc_public:
1127 case tok::objc_protected:
1128 case tok::objc_package:
1129 visibility = Tok.getObjCKeywordID();
1130 ConsumeToken();
1131 continue;
1132 default:
1133 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1134 continue;
1138 if (Tok.is(tok::code_completion)) {
1139 Actions.CodeCompleteOrdinaryName(getCurScope(),
1140 Sema::PCC_ObjCInstanceVariableList);
1141 ConsumeCodeCompletionToken();
1144 struct ObjCIvarCallback : FieldCallback {
1145 Parser &P;
1146 Decl *IDecl;
1147 tok::ObjCKeywordKind visibility;
1148 llvm::SmallVectorImpl<Decl *> &AllIvarDecls;
1150 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1151 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) :
1152 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1155 Decl *invoke(FieldDeclarator &FD) {
1156 // Install the declarator into the interface decl.
1157 Decl *Field
1158 = P.Actions.ActOnIvar(P.getCurScope(),
1159 FD.D.getDeclSpec().getSourceRange().getBegin(),
1160 IDecl, FD.D, FD.BitfieldSize, visibility);
1161 if (Field)
1162 AllIvarDecls.push_back(Field);
1163 return Field;
1165 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1167 // Parse all the comma separated declarators.
1168 DeclSpec DS;
1169 ParseStructDeclaration(DS, Callback);
1171 if (Tok.is(tok::semi)) {
1172 ConsumeToken();
1173 } else {
1174 Diag(Tok, diag::err_expected_semi_decl_list);
1175 // Skip to end of block or statement
1176 SkipUntil(tok::r_brace, true, true);
1179 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1180 Actions.ActOnLastBitfield(RBraceLoc, interfaceDecl, AllIvarDecls);
1181 // Call ActOnFields() even if we don't have any decls. This is useful
1182 // for code rewriting tools that need to be aware of the empty list.
1183 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1184 AllIvarDecls.data(), AllIvarDecls.size(),
1185 LBraceLoc, RBraceLoc, 0);
1186 return;
1189 /// objc-protocol-declaration:
1190 /// objc-protocol-definition
1191 /// objc-protocol-forward-reference
1193 /// objc-protocol-definition:
1194 /// @protocol identifier
1195 /// objc-protocol-refs[opt]
1196 /// objc-interface-decl-list
1197 /// @end
1199 /// objc-protocol-forward-reference:
1200 /// @protocol identifier-list ';'
1202 /// "@protocol identifier ;" should be resolved as "@protocol
1203 /// identifier-list ;": objc-interface-decl-list may not start with a
1204 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1205 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1206 ParsedAttributes &attrs) {
1207 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1208 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1209 ConsumeToken(); // the "protocol" identifier
1211 if (Tok.is(tok::code_completion)) {
1212 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1213 ConsumeCodeCompletionToken();
1216 if (Tok.isNot(tok::identifier)) {
1217 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1218 return 0;
1220 // Save the protocol name, then consume it.
1221 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1222 SourceLocation nameLoc = ConsumeToken();
1224 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1225 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1226 ConsumeToken();
1227 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1228 attrs.getList());
1231 if (Tok.is(tok::comma)) { // list of forward declarations.
1232 llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1233 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1235 // Parse the list of forward declarations.
1236 while (1) {
1237 ConsumeToken(); // the ','
1238 if (Tok.isNot(tok::identifier)) {
1239 Diag(Tok, diag::err_expected_ident);
1240 SkipUntil(tok::semi);
1241 return 0;
1243 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1244 Tok.getLocation()));
1245 ConsumeToken(); // the identifier
1247 if (Tok.isNot(tok::comma))
1248 break;
1250 // Consume the ';'.
1251 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1252 return 0;
1254 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1255 &ProtocolRefs[0],
1256 ProtocolRefs.size(),
1257 attrs.getList());
1260 // Last, and definitely not least, parse a protocol declaration.
1261 SourceLocation LAngleLoc, EndProtoLoc;
1263 llvm::SmallVector<Decl *, 8> ProtocolRefs;
1264 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1265 if (Tok.is(tok::less) &&
1266 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1267 LAngleLoc, EndProtoLoc))
1268 return 0;
1270 Decl *ProtoType =
1271 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1272 ProtocolRefs.data(),
1273 ProtocolRefs.size(),
1274 ProtocolLocs.data(),
1275 EndProtoLoc, attrs.getList());
1276 ParseObjCInterfaceDeclList(ProtoType, tok::objc_protocol);
1277 return ProtoType;
1280 /// objc-implementation:
1281 /// objc-class-implementation-prologue
1282 /// objc-category-implementation-prologue
1284 /// objc-class-implementation-prologue:
1285 /// @implementation identifier objc-superclass[opt]
1286 /// objc-class-instance-variables[opt]
1288 /// objc-category-implementation-prologue:
1289 /// @implementation identifier ( identifier )
1290 Decl *Parser::ParseObjCAtImplementationDeclaration(
1291 SourceLocation atLoc) {
1292 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1293 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1294 ConsumeToken(); // the "implementation" identifier
1296 // Code completion after '@implementation'.
1297 if (Tok.is(tok::code_completion)) {
1298 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1299 ConsumeCodeCompletionToken();
1302 if (Tok.isNot(tok::identifier)) {
1303 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1304 return 0;
1306 // We have a class or category name - consume it.
1307 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1308 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1310 if (Tok.is(tok::l_paren)) {
1311 // we have a category implementation.
1312 ConsumeParen();
1313 SourceLocation categoryLoc, rparenLoc;
1314 IdentifierInfo *categoryId = 0;
1316 if (Tok.is(tok::code_completion)) {
1317 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1318 ConsumeCodeCompletionToken();
1321 if (Tok.is(tok::identifier)) {
1322 categoryId = Tok.getIdentifierInfo();
1323 categoryLoc = ConsumeToken();
1324 } else {
1325 Diag(Tok, diag::err_expected_ident); // missing category name.
1326 return 0;
1328 if (Tok.isNot(tok::r_paren)) {
1329 Diag(Tok, diag::err_expected_rparen);
1330 SkipUntil(tok::r_paren, false); // don't stop at ';'
1331 return 0;
1333 rparenLoc = ConsumeParen();
1334 Decl *ImplCatType = Actions.ActOnStartCategoryImplementation(
1335 atLoc, nameId, nameLoc, categoryId,
1336 categoryLoc);
1337 ObjCImpDecl = ImplCatType;
1338 PendingObjCImpDecl.push_back(ObjCImpDecl);
1339 return 0;
1341 // We have a class implementation
1342 SourceLocation superClassLoc;
1343 IdentifierInfo *superClassId = 0;
1344 if (Tok.is(tok::colon)) {
1345 // We have a super class
1346 ConsumeToken();
1347 if (Tok.isNot(tok::identifier)) {
1348 Diag(Tok, diag::err_expected_ident); // missing super class name.
1349 return 0;
1351 superClassId = Tok.getIdentifierInfo();
1352 superClassLoc = ConsumeToken(); // Consume super class name
1354 Decl *ImplClsType = Actions.ActOnStartClassImplementation(
1355 atLoc, nameId, nameLoc,
1356 superClassId, superClassLoc);
1358 if (Tok.is(tok::l_brace)) // we have ivars
1359 ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/,
1360 tok::objc_private, atLoc);
1361 ObjCImpDecl = ImplClsType;
1362 PendingObjCImpDecl.push_back(ObjCImpDecl);
1364 return 0;
1367 Decl *Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1368 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1369 "ParseObjCAtEndDeclaration(): Expected @end");
1370 Decl *Result = ObjCImpDecl;
1371 ConsumeToken(); // the "end" identifier
1372 if (ObjCImpDecl) {
1373 Actions.ActOnAtEnd(getCurScope(), atEnd, ObjCImpDecl);
1374 ObjCImpDecl = 0;
1375 PendingObjCImpDecl.pop_back();
1377 else {
1378 // missing @implementation
1379 Diag(atEnd.getBegin(), diag::warn_expected_implementation);
1381 return Result;
1384 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
1385 Actions.DiagnoseUseOfUnimplementedSelectors();
1386 if (PendingObjCImpDecl.empty())
1387 return Actions.ConvertDeclToDeclGroup(0);
1388 Decl *ImpDecl = PendingObjCImpDecl.pop_back_val();
1389 Actions.ActOnAtEnd(getCurScope(), SourceRange(), ImpDecl);
1390 return Actions.ConvertDeclToDeclGroup(ImpDecl);
1393 /// compatibility-alias-decl:
1394 /// @compatibility_alias alias-name class-name ';'
1396 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1397 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1398 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1399 ConsumeToken(); // consume compatibility_alias
1400 if (Tok.isNot(tok::identifier)) {
1401 Diag(Tok, diag::err_expected_ident);
1402 return 0;
1404 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1405 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1406 if (Tok.isNot(tok::identifier)) {
1407 Diag(Tok, diag::err_expected_ident);
1408 return 0;
1410 IdentifierInfo *classId = Tok.getIdentifierInfo();
1411 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1412 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1413 "@compatibility_alias");
1414 return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
1415 classId, classLoc);
1418 /// property-synthesis:
1419 /// @synthesize property-ivar-list ';'
1421 /// property-ivar-list:
1422 /// property-ivar
1423 /// property-ivar-list ',' property-ivar
1425 /// property-ivar:
1426 /// identifier
1427 /// identifier '=' identifier
1429 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1430 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1431 "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1432 ConsumeToken(); // consume synthesize
1434 while (true) {
1435 if (Tok.is(tok::code_completion)) {
1436 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1437 ConsumeCodeCompletionToken();
1440 if (Tok.isNot(tok::identifier)) {
1441 Diag(Tok, diag::err_synthesized_property_name);
1442 SkipUntil(tok::semi);
1443 return 0;
1446 IdentifierInfo *propertyIvar = 0;
1447 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1448 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1449 SourceLocation propertyIvarLoc;
1450 if (Tok.is(tok::equal)) {
1451 // property '=' ivar-name
1452 ConsumeToken(); // consume '='
1454 if (Tok.is(tok::code_completion)) {
1455 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId,
1456 ObjCImpDecl);
1457 ConsumeCodeCompletionToken();
1460 if (Tok.isNot(tok::identifier)) {
1461 Diag(Tok, diag::err_expected_ident);
1462 break;
1464 propertyIvar = Tok.getIdentifierInfo();
1465 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1467 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, ObjCImpDecl,
1468 propertyId, propertyIvar, propertyIvarLoc);
1469 if (Tok.isNot(tok::comma))
1470 break;
1471 ConsumeToken(); // consume ','
1473 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1474 return 0;
1477 /// property-dynamic:
1478 /// @dynamic property-list
1480 /// property-list:
1481 /// identifier
1482 /// property-list ',' identifier
1484 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1485 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1486 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1487 ConsumeToken(); // consume dynamic
1488 while (true) {
1489 if (Tok.is(tok::code_completion)) {
1490 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1491 ConsumeCodeCompletionToken();
1494 if (Tok.isNot(tok::identifier)) {
1495 Diag(Tok, diag::err_expected_ident);
1496 SkipUntil(tok::semi);
1497 return 0;
1500 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1501 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1502 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, ObjCImpDecl,
1503 propertyId, 0, SourceLocation());
1505 if (Tok.isNot(tok::comma))
1506 break;
1507 ConsumeToken(); // consume ','
1509 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1510 return 0;
1513 /// objc-throw-statement:
1514 /// throw expression[opt];
1516 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1517 ExprResult Res;
1518 ConsumeToken(); // consume throw
1519 if (Tok.isNot(tok::semi)) {
1520 Res = ParseExpression();
1521 if (Res.isInvalid()) {
1522 SkipUntil(tok::semi);
1523 return StmtError();
1526 // consume ';'
1527 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1528 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1531 /// objc-synchronized-statement:
1532 /// @synchronized '(' expression ')' compound-statement
1534 StmtResult
1535 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1536 ConsumeToken(); // consume synchronized
1537 if (Tok.isNot(tok::l_paren)) {
1538 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1539 return StmtError();
1541 ConsumeParen(); // '('
1542 ExprResult Res(ParseExpression());
1543 if (Res.isInvalid()) {
1544 SkipUntil(tok::semi);
1545 return StmtError();
1547 if (Tok.isNot(tok::r_paren)) {
1548 Diag(Tok, diag::err_expected_lbrace);
1549 return StmtError();
1551 ConsumeParen(); // ')'
1552 if (Tok.isNot(tok::l_brace)) {
1553 Diag(Tok, diag::err_expected_lbrace);
1554 return StmtError();
1556 // Enter a scope to hold everything within the compound stmt. Compound
1557 // statements can always hold declarations.
1558 ParseScope BodyScope(this, Scope::DeclScope);
1560 StmtResult SynchBody(ParseCompoundStatementBody());
1562 BodyScope.Exit();
1563 if (SynchBody.isInvalid())
1564 SynchBody = Actions.ActOnNullStmt(Tok.getLocation());
1565 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, Res.take(), SynchBody.take());
1568 /// objc-try-catch-statement:
1569 /// @try compound-statement objc-catch-list[opt]
1570 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1572 /// objc-catch-list:
1573 /// @catch ( parameter-declaration ) compound-statement
1574 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1575 /// catch-parameter-declaration:
1576 /// parameter-declaration
1577 /// '...' [OBJC2]
1579 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1580 bool catch_or_finally_seen = false;
1582 ConsumeToken(); // consume try
1583 if (Tok.isNot(tok::l_brace)) {
1584 Diag(Tok, diag::err_expected_lbrace);
1585 return StmtError();
1587 StmtVector CatchStmts(Actions);
1588 StmtResult FinallyStmt;
1589 ParseScope TryScope(this, Scope::DeclScope);
1590 StmtResult TryBody(ParseCompoundStatementBody());
1591 TryScope.Exit();
1592 if (TryBody.isInvalid())
1593 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1595 while (Tok.is(tok::at)) {
1596 // At this point, we need to lookahead to determine if this @ is the start
1597 // of an @catch or @finally. We don't want to consume the @ token if this
1598 // is an @try or @encode or something else.
1599 Token AfterAt = GetLookAheadToken(1);
1600 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1601 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1602 break;
1604 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1605 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1606 Decl *FirstPart = 0;
1607 ConsumeToken(); // consume catch
1608 if (Tok.is(tok::l_paren)) {
1609 ConsumeParen();
1610 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1611 if (Tok.isNot(tok::ellipsis)) {
1612 DeclSpec DS;
1613 ParseDeclarationSpecifiers(DS);
1614 // For some odd reason, the name of the exception variable is
1615 // optional. As a result, we need to use "PrototypeContext", because
1616 // we must accept either 'declarator' or 'abstract-declarator' here.
1617 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1618 ParseDeclarator(ParmDecl);
1620 // Inform the actions module about the declarator, so it
1621 // gets added to the current scope.
1622 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1623 } else
1624 ConsumeToken(); // consume '...'
1626 SourceLocation RParenLoc;
1628 if (Tok.is(tok::r_paren))
1629 RParenLoc = ConsumeParen();
1630 else // Skip over garbage, until we get to ')'. Eat the ')'.
1631 SkipUntil(tok::r_paren, true, false);
1633 StmtResult CatchBody(true);
1634 if (Tok.is(tok::l_brace))
1635 CatchBody = ParseCompoundStatementBody();
1636 else
1637 Diag(Tok, diag::err_expected_lbrace);
1638 if (CatchBody.isInvalid())
1639 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1641 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1642 RParenLoc,
1643 FirstPart,
1644 CatchBody.take());
1645 if (!Catch.isInvalid())
1646 CatchStmts.push_back(Catch.release());
1648 } else {
1649 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1650 << "@catch clause";
1651 return StmtError();
1653 catch_or_finally_seen = true;
1654 } else {
1655 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1656 ConsumeToken(); // consume finally
1657 ParseScope FinallyScope(this, Scope::DeclScope);
1659 StmtResult FinallyBody(true);
1660 if (Tok.is(tok::l_brace))
1661 FinallyBody = ParseCompoundStatementBody();
1662 else
1663 Diag(Tok, diag::err_expected_lbrace);
1664 if (FinallyBody.isInvalid())
1665 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1666 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1667 FinallyBody.take());
1668 catch_or_finally_seen = true;
1669 break;
1672 if (!catch_or_finally_seen) {
1673 Diag(atLoc, diag::err_missing_catch_finally);
1674 return StmtError();
1677 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1678 move_arg(CatchStmts),
1679 FinallyStmt.take());
1682 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1684 Decl *Parser::ParseObjCMethodDefinition() {
1685 Decl *MDecl = ParseObjCMethodPrototype(ObjCImpDecl);
1687 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1688 "parsing Objective-C method");
1690 // parse optional ';'
1691 if (Tok.is(tok::semi)) {
1692 if (ObjCImpDecl) {
1693 Diag(Tok, diag::warn_semicolon_before_method_body)
1694 << FixItHint::CreateRemoval(Tok.getLocation());
1696 ConsumeToken();
1699 // We should have an opening brace now.
1700 if (Tok.isNot(tok::l_brace)) {
1701 Diag(Tok, diag::err_expected_method_body);
1703 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1704 SkipUntil(tok::l_brace, true, true);
1706 // If we didn't find the '{', bail out.
1707 if (Tok.isNot(tok::l_brace))
1708 return 0;
1710 SourceLocation BraceLoc = Tok.getLocation();
1712 // Enter a scope for the method body.
1713 ParseScope BodyScope(this,
1714 Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
1716 // Tell the actions module that we have entered a method definition with the
1717 // specified Declarator for the method.
1718 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
1720 if (PP.isCodeCompletionEnabled())
1721 if (trySkippingFunctionBodyForCodeCompletion())
1722 return Actions.ActOnFinishFunctionBody(MDecl, 0);
1724 StmtResult FnBody(ParseCompoundStatementBody());
1726 // If the function body could not be parsed, make a bogus compoundstmt.
1727 if (FnBody.isInvalid())
1728 FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
1729 MultiStmtArg(Actions), false);
1731 // TODO: Pass argument information.
1732 Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
1734 // Leave the function body scope.
1735 BodyScope.Exit();
1737 return MDecl;
1740 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1741 if (Tok.is(tok::code_completion)) {
1742 Actions.CodeCompleteObjCAtStatement(getCurScope());
1743 ConsumeCodeCompletionToken();
1744 return StmtError();
1747 if (Tok.isObjCAtKeyword(tok::objc_try))
1748 return ParseObjCTryStmt(AtLoc);
1750 if (Tok.isObjCAtKeyword(tok::objc_throw))
1751 return ParseObjCThrowStmt(AtLoc);
1753 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1754 return ParseObjCSynchronizedStmt(AtLoc);
1756 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
1757 if (Res.isInvalid()) {
1758 // If the expression is invalid, skip ahead to the next semicolon. Not
1759 // doing this opens us up to the possibility of infinite loops if
1760 // ParseExpression does not consume any tokens.
1761 SkipUntil(tok::semi);
1762 return StmtError();
1765 // Otherwise, eat the semicolon.
1766 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1767 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
1770 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1771 switch (Tok.getKind()) {
1772 case tok::code_completion:
1773 Actions.CodeCompleteObjCAtExpression(getCurScope());
1774 ConsumeCodeCompletionToken();
1775 return ExprError();
1777 case tok::string_literal: // primary-expression: string-literal
1778 case tok::wide_string_literal:
1779 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1780 default:
1781 if (Tok.getIdentifierInfo() == 0)
1782 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1784 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1785 case tok::objc_encode:
1786 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1787 case tok::objc_protocol:
1788 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1789 case tok::objc_selector:
1790 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1791 default:
1792 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1797 /// \brirg Parse the receiver of an Objective-C++ message send.
1799 /// This routine parses the receiver of a message send in
1800 /// Objective-C++ either as a type or as an expression. Note that this
1801 /// routine must not be called to parse a send to 'super', since it
1802 /// has no way to return such a result.
1803 ///
1804 /// \param IsExpr Whether the receiver was parsed as an expression.
1806 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
1807 /// IsExpr is true), the parsed expression. If the receiver was parsed
1808 /// as a type (\c IsExpr is false), the parsed type.
1810 /// \returns True if an error occurred during parsing or semantic
1811 /// analysis, in which case the arguments do not have valid
1812 /// values. Otherwise, returns false for a successful parse.
1814 /// objc-receiver: [C++]
1815 /// 'super' [not parsed here]
1816 /// expression
1817 /// simple-type-specifier
1818 /// typename-specifier
1819 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
1820 InMessageExpressionRAIIObject InMessage(*this, true);
1822 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1823 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
1824 TryAnnotateTypeOrScopeToken();
1826 if (!isCXXSimpleTypeSpecifier()) {
1827 // objc-receiver:
1828 // expression
1829 ExprResult Receiver = ParseExpression();
1830 if (Receiver.isInvalid())
1831 return true;
1833 IsExpr = true;
1834 TypeOrExpr = Receiver.take();
1835 return false;
1838 // objc-receiver:
1839 // typename-specifier
1840 // simple-type-specifier
1841 // expression (that starts with one of the above)
1842 DeclSpec DS;
1843 ParseCXXSimpleTypeSpecifier(DS);
1845 if (Tok.is(tok::l_paren)) {
1846 // If we see an opening parentheses at this point, we are
1847 // actually parsing an expression that starts with a
1848 // function-style cast, e.g.,
1850 // postfix-expression:
1851 // simple-type-specifier ( expression-list [opt] )
1852 // typename-specifier ( expression-list [opt] )
1854 // Parse the remainder of this case, then the (optional)
1855 // postfix-expression suffix, followed by the (optional)
1856 // right-hand side of the binary expression. We have an
1857 // instance method.
1858 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
1859 if (!Receiver.isInvalid())
1860 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
1861 if (!Receiver.isInvalid())
1862 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
1863 if (Receiver.isInvalid())
1864 return true;
1866 IsExpr = true;
1867 TypeOrExpr = Receiver.take();
1868 return false;
1871 // We have a class message. Turn the simple-type-specifier or
1872 // typename-specifier we parsed into a type and parse the
1873 // remainder of the class message.
1874 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1875 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1876 if (Type.isInvalid())
1877 return true;
1879 IsExpr = false;
1880 TypeOrExpr = Type.get().getAsOpaquePtr();
1881 return false;
1884 /// \brief Determine whether the parser is currently referring to a an
1885 /// Objective-C message send, using a simplified heuristic to avoid overhead.
1887 /// This routine will only return true for a subset of valid message-send
1888 /// expressions.
1889 bool Parser::isSimpleObjCMessageExpression() {
1890 assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
1891 "Incorrect start for isSimpleObjCMessageExpression");
1892 return GetLookAheadToken(1).is(tok::identifier) &&
1893 GetLookAheadToken(2).is(tok::identifier);
1896 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
1897 if (!getLang().ObjC1 || !NextToken().is(tok::identifier) ||
1898 InMessageExpression)
1899 return false;
1902 ParsedType Type;
1904 if (Tok.is(tok::annot_typename))
1905 Type = getTypeAnnotation(Tok);
1906 else if (Tok.is(tok::identifier))
1907 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
1908 getCurScope());
1909 else
1910 return false;
1912 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
1913 const Token &AfterNext = GetLookAheadToken(2);
1914 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
1915 if (Tok.is(tok::identifier))
1916 TryAnnotateTypeOrScopeToken();
1918 return Tok.is(tok::annot_typename);
1922 return false;
1925 /// objc-message-expr:
1926 /// '[' objc-receiver objc-message-args ']'
1928 /// objc-receiver: [C]
1929 /// 'super'
1930 /// expression
1931 /// class-name
1932 /// type-name
1934 ExprResult Parser::ParseObjCMessageExpression() {
1935 assert(Tok.is(tok::l_square) && "'[' expected");
1936 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
1938 if (Tok.is(tok::code_completion)) {
1939 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
1940 ConsumeCodeCompletionToken();
1941 SkipUntil(tok::r_square);
1942 return ExprError();
1945 InMessageExpressionRAIIObject InMessage(*this, true);
1947 if (getLang().CPlusPlus) {
1948 // We completely separate the C and C++ cases because C++ requires
1949 // more complicated (read: slower) parsing.
1951 // Handle send to super.
1952 // FIXME: This doesn't benefit from the same typo-correction we
1953 // get in Objective-C.
1954 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
1955 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
1956 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
1957 ParsedType(), 0);
1959 // Parse the receiver, which is either a type or an expression.
1960 bool IsExpr;
1961 void *TypeOrExpr = NULL;
1962 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
1963 SkipUntil(tok::r_square);
1964 return ExprError();
1967 if (IsExpr)
1968 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1969 ParsedType(),
1970 static_cast<Expr*>(TypeOrExpr));
1972 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1973 ParsedType::getFromOpaquePtr(TypeOrExpr),
1977 if (Tok.is(tok::identifier)) {
1978 IdentifierInfo *Name = Tok.getIdentifierInfo();
1979 SourceLocation NameLoc = Tok.getLocation();
1980 ParsedType ReceiverType;
1981 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
1982 Name == Ident_super,
1983 NextToken().is(tok::period),
1984 ReceiverType)) {
1985 case Sema::ObjCSuperMessage:
1986 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
1987 ParsedType(), 0);
1989 case Sema::ObjCClassMessage:
1990 if (!ReceiverType) {
1991 SkipUntil(tok::r_square);
1992 return ExprError();
1995 ConsumeToken(); // the type name
1997 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1998 ReceiverType, 0);
2000 case Sema::ObjCInstanceMessage:
2001 // Fall through to parse an expression.
2002 break;
2006 // Otherwise, an arbitrary expression can be the receiver of a send.
2007 ExprResult Res(ParseExpression());
2008 if (Res.isInvalid()) {
2009 SkipUntil(tok::r_square);
2010 return move(Res);
2013 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2014 ParsedType(), Res.take());
2017 /// \brief Parse the remainder of an Objective-C message following the
2018 /// '[' objc-receiver.
2020 /// This routine handles sends to super, class messages (sent to a
2021 /// class name), and instance messages (sent to an object), and the
2022 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2023 /// ReceiverExpr, respectively. Only one of these parameters may have
2024 /// a valid value.
2026 /// \param LBracLoc The location of the opening '['.
2028 /// \param SuperLoc If this is a send to 'super', the location of the
2029 /// 'super' keyword that indicates a send to the superclass.
2031 /// \param ReceiverType If this is a class message, the type of the
2032 /// class we are sending a message to.
2034 /// \param ReceiverExpr If this is an instance message, the expression
2035 /// used to compute the receiver object.
2037 /// objc-message-args:
2038 /// objc-selector
2039 /// objc-keywordarg-list
2041 /// objc-keywordarg-list:
2042 /// objc-keywordarg
2043 /// objc-keywordarg-list objc-keywordarg
2045 /// objc-keywordarg:
2046 /// selector-name[opt] ':' objc-keywordexpr
2048 /// objc-keywordexpr:
2049 /// nonempty-expr-list
2051 /// nonempty-expr-list:
2052 /// assignment-expression
2053 /// nonempty-expr-list , assignment-expression
2055 ExprResult
2056 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2057 SourceLocation SuperLoc,
2058 ParsedType ReceiverType,
2059 ExprArg ReceiverExpr) {
2060 InMessageExpressionRAIIObject InMessage(*this, true);
2062 if (Tok.is(tok::code_completion)) {
2063 if (SuperLoc.isValid())
2064 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2065 false);
2066 else if (ReceiverType)
2067 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2068 false);
2069 else
2070 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2071 0, 0, false);
2072 ConsumeCodeCompletionToken();
2075 // Parse objc-selector
2076 SourceLocation Loc;
2077 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2079 SourceLocation SelectorLoc = Loc;
2081 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2082 ExprVector KeyExprs(Actions);
2084 if (Tok.is(tok::colon)) {
2085 while (1) {
2086 // Each iteration parses a single keyword argument.
2087 KeyIdents.push_back(selIdent);
2089 if (Tok.isNot(tok::colon)) {
2090 Diag(Tok, diag::err_expected_colon);
2091 // We must manually skip to a ']', otherwise the expression skipper will
2092 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2093 // the enclosing expression.
2094 SkipUntil(tok::r_square);
2095 return ExprError();
2098 ConsumeToken(); // Eat the ':'.
2099 /// Parse the expression after ':'
2101 if (Tok.is(tok::code_completion)) {
2102 if (SuperLoc.isValid())
2103 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2104 KeyIdents.data(),
2105 KeyIdents.size(),
2106 /*AtArgumentEpression=*/true);
2107 else if (ReceiverType)
2108 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2109 KeyIdents.data(),
2110 KeyIdents.size(),
2111 /*AtArgumentEpression=*/true);
2112 else
2113 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2114 KeyIdents.data(),
2115 KeyIdents.size(),
2116 /*AtArgumentEpression=*/true);
2118 ConsumeCodeCompletionToken();
2119 SkipUntil(tok::r_square);
2120 return ExprError();
2123 ExprResult Res(ParseAssignmentExpression());
2124 if (Res.isInvalid()) {
2125 // We must manually skip to a ']', otherwise the expression skipper will
2126 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2127 // the enclosing expression.
2128 SkipUntil(tok::r_square);
2129 return move(Res);
2132 // We have a valid expression.
2133 KeyExprs.push_back(Res.release());
2135 // Code completion after each argument.
2136 if (Tok.is(tok::code_completion)) {
2137 if (SuperLoc.isValid())
2138 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2139 KeyIdents.data(),
2140 KeyIdents.size(),
2141 /*AtArgumentEpression=*/false);
2142 else if (ReceiverType)
2143 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2144 KeyIdents.data(),
2145 KeyIdents.size(),
2146 /*AtArgumentEpression=*/false);
2147 else
2148 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2149 KeyIdents.data(),
2150 KeyIdents.size(),
2151 /*AtArgumentEpression=*/false);
2152 ConsumeCodeCompletionToken();
2153 SkipUntil(tok::r_square);
2154 return ExprError();
2157 // Check for another keyword selector.
2158 selIdent = ParseObjCSelectorPiece(Loc);
2159 if (!selIdent && Tok.isNot(tok::colon))
2160 break;
2161 // We have a selector or a colon, continue parsing.
2163 // Parse the, optional, argument list, comma separated.
2164 while (Tok.is(tok::comma)) {
2165 ConsumeToken(); // Eat the ','.
2166 /// Parse the expression after ','
2167 ExprResult Res(ParseAssignmentExpression());
2168 if (Res.isInvalid()) {
2169 // We must manually skip to a ']', otherwise the expression skipper will
2170 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2171 // the enclosing expression.
2172 SkipUntil(tok::r_square);
2173 return move(Res);
2176 // We have a valid expression.
2177 KeyExprs.push_back(Res.release());
2179 } else if (!selIdent) {
2180 Diag(Tok, diag::err_expected_ident); // missing selector name.
2182 // We must manually skip to a ']', otherwise the expression skipper will
2183 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2184 // the enclosing expression.
2185 SkipUntil(tok::r_square);
2186 return ExprError();
2189 if (Tok.isNot(tok::r_square)) {
2190 if (Tok.is(tok::identifier))
2191 Diag(Tok, diag::err_expected_colon);
2192 else
2193 Diag(Tok, diag::err_expected_rsquare);
2194 // We must manually skip to a ']', otherwise the expression skipper will
2195 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2196 // the enclosing expression.
2197 SkipUntil(tok::r_square);
2198 return ExprError();
2201 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2203 unsigned nKeys = KeyIdents.size();
2204 if (nKeys == 0)
2205 KeyIdents.push_back(selIdent);
2206 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2208 if (SuperLoc.isValid())
2209 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2210 LBracLoc, SelectorLoc, RBracLoc,
2211 MultiExprArg(Actions,
2212 KeyExprs.take(),
2213 KeyExprs.size()));
2214 else if (ReceiverType)
2215 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2216 LBracLoc, SelectorLoc, RBracLoc,
2217 MultiExprArg(Actions,
2218 KeyExprs.take(),
2219 KeyExprs.size()));
2220 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2221 LBracLoc, SelectorLoc, RBracLoc,
2222 MultiExprArg(Actions,
2223 KeyExprs.take(),
2224 KeyExprs.size()));
2227 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2228 ExprResult Res(ParseStringLiteralExpression());
2229 if (Res.isInvalid()) return move(Res);
2231 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2232 // expressions. At this point, we know that the only valid thing that starts
2233 // with '@' is an @"".
2234 llvm::SmallVector<SourceLocation, 4> AtLocs;
2235 ExprVector AtStrings(Actions);
2236 AtLocs.push_back(AtLoc);
2237 AtStrings.push_back(Res.release());
2239 while (Tok.is(tok::at)) {
2240 AtLocs.push_back(ConsumeToken()); // eat the @.
2242 // Invalid unless there is a string literal.
2243 if (!isTokenStringLiteral())
2244 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2246 ExprResult Lit(ParseStringLiteralExpression());
2247 if (Lit.isInvalid())
2248 return move(Lit);
2250 AtStrings.push_back(Lit.release());
2253 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2254 AtStrings.size()));
2257 /// objc-encode-expression:
2258 /// @encode ( type-name )
2259 ExprResult
2260 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2261 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2263 SourceLocation EncLoc = ConsumeToken();
2265 if (Tok.isNot(tok::l_paren))
2266 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2268 SourceLocation LParenLoc = ConsumeParen();
2270 TypeResult Ty = ParseTypeName();
2272 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2274 if (Ty.isInvalid())
2275 return ExprError();
2277 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc,
2278 Ty.get(), RParenLoc));
2281 /// objc-protocol-expression
2282 /// @protocol ( protocol-name )
2283 ExprResult
2284 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2285 SourceLocation ProtoLoc = ConsumeToken();
2287 if (Tok.isNot(tok::l_paren))
2288 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2290 SourceLocation LParenLoc = ConsumeParen();
2292 if (Tok.isNot(tok::identifier))
2293 return ExprError(Diag(Tok, diag::err_expected_ident));
2295 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2296 ConsumeToken();
2298 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2300 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2301 LParenLoc, RParenLoc));
2304 /// objc-selector-expression
2305 /// @selector '(' objc-keyword-selector ')'
2306 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2307 SourceLocation SelectorLoc = ConsumeToken();
2309 if (Tok.isNot(tok::l_paren))
2310 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2312 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2313 SourceLocation LParenLoc = ConsumeParen();
2314 SourceLocation sLoc;
2316 if (Tok.is(tok::code_completion)) {
2317 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2318 KeyIdents.size());
2319 ConsumeCodeCompletionToken();
2320 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2321 return ExprError();
2324 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2325 if (!SelIdent && // missing selector name.
2326 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2327 return ExprError(Diag(Tok, diag::err_expected_ident));
2329 KeyIdents.push_back(SelIdent);
2330 unsigned nColons = 0;
2331 if (Tok.isNot(tok::r_paren)) {
2332 while (1) {
2333 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2334 ++nColons;
2335 KeyIdents.push_back(0);
2336 } else if (Tok.isNot(tok::colon))
2337 return ExprError(Diag(Tok, diag::err_expected_colon));
2339 ++nColons;
2340 ConsumeToken(); // Eat the ':'.
2341 if (Tok.is(tok::r_paren))
2342 break;
2344 if (Tok.is(tok::code_completion)) {
2345 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2346 KeyIdents.size());
2347 ConsumeCodeCompletionToken();
2348 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2349 return ExprError();
2352 // Check for another keyword selector.
2353 SourceLocation Loc;
2354 SelIdent = ParseObjCSelectorPiece(Loc);
2355 KeyIdents.push_back(SelIdent);
2356 if (!SelIdent && Tok.isNot(tok::colon))
2357 break;
2360 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2361 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2362 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2363 LParenLoc, RParenLoc));