Amazing that there are still issues with the fields of anonymous struct/unions..
[clang.git] / lib / Parse / ParseObjc.cpp
blobaf53d7d592d5cf0b1c2dcae412f74da999265f94
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);
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(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;
883 while (1) {
884 Sema::ObjCArgInfo ArgInfo;
886 // Each iteration parses a single keyword argument.
887 if (Tok.isNot(tok::colon)) {
888 Diag(Tok, diag::err_expected_colon);
889 break;
891 ConsumeToken(); // Eat the ':'.
893 ArgInfo.Type = ParsedType();
894 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
895 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, true);
897 // If attributes exist before the argument name, parse them.
898 ArgInfo.ArgAttrs = 0;
899 if (getLang().ObjC2) {
900 ParsedAttributes attrs;
901 MaybeParseGNUAttributes(attrs);
902 ArgInfo.ArgAttrs = attrs.getList();
905 // Code completion for the next piece of the selector.
906 if (Tok.is(tok::code_completion)) {
907 ConsumeCodeCompletionToken();
908 KeyIdents.push_back(SelIdent);
909 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
910 mType == tok::minus,
911 /*AtParameterName=*/true,
912 ReturnType,
913 KeyIdents.data(),
914 KeyIdents.size());
915 KeyIdents.pop_back();
916 break;
919 if (Tok.isNot(tok::identifier)) {
920 Diag(Tok, diag::err_expected_ident); // missing argument name.
921 break;
924 ArgInfo.Name = Tok.getIdentifierInfo();
925 ArgInfo.NameLoc = Tok.getLocation();
926 ConsumeToken(); // Eat the identifier.
928 ArgInfos.push_back(ArgInfo);
929 KeyIdents.push_back(SelIdent);
931 // Code completion for the next piece of the selector.
932 if (Tok.is(tok::code_completion)) {
933 ConsumeCodeCompletionToken();
934 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
935 mType == tok::minus,
936 /*AtParameterName=*/false,
937 ReturnType,
938 KeyIdents.data(),
939 KeyIdents.size());
940 break;
943 // Check for another keyword selector.
944 SourceLocation Loc;
945 SelIdent = ParseObjCSelectorPiece(Loc);
946 if (!SelIdent && Tok.isNot(tok::colon))
947 break;
948 // We have a selector or a colon, continue parsing.
951 bool isVariadic = false;
953 // Parse the (optional) parameter list.
954 while (Tok.is(tok::comma)) {
955 ConsumeToken();
956 if (Tok.is(tok::ellipsis)) {
957 isVariadic = true;
958 ConsumeToken();
959 break;
961 DeclSpec DS;
962 ParseDeclarationSpecifiers(DS);
963 // Parse the declarator.
964 Declarator ParmDecl(DS, Declarator::PrototypeContext);
965 ParseDeclarator(ParmDecl);
966 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
967 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
968 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
969 ParmDecl.getIdentifierLoc(),
970 Param,
971 0));
975 // FIXME: Add support for optional parameter list...
976 // If attributes exist after the method, parse them.
977 if (getLang().ObjC2)
978 MaybeParseGNUAttributes(attrs);
980 if (KeyIdents.size() == 0)
981 return 0;
982 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
983 &KeyIdents[0]);
984 Decl *Result
985 = Actions.ActOnMethodDeclaration(mLoc, Tok.getLocation(),
986 mType, IDecl, DSRet, ReturnType, Sel,
987 &ArgInfos[0],
988 CParamInfo.data(), CParamInfo.size(),
989 attrs.getList(),
990 MethodImplKind, isVariadic);
991 PD.complete(Result);
992 return Result;
995 /// objc-protocol-refs:
996 /// '<' identifier-list '>'
998 bool Parser::
999 ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl *> &Protocols,
1000 llvm::SmallVectorImpl<SourceLocation> &ProtocolLocs,
1001 bool WarnOnDeclarations,
1002 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1003 assert(Tok.is(tok::less) && "expected <");
1005 LAngleLoc = ConsumeToken(); // the "<"
1007 llvm::SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1009 while (1) {
1010 if (Tok.is(tok::code_completion)) {
1011 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1012 ProtocolIdents.size());
1013 ConsumeCodeCompletionToken();
1016 if (Tok.isNot(tok::identifier)) {
1017 Diag(Tok, diag::err_expected_ident);
1018 SkipUntil(tok::greater);
1019 return true;
1021 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1022 Tok.getLocation()));
1023 ProtocolLocs.push_back(Tok.getLocation());
1024 ConsumeToken();
1026 if (Tok.isNot(tok::comma))
1027 break;
1028 ConsumeToken();
1031 // Consume the '>'.
1032 if (Tok.isNot(tok::greater)) {
1033 Diag(Tok, diag::err_expected_greater);
1034 return true;
1037 EndLoc = ConsumeAnyToken();
1039 // Convert the list of protocols identifiers into a list of protocol decls.
1040 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1041 &ProtocolIdents[0], ProtocolIdents.size(),
1042 Protocols);
1043 return false;
1046 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1047 /// in a decl-specifier-seq, starting at the '<'.
1048 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1049 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1050 assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1051 SourceLocation LAngleLoc, EndProtoLoc;
1052 llvm::SmallVector<Decl *, 8> ProtocolDecl;
1053 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1054 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1055 LAngleLoc, EndProtoLoc);
1056 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1057 ProtocolLocs.data(), LAngleLoc);
1058 if (EndProtoLoc.isValid())
1059 DS.SetRangeEnd(EndProtoLoc);
1060 return Result;
1064 /// objc-class-instance-variables:
1065 /// '{' objc-instance-variable-decl-list[opt] '}'
1067 /// objc-instance-variable-decl-list:
1068 /// objc-visibility-spec
1069 /// objc-instance-variable-decl ';'
1070 /// ';'
1071 /// objc-instance-variable-decl-list objc-visibility-spec
1072 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1073 /// objc-instance-variable-decl-list ';'
1075 /// objc-visibility-spec:
1076 /// @private
1077 /// @protected
1078 /// @public
1079 /// @package [OBJC2]
1081 /// objc-instance-variable-decl:
1082 /// struct-declaration
1084 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1085 tok::ObjCKeywordKind visibility,
1086 SourceLocation atLoc) {
1087 assert(Tok.is(tok::l_brace) && "expected {");
1088 llvm::SmallVector<Decl *, 32> AllIvarDecls;
1090 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1092 SourceLocation LBraceLoc = ConsumeBrace(); // the "{"
1094 // While we still have something to read, read the instance variables.
1095 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1096 // Each iteration of this loop reads one objc-instance-variable-decl.
1098 // Check for extraneous top-level semicolon.
1099 if (Tok.is(tok::semi)) {
1100 Diag(Tok, diag::ext_extra_ivar_semi)
1101 << FixItHint::CreateRemoval(Tok.getLocation());
1102 ConsumeToken();
1103 continue;
1106 // Set the default visibility to private.
1107 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1108 ConsumeToken(); // eat the @ sign
1110 if (Tok.is(tok::code_completion)) {
1111 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1112 ConsumeCodeCompletionToken();
1115 switch (Tok.getObjCKeywordID()) {
1116 case tok::objc_private:
1117 case tok::objc_public:
1118 case tok::objc_protected:
1119 case tok::objc_package:
1120 visibility = Tok.getObjCKeywordID();
1121 ConsumeToken();
1122 continue;
1123 default:
1124 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1125 continue;
1129 if (Tok.is(tok::code_completion)) {
1130 Actions.CodeCompleteOrdinaryName(getCurScope(),
1131 Sema::PCC_ObjCInstanceVariableList);
1132 ConsumeCodeCompletionToken();
1135 struct ObjCIvarCallback : FieldCallback {
1136 Parser &P;
1137 Decl *IDecl;
1138 tok::ObjCKeywordKind visibility;
1139 llvm::SmallVectorImpl<Decl *> &AllIvarDecls;
1141 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1142 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) :
1143 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1146 Decl *invoke(FieldDeclarator &FD) {
1147 // Install the declarator into the interface decl.
1148 Decl *Field
1149 = P.Actions.ActOnIvar(P.getCurScope(),
1150 FD.D.getDeclSpec().getSourceRange().getBegin(),
1151 IDecl, FD.D, FD.BitfieldSize, visibility);
1152 if (Field)
1153 AllIvarDecls.push_back(Field);
1154 return Field;
1156 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1158 // Parse all the comma separated declarators.
1159 DeclSpec DS;
1160 ParseStructDeclaration(DS, Callback);
1162 if (Tok.is(tok::semi)) {
1163 ConsumeToken();
1164 } else {
1165 Diag(Tok, diag::err_expected_semi_decl_list);
1166 // Skip to end of block or statement
1167 SkipUntil(tok::r_brace, true, true);
1170 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1171 Actions.ActOnLastBitfield(RBraceLoc, interfaceDecl, AllIvarDecls);
1172 // Call ActOnFields() even if we don't have any decls. This is useful
1173 // for code rewriting tools that need to be aware of the empty list.
1174 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1175 AllIvarDecls.data(), AllIvarDecls.size(),
1176 LBraceLoc, RBraceLoc, 0);
1177 return;
1180 /// objc-protocol-declaration:
1181 /// objc-protocol-definition
1182 /// objc-protocol-forward-reference
1184 /// objc-protocol-definition:
1185 /// @protocol identifier
1186 /// objc-protocol-refs[opt]
1187 /// objc-interface-decl-list
1188 /// @end
1190 /// objc-protocol-forward-reference:
1191 /// @protocol identifier-list ';'
1193 /// "@protocol identifier ;" should be resolved as "@protocol
1194 /// identifier-list ;": objc-interface-decl-list may not start with a
1195 /// semicolon in the first alternative if objc-protocol-refs are omitted.
1196 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1197 ParsedAttributes &attrs) {
1198 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1199 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1200 ConsumeToken(); // the "protocol" identifier
1202 if (Tok.is(tok::code_completion)) {
1203 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1204 ConsumeCodeCompletionToken();
1207 if (Tok.isNot(tok::identifier)) {
1208 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1209 return 0;
1211 // Save the protocol name, then consume it.
1212 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1213 SourceLocation nameLoc = ConsumeToken();
1215 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1216 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1217 ConsumeToken();
1218 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1219 attrs.getList());
1222 if (Tok.is(tok::comma)) { // list of forward declarations.
1223 llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1224 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1226 // Parse the list of forward declarations.
1227 while (1) {
1228 ConsumeToken(); // the ','
1229 if (Tok.isNot(tok::identifier)) {
1230 Diag(Tok, diag::err_expected_ident);
1231 SkipUntil(tok::semi);
1232 return 0;
1234 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1235 Tok.getLocation()));
1236 ConsumeToken(); // the identifier
1238 if (Tok.isNot(tok::comma))
1239 break;
1241 // Consume the ';'.
1242 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1243 return 0;
1245 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1246 &ProtocolRefs[0],
1247 ProtocolRefs.size(),
1248 attrs.getList());
1251 // Last, and definitely not least, parse a protocol declaration.
1252 SourceLocation LAngleLoc, EndProtoLoc;
1254 llvm::SmallVector<Decl *, 8> ProtocolRefs;
1255 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1256 if (Tok.is(tok::less) &&
1257 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1258 LAngleLoc, EndProtoLoc))
1259 return 0;
1261 Decl *ProtoType =
1262 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1263 ProtocolRefs.data(),
1264 ProtocolRefs.size(),
1265 ProtocolLocs.data(),
1266 EndProtoLoc, attrs.getList());
1267 ParseObjCInterfaceDeclList(ProtoType, tok::objc_protocol);
1268 return ProtoType;
1271 /// objc-implementation:
1272 /// objc-class-implementation-prologue
1273 /// objc-category-implementation-prologue
1275 /// objc-class-implementation-prologue:
1276 /// @implementation identifier objc-superclass[opt]
1277 /// objc-class-instance-variables[opt]
1279 /// objc-category-implementation-prologue:
1280 /// @implementation identifier ( identifier )
1281 Decl *Parser::ParseObjCAtImplementationDeclaration(
1282 SourceLocation atLoc) {
1283 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1284 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1285 ConsumeToken(); // the "implementation" identifier
1287 // Code completion after '@implementation'.
1288 if (Tok.is(tok::code_completion)) {
1289 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1290 ConsumeCodeCompletionToken();
1293 if (Tok.isNot(tok::identifier)) {
1294 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1295 return 0;
1297 // We have a class or category name - consume it.
1298 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1299 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1301 if (Tok.is(tok::l_paren)) {
1302 // we have a category implementation.
1303 ConsumeParen();
1304 SourceLocation categoryLoc, rparenLoc;
1305 IdentifierInfo *categoryId = 0;
1307 if (Tok.is(tok::code_completion)) {
1308 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1309 ConsumeCodeCompletionToken();
1312 if (Tok.is(tok::identifier)) {
1313 categoryId = Tok.getIdentifierInfo();
1314 categoryLoc = ConsumeToken();
1315 } else {
1316 Diag(Tok, diag::err_expected_ident); // missing category name.
1317 return 0;
1319 if (Tok.isNot(tok::r_paren)) {
1320 Diag(Tok, diag::err_expected_rparen);
1321 SkipUntil(tok::r_paren, false); // don't stop at ';'
1322 return 0;
1324 rparenLoc = ConsumeParen();
1325 Decl *ImplCatType = Actions.ActOnStartCategoryImplementation(
1326 atLoc, nameId, nameLoc, categoryId,
1327 categoryLoc);
1328 ObjCImpDecl = ImplCatType;
1329 PendingObjCImpDecl.push_back(ObjCImpDecl);
1330 return 0;
1332 // We have a class implementation
1333 SourceLocation superClassLoc;
1334 IdentifierInfo *superClassId = 0;
1335 if (Tok.is(tok::colon)) {
1336 // We have a super class
1337 ConsumeToken();
1338 if (Tok.isNot(tok::identifier)) {
1339 Diag(Tok, diag::err_expected_ident); // missing super class name.
1340 return 0;
1342 superClassId = Tok.getIdentifierInfo();
1343 superClassLoc = ConsumeToken(); // Consume super class name
1345 Decl *ImplClsType = Actions.ActOnStartClassImplementation(
1346 atLoc, nameId, nameLoc,
1347 superClassId, superClassLoc);
1349 if (Tok.is(tok::l_brace)) // we have ivars
1350 ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/,
1351 tok::objc_private, atLoc);
1352 ObjCImpDecl = ImplClsType;
1353 PendingObjCImpDecl.push_back(ObjCImpDecl);
1355 return 0;
1358 Decl *Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1359 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1360 "ParseObjCAtEndDeclaration(): Expected @end");
1361 Decl *Result = ObjCImpDecl;
1362 ConsumeToken(); // the "end" identifier
1363 if (ObjCImpDecl) {
1364 Actions.ActOnAtEnd(getCurScope(), atEnd, ObjCImpDecl);
1365 ObjCImpDecl = 0;
1366 PendingObjCImpDecl.pop_back();
1368 else {
1369 // missing @implementation
1370 Diag(atEnd.getBegin(), diag::warn_expected_implementation);
1372 return Result;
1375 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
1376 Actions.DiagnoseUseOfUnimplementedSelectors();
1377 if (PendingObjCImpDecl.empty())
1378 return Actions.ConvertDeclToDeclGroup(0);
1379 Decl *ImpDecl = PendingObjCImpDecl.pop_back_val();
1380 Actions.ActOnAtEnd(getCurScope(), SourceRange(), ImpDecl);
1381 return Actions.ConvertDeclToDeclGroup(ImpDecl);
1384 /// compatibility-alias-decl:
1385 /// @compatibility_alias alias-name class-name ';'
1387 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1388 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1389 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1390 ConsumeToken(); // consume compatibility_alias
1391 if (Tok.isNot(tok::identifier)) {
1392 Diag(Tok, diag::err_expected_ident);
1393 return 0;
1395 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1396 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1397 if (Tok.isNot(tok::identifier)) {
1398 Diag(Tok, diag::err_expected_ident);
1399 return 0;
1401 IdentifierInfo *classId = Tok.getIdentifierInfo();
1402 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1403 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1404 "@compatibility_alias");
1405 return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
1406 classId, classLoc);
1409 /// property-synthesis:
1410 /// @synthesize property-ivar-list ';'
1412 /// property-ivar-list:
1413 /// property-ivar
1414 /// property-ivar-list ',' property-ivar
1416 /// property-ivar:
1417 /// identifier
1418 /// identifier '=' identifier
1420 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1421 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1422 "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1423 ConsumeToken(); // consume synthesize
1425 while (true) {
1426 if (Tok.is(tok::code_completion)) {
1427 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1428 ConsumeCodeCompletionToken();
1431 if (Tok.isNot(tok::identifier)) {
1432 Diag(Tok, diag::err_synthesized_property_name);
1433 SkipUntil(tok::semi);
1434 return 0;
1437 IdentifierInfo *propertyIvar = 0;
1438 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1439 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1440 SourceLocation propertyIvarLoc;
1441 if (Tok.is(tok::equal)) {
1442 // property '=' ivar-name
1443 ConsumeToken(); // consume '='
1445 if (Tok.is(tok::code_completion)) {
1446 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId,
1447 ObjCImpDecl);
1448 ConsumeCodeCompletionToken();
1451 if (Tok.isNot(tok::identifier)) {
1452 Diag(Tok, diag::err_expected_ident);
1453 break;
1455 propertyIvar = Tok.getIdentifierInfo();
1456 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1458 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, ObjCImpDecl,
1459 propertyId, propertyIvar, propertyIvarLoc);
1460 if (Tok.isNot(tok::comma))
1461 break;
1462 ConsumeToken(); // consume ','
1464 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1465 return 0;
1468 /// property-dynamic:
1469 /// @dynamic property-list
1471 /// property-list:
1472 /// identifier
1473 /// property-list ',' identifier
1475 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1476 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1477 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1478 ConsumeToken(); // consume dynamic
1479 while (true) {
1480 if (Tok.is(tok::code_completion)) {
1481 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1482 ConsumeCodeCompletionToken();
1485 if (Tok.isNot(tok::identifier)) {
1486 Diag(Tok, diag::err_expected_ident);
1487 SkipUntil(tok::semi);
1488 return 0;
1491 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1492 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1493 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, ObjCImpDecl,
1494 propertyId, 0, SourceLocation());
1496 if (Tok.isNot(tok::comma))
1497 break;
1498 ConsumeToken(); // consume ','
1500 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1501 return 0;
1504 /// objc-throw-statement:
1505 /// throw expression[opt];
1507 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1508 ExprResult Res;
1509 ConsumeToken(); // consume throw
1510 if (Tok.isNot(tok::semi)) {
1511 Res = ParseExpression();
1512 if (Res.isInvalid()) {
1513 SkipUntil(tok::semi);
1514 return StmtError();
1517 // consume ';'
1518 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1519 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1522 /// objc-synchronized-statement:
1523 /// @synchronized '(' expression ')' compound-statement
1525 StmtResult
1526 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1527 ConsumeToken(); // consume synchronized
1528 if (Tok.isNot(tok::l_paren)) {
1529 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1530 return StmtError();
1532 ConsumeParen(); // '('
1533 ExprResult Res(ParseExpression());
1534 if (Res.isInvalid()) {
1535 SkipUntil(tok::semi);
1536 return StmtError();
1538 if (Tok.isNot(tok::r_paren)) {
1539 Diag(Tok, diag::err_expected_lbrace);
1540 return StmtError();
1542 ConsumeParen(); // ')'
1543 if (Tok.isNot(tok::l_brace)) {
1544 Diag(Tok, diag::err_expected_lbrace);
1545 return StmtError();
1547 // Enter a scope to hold everything within the compound stmt. Compound
1548 // statements can always hold declarations.
1549 ParseScope BodyScope(this, Scope::DeclScope);
1551 StmtResult SynchBody(ParseCompoundStatementBody());
1553 BodyScope.Exit();
1554 if (SynchBody.isInvalid())
1555 SynchBody = Actions.ActOnNullStmt(Tok.getLocation());
1556 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, Res.take(), SynchBody.take());
1559 /// objc-try-catch-statement:
1560 /// @try compound-statement objc-catch-list[opt]
1561 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1563 /// objc-catch-list:
1564 /// @catch ( parameter-declaration ) compound-statement
1565 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1566 /// catch-parameter-declaration:
1567 /// parameter-declaration
1568 /// '...' [OBJC2]
1570 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1571 bool catch_or_finally_seen = false;
1573 ConsumeToken(); // consume try
1574 if (Tok.isNot(tok::l_brace)) {
1575 Diag(Tok, diag::err_expected_lbrace);
1576 return StmtError();
1578 StmtVector CatchStmts(Actions);
1579 StmtResult FinallyStmt;
1580 ParseScope TryScope(this, Scope::DeclScope);
1581 StmtResult TryBody(ParseCompoundStatementBody());
1582 TryScope.Exit();
1583 if (TryBody.isInvalid())
1584 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1586 while (Tok.is(tok::at)) {
1587 // At this point, we need to lookahead to determine if this @ is the start
1588 // of an @catch or @finally. We don't want to consume the @ token if this
1589 // is an @try or @encode or something else.
1590 Token AfterAt = GetLookAheadToken(1);
1591 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1592 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1593 break;
1595 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1596 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1597 Decl *FirstPart = 0;
1598 ConsumeToken(); // consume catch
1599 if (Tok.is(tok::l_paren)) {
1600 ConsumeParen();
1601 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1602 if (Tok.isNot(tok::ellipsis)) {
1603 DeclSpec DS;
1604 ParseDeclarationSpecifiers(DS);
1605 // For some odd reason, the name of the exception variable is
1606 // optional. As a result, we need to use "PrototypeContext", because
1607 // we must accept either 'declarator' or 'abstract-declarator' here.
1608 Declarator ParmDecl(DS, Declarator::PrototypeContext);
1609 ParseDeclarator(ParmDecl);
1611 // Inform the actions module about the declarator, so it
1612 // gets added to the current scope.
1613 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1614 } else
1615 ConsumeToken(); // consume '...'
1617 SourceLocation RParenLoc;
1619 if (Tok.is(tok::r_paren))
1620 RParenLoc = ConsumeParen();
1621 else // Skip over garbage, until we get to ')'. Eat the ')'.
1622 SkipUntil(tok::r_paren, true, false);
1624 StmtResult CatchBody(true);
1625 if (Tok.is(tok::l_brace))
1626 CatchBody = ParseCompoundStatementBody();
1627 else
1628 Diag(Tok, diag::err_expected_lbrace);
1629 if (CatchBody.isInvalid())
1630 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1632 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1633 RParenLoc,
1634 FirstPart,
1635 CatchBody.take());
1636 if (!Catch.isInvalid())
1637 CatchStmts.push_back(Catch.release());
1639 } else {
1640 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1641 << "@catch clause";
1642 return StmtError();
1644 catch_or_finally_seen = true;
1645 } else {
1646 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1647 ConsumeToken(); // consume finally
1648 ParseScope FinallyScope(this, Scope::DeclScope);
1650 StmtResult FinallyBody(true);
1651 if (Tok.is(tok::l_brace))
1652 FinallyBody = ParseCompoundStatementBody();
1653 else
1654 Diag(Tok, diag::err_expected_lbrace);
1655 if (FinallyBody.isInvalid())
1656 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1657 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1658 FinallyBody.take());
1659 catch_or_finally_seen = true;
1660 break;
1663 if (!catch_or_finally_seen) {
1664 Diag(atLoc, diag::err_missing_catch_finally);
1665 return StmtError();
1668 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1669 move_arg(CatchStmts),
1670 FinallyStmt.take());
1673 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1675 Decl *Parser::ParseObjCMethodDefinition() {
1676 Decl *MDecl = ParseObjCMethodPrototype(ObjCImpDecl);
1678 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1679 "parsing Objective-C method");
1681 // parse optional ';'
1682 if (Tok.is(tok::semi)) {
1683 if (ObjCImpDecl) {
1684 Diag(Tok, diag::warn_semicolon_before_method_body)
1685 << FixItHint::CreateRemoval(Tok.getLocation());
1687 ConsumeToken();
1690 // We should have an opening brace now.
1691 if (Tok.isNot(tok::l_brace)) {
1692 Diag(Tok, diag::err_expected_method_body);
1694 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1695 SkipUntil(tok::l_brace, true, true);
1697 // If we didn't find the '{', bail out.
1698 if (Tok.isNot(tok::l_brace))
1699 return 0;
1701 SourceLocation BraceLoc = Tok.getLocation();
1703 // Enter a scope for the method body.
1704 ParseScope BodyScope(this,
1705 Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
1707 // Tell the actions module that we have entered a method definition with the
1708 // specified Declarator for the method.
1709 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
1711 if (PP.isCodeCompletionEnabled())
1712 if (trySkippingFunctionBodyForCodeCompletion())
1713 return Actions.ActOnFinishFunctionBody(MDecl, 0);
1715 StmtResult FnBody(ParseCompoundStatementBody());
1717 // If the function body could not be parsed, make a bogus compoundstmt.
1718 if (FnBody.isInvalid())
1719 FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
1720 MultiStmtArg(Actions), false);
1722 // TODO: Pass argument information.
1723 Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
1725 // Leave the function body scope.
1726 BodyScope.Exit();
1728 return MDecl;
1731 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1732 if (Tok.is(tok::code_completion)) {
1733 Actions.CodeCompleteObjCAtStatement(getCurScope());
1734 ConsumeCodeCompletionToken();
1735 return StmtError();
1738 if (Tok.isObjCAtKeyword(tok::objc_try))
1739 return ParseObjCTryStmt(AtLoc);
1741 if (Tok.isObjCAtKeyword(tok::objc_throw))
1742 return ParseObjCThrowStmt(AtLoc);
1744 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1745 return ParseObjCSynchronizedStmt(AtLoc);
1747 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
1748 if (Res.isInvalid()) {
1749 // If the expression is invalid, skip ahead to the next semicolon. Not
1750 // doing this opens us up to the possibility of infinite loops if
1751 // ParseExpression does not consume any tokens.
1752 SkipUntil(tok::semi);
1753 return StmtError();
1756 // Otherwise, eat the semicolon.
1757 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1758 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
1761 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1762 switch (Tok.getKind()) {
1763 case tok::code_completion:
1764 Actions.CodeCompleteObjCAtExpression(getCurScope());
1765 ConsumeCodeCompletionToken();
1766 return ExprError();
1768 case tok::string_literal: // primary-expression: string-literal
1769 case tok::wide_string_literal:
1770 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1771 default:
1772 if (Tok.getIdentifierInfo() == 0)
1773 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1775 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1776 case tok::objc_encode:
1777 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1778 case tok::objc_protocol:
1779 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1780 case tok::objc_selector:
1781 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1782 default:
1783 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1788 /// \brirg Parse the receiver of an Objective-C++ message send.
1790 /// This routine parses the receiver of a message send in
1791 /// Objective-C++ either as a type or as an expression. Note that this
1792 /// routine must not be called to parse a send to 'super', since it
1793 /// has no way to return such a result.
1794 ///
1795 /// \param IsExpr Whether the receiver was parsed as an expression.
1797 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
1798 /// IsExpr is true), the parsed expression. If the receiver was parsed
1799 /// as a type (\c IsExpr is false), the parsed type.
1801 /// \returns True if an error occurred during parsing or semantic
1802 /// analysis, in which case the arguments do not have valid
1803 /// values. Otherwise, returns false for a successful parse.
1805 /// objc-receiver: [C++]
1806 /// 'super' [not parsed here]
1807 /// expression
1808 /// simple-type-specifier
1809 /// typename-specifier
1810 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
1811 InMessageExpressionRAIIObject InMessage(*this, true);
1813 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1814 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
1815 TryAnnotateTypeOrScopeToken();
1817 if (!isCXXSimpleTypeSpecifier()) {
1818 // objc-receiver:
1819 // expression
1820 ExprResult Receiver = ParseExpression();
1821 if (Receiver.isInvalid())
1822 return true;
1824 IsExpr = true;
1825 TypeOrExpr = Receiver.take();
1826 return false;
1829 // objc-receiver:
1830 // typename-specifier
1831 // simple-type-specifier
1832 // expression (that starts with one of the above)
1833 DeclSpec DS;
1834 ParseCXXSimpleTypeSpecifier(DS);
1836 if (Tok.is(tok::l_paren)) {
1837 // If we see an opening parentheses at this point, we are
1838 // actually parsing an expression that starts with a
1839 // function-style cast, e.g.,
1841 // postfix-expression:
1842 // simple-type-specifier ( expression-list [opt] )
1843 // typename-specifier ( expression-list [opt] )
1845 // Parse the remainder of this case, then the (optional)
1846 // postfix-expression suffix, followed by the (optional)
1847 // right-hand side of the binary expression. We have an
1848 // instance method.
1849 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
1850 if (!Receiver.isInvalid())
1851 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
1852 if (!Receiver.isInvalid())
1853 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
1854 if (Receiver.isInvalid())
1855 return true;
1857 IsExpr = true;
1858 TypeOrExpr = Receiver.take();
1859 return false;
1862 // We have a class message. Turn the simple-type-specifier or
1863 // typename-specifier we parsed into a type and parse the
1864 // remainder of the class message.
1865 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1866 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1867 if (Type.isInvalid())
1868 return true;
1870 IsExpr = false;
1871 TypeOrExpr = Type.get().getAsOpaquePtr();
1872 return false;
1875 /// \brief Determine whether the parser is currently referring to a an
1876 /// Objective-C message send, using a simplified heuristic to avoid overhead.
1878 /// This routine will only return true for a subset of valid message-send
1879 /// expressions.
1880 bool Parser::isSimpleObjCMessageExpression() {
1881 assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
1882 "Incorrect start for isSimpleObjCMessageExpression");
1883 return GetLookAheadToken(1).is(tok::identifier) &&
1884 GetLookAheadToken(2).is(tok::identifier);
1887 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
1888 if (!getLang().ObjC1 || !NextToken().is(tok::identifier) ||
1889 InMessageExpression)
1890 return false;
1893 ParsedType Type;
1895 if (Tok.is(tok::annot_typename))
1896 Type = getTypeAnnotation(Tok);
1897 else if (Tok.is(tok::identifier))
1898 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
1899 getCurScope());
1900 else
1901 return false;
1903 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
1904 const Token &AfterNext = GetLookAheadToken(2);
1905 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
1906 if (Tok.is(tok::identifier))
1907 TryAnnotateTypeOrScopeToken();
1909 return Tok.is(tok::annot_typename);
1913 return false;
1916 /// objc-message-expr:
1917 /// '[' objc-receiver objc-message-args ']'
1919 /// objc-receiver: [C]
1920 /// 'super'
1921 /// expression
1922 /// class-name
1923 /// type-name
1925 ExprResult Parser::ParseObjCMessageExpression() {
1926 assert(Tok.is(tok::l_square) && "'[' expected");
1927 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
1929 if (Tok.is(tok::code_completion)) {
1930 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
1931 ConsumeCodeCompletionToken();
1932 SkipUntil(tok::r_square);
1933 return ExprError();
1936 InMessageExpressionRAIIObject InMessage(*this, true);
1938 if (getLang().CPlusPlus) {
1939 // We completely separate the C and C++ cases because C++ requires
1940 // more complicated (read: slower) parsing.
1942 // Handle send to super.
1943 // FIXME: This doesn't benefit from the same typo-correction we
1944 // get in Objective-C.
1945 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
1946 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
1947 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
1948 ParsedType(), 0);
1950 // Parse the receiver, which is either a type or an expression.
1951 bool IsExpr;
1952 void *TypeOrExpr = NULL;
1953 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
1954 SkipUntil(tok::r_square);
1955 return ExprError();
1958 if (IsExpr)
1959 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1960 ParsedType(),
1961 static_cast<Expr*>(TypeOrExpr));
1963 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1964 ParsedType::getFromOpaquePtr(TypeOrExpr),
1968 if (Tok.is(tok::identifier)) {
1969 IdentifierInfo *Name = Tok.getIdentifierInfo();
1970 SourceLocation NameLoc = Tok.getLocation();
1971 ParsedType ReceiverType;
1972 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
1973 Name == Ident_super,
1974 NextToken().is(tok::period),
1975 ReceiverType)) {
1976 case Sema::ObjCSuperMessage:
1977 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
1978 ParsedType(), 0);
1980 case Sema::ObjCClassMessage:
1981 if (!ReceiverType) {
1982 SkipUntil(tok::r_square);
1983 return ExprError();
1986 ConsumeToken(); // the type name
1988 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
1989 ReceiverType, 0);
1991 case Sema::ObjCInstanceMessage:
1992 // Fall through to parse an expression.
1993 break;
1997 // Otherwise, an arbitrary expression can be the receiver of a send.
1998 ExprResult Res(ParseExpression());
1999 if (Res.isInvalid()) {
2000 SkipUntil(tok::r_square);
2001 return move(Res);
2004 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2005 ParsedType(), Res.take());
2008 /// \brief Parse the remainder of an Objective-C message following the
2009 /// '[' objc-receiver.
2011 /// This routine handles sends to super, class messages (sent to a
2012 /// class name), and instance messages (sent to an object), and the
2013 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2014 /// ReceiverExpr, respectively. Only one of these parameters may have
2015 /// a valid value.
2017 /// \param LBracLoc The location of the opening '['.
2019 /// \param SuperLoc If this is a send to 'super', the location of the
2020 /// 'super' keyword that indicates a send to the superclass.
2022 /// \param ReceiverType If this is a class message, the type of the
2023 /// class we are sending a message to.
2025 /// \param ReceiverExpr If this is an instance message, the expression
2026 /// used to compute the receiver object.
2028 /// objc-message-args:
2029 /// objc-selector
2030 /// objc-keywordarg-list
2032 /// objc-keywordarg-list:
2033 /// objc-keywordarg
2034 /// objc-keywordarg-list objc-keywordarg
2036 /// objc-keywordarg:
2037 /// selector-name[opt] ':' objc-keywordexpr
2039 /// objc-keywordexpr:
2040 /// nonempty-expr-list
2042 /// nonempty-expr-list:
2043 /// assignment-expression
2044 /// nonempty-expr-list , assignment-expression
2046 ExprResult
2047 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2048 SourceLocation SuperLoc,
2049 ParsedType ReceiverType,
2050 ExprArg ReceiverExpr) {
2051 InMessageExpressionRAIIObject InMessage(*this, true);
2053 if (Tok.is(tok::code_completion)) {
2054 if (SuperLoc.isValid())
2055 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2056 false);
2057 else if (ReceiverType)
2058 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2059 false);
2060 else
2061 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2062 0, 0, false);
2063 ConsumeCodeCompletionToken();
2066 // Parse objc-selector
2067 SourceLocation Loc;
2068 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2070 SourceLocation SelectorLoc = Loc;
2072 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2073 ExprVector KeyExprs(Actions);
2075 if (Tok.is(tok::colon)) {
2076 while (1) {
2077 // Each iteration parses a single keyword argument.
2078 KeyIdents.push_back(selIdent);
2080 if (Tok.isNot(tok::colon)) {
2081 Diag(Tok, diag::err_expected_colon);
2082 // We must manually skip to a ']', otherwise the expression skipper will
2083 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2084 // the enclosing expression.
2085 SkipUntil(tok::r_square);
2086 return ExprError();
2089 ConsumeToken(); // Eat the ':'.
2090 /// Parse the expression after ':'
2092 if (Tok.is(tok::code_completion)) {
2093 if (SuperLoc.isValid())
2094 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2095 KeyIdents.data(),
2096 KeyIdents.size(),
2097 /*AtArgumentEpression=*/true);
2098 else if (ReceiverType)
2099 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2100 KeyIdents.data(),
2101 KeyIdents.size(),
2102 /*AtArgumentEpression=*/true);
2103 else
2104 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2105 KeyIdents.data(),
2106 KeyIdents.size(),
2107 /*AtArgumentEpression=*/true);
2109 ConsumeCodeCompletionToken();
2110 SkipUntil(tok::r_square);
2111 return ExprError();
2114 ExprResult Res(ParseAssignmentExpression());
2115 if (Res.isInvalid()) {
2116 // We must manually skip to a ']', otherwise the expression skipper will
2117 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2118 // the enclosing expression.
2119 SkipUntil(tok::r_square);
2120 return move(Res);
2123 // We have a valid expression.
2124 KeyExprs.push_back(Res.release());
2126 // Code completion after each argument.
2127 if (Tok.is(tok::code_completion)) {
2128 if (SuperLoc.isValid())
2129 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2130 KeyIdents.data(),
2131 KeyIdents.size(),
2132 /*AtArgumentEpression=*/false);
2133 else if (ReceiverType)
2134 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2135 KeyIdents.data(),
2136 KeyIdents.size(),
2137 /*AtArgumentEpression=*/false);
2138 else
2139 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2140 KeyIdents.data(),
2141 KeyIdents.size(),
2142 /*AtArgumentEpression=*/false);
2143 ConsumeCodeCompletionToken();
2144 SkipUntil(tok::r_square);
2145 return ExprError();
2148 // Check for another keyword selector.
2149 selIdent = ParseObjCSelectorPiece(Loc);
2150 if (!selIdent && Tok.isNot(tok::colon))
2151 break;
2152 // We have a selector or a colon, continue parsing.
2154 // Parse the, optional, argument list, comma separated.
2155 while (Tok.is(tok::comma)) {
2156 ConsumeToken(); // Eat the ','.
2157 /// Parse the expression after ','
2158 ExprResult Res(ParseAssignmentExpression());
2159 if (Res.isInvalid()) {
2160 // We must manually skip to a ']', otherwise the expression skipper will
2161 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2162 // the enclosing expression.
2163 SkipUntil(tok::r_square);
2164 return move(Res);
2167 // We have a valid expression.
2168 KeyExprs.push_back(Res.release());
2170 } else if (!selIdent) {
2171 Diag(Tok, diag::err_expected_ident); // missing selector name.
2173 // We must manually skip to a ']', otherwise the expression skipper will
2174 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2175 // the enclosing expression.
2176 SkipUntil(tok::r_square);
2177 return ExprError();
2180 if (Tok.isNot(tok::r_square)) {
2181 if (Tok.is(tok::identifier))
2182 Diag(Tok, diag::err_expected_colon);
2183 else
2184 Diag(Tok, diag::err_expected_rsquare);
2185 // We must manually skip to a ']', otherwise the expression skipper will
2186 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2187 // the enclosing expression.
2188 SkipUntil(tok::r_square);
2189 return ExprError();
2192 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2194 unsigned nKeys = KeyIdents.size();
2195 if (nKeys == 0)
2196 KeyIdents.push_back(selIdent);
2197 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2199 if (SuperLoc.isValid())
2200 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2201 LBracLoc, SelectorLoc, RBracLoc,
2202 MultiExprArg(Actions,
2203 KeyExprs.take(),
2204 KeyExprs.size()));
2205 else if (ReceiverType)
2206 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2207 LBracLoc, SelectorLoc, RBracLoc,
2208 MultiExprArg(Actions,
2209 KeyExprs.take(),
2210 KeyExprs.size()));
2211 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2212 LBracLoc, SelectorLoc, RBracLoc,
2213 MultiExprArg(Actions,
2214 KeyExprs.take(),
2215 KeyExprs.size()));
2218 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2219 ExprResult Res(ParseStringLiteralExpression());
2220 if (Res.isInvalid()) return move(Res);
2222 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2223 // expressions. At this point, we know that the only valid thing that starts
2224 // with '@' is an @"".
2225 llvm::SmallVector<SourceLocation, 4> AtLocs;
2226 ExprVector AtStrings(Actions);
2227 AtLocs.push_back(AtLoc);
2228 AtStrings.push_back(Res.release());
2230 while (Tok.is(tok::at)) {
2231 AtLocs.push_back(ConsumeToken()); // eat the @.
2233 // Invalid unless there is a string literal.
2234 if (!isTokenStringLiteral())
2235 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2237 ExprResult Lit(ParseStringLiteralExpression());
2238 if (Lit.isInvalid())
2239 return move(Lit);
2241 AtStrings.push_back(Lit.release());
2244 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2245 AtStrings.size()));
2248 /// objc-encode-expression:
2249 /// @encode ( type-name )
2250 ExprResult
2251 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2252 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2254 SourceLocation EncLoc = ConsumeToken();
2256 if (Tok.isNot(tok::l_paren))
2257 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2259 SourceLocation LParenLoc = ConsumeParen();
2261 TypeResult Ty = ParseTypeName();
2263 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2265 if (Ty.isInvalid())
2266 return ExprError();
2268 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc,
2269 Ty.get(), RParenLoc));
2272 /// objc-protocol-expression
2273 /// @protocol ( protocol-name )
2274 ExprResult
2275 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2276 SourceLocation ProtoLoc = ConsumeToken();
2278 if (Tok.isNot(tok::l_paren))
2279 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2281 SourceLocation LParenLoc = ConsumeParen();
2283 if (Tok.isNot(tok::identifier))
2284 return ExprError(Diag(Tok, diag::err_expected_ident));
2286 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2287 ConsumeToken();
2289 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2291 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2292 LParenLoc, RParenLoc));
2295 /// objc-selector-expression
2296 /// @selector '(' objc-keyword-selector ')'
2297 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2298 SourceLocation SelectorLoc = ConsumeToken();
2300 if (Tok.isNot(tok::l_paren))
2301 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2303 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2304 SourceLocation LParenLoc = ConsumeParen();
2305 SourceLocation sLoc;
2307 if (Tok.is(tok::code_completion)) {
2308 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2309 KeyIdents.size());
2310 ConsumeCodeCompletionToken();
2311 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2312 return ExprError();
2315 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2316 if (!SelIdent && // missing selector name.
2317 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2318 return ExprError(Diag(Tok, diag::err_expected_ident));
2320 KeyIdents.push_back(SelIdent);
2321 unsigned nColons = 0;
2322 if (Tok.isNot(tok::r_paren)) {
2323 while (1) {
2324 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2325 ++nColons;
2326 KeyIdents.push_back(0);
2327 } else if (Tok.isNot(tok::colon))
2328 return ExprError(Diag(Tok, diag::err_expected_colon));
2330 ++nColons;
2331 ConsumeToken(); // Eat the ':'.
2332 if (Tok.is(tok::r_paren))
2333 break;
2335 if (Tok.is(tok::code_completion)) {
2336 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2337 KeyIdents.size());
2338 ConsumeCodeCompletionToken();
2339 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2340 return ExprError();
2343 // Check for another keyword selector.
2344 SourceLocation Loc;
2345 SelIdent = ParseObjCSelectorPiece(Loc);
2346 KeyIdents.push_back(SelIdent);
2347 if (!SelIdent && Tok.isNot(tok::colon))
2348 break;
2351 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2352 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2353 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2354 LParenLoc, RParenLoc));