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.
11 //
12 //===----------------------------------------------------------------------===//
13
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;
22
23
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'
ParseObjCAtDirectives()32 Decl *Parser::ParseObjCAtDirectives() {
33 SourceLocation AtLoc = ConsumeToken(); // the "@"
34
35 if (Tok.is(tok::code_completion)) {
36 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, false);
37 ConsumeCodeCompletionToken();
38 }
39
40 switch (Tok.getObjCKeywordID()) {
41 case tok::objc_class:
42 return ParseObjCAtClassDeclaration(AtLoc);
43 case tok::objc_interface: {
44 ParsedAttributes attrs(AttrFactory);
45 return ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
46 }
47 case tok::objc_protocol: {
48 ParsedAttributes attrs(AttrFactory);
49 return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
50 }
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;
65 }
66 }
67
68 ///
69 /// objc-class-declaration:
70 /// '@' 'class' identifier-list ';'
71 ///
ParseObjCAtClassDeclaration(SourceLocation atLoc)72 Decl *Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) {
73 ConsumeToken(); // the identifier "class"
74 llvm::SmallVector<IdentifierInfo *, 8> ClassNames;
75 llvm::SmallVector<SourceLocation, 8> ClassLocs;
76
77
78 while (1) {
79 if (Tok.isNot(tok::identifier)) {
80 Diag(Tok, diag::err_expected_ident);
81 SkipUntil(tok::semi);
82 return 0;
83 }
84 ClassNames.push_back(Tok.getIdentifierInfo());
85 ClassLocs.push_back(Tok.getLocation());
86 ConsumeToken();
87
88 if (Tok.isNot(tok::comma))
89 break;
90
91 ConsumeToken();
92 }
93
94 // Consume the ';'.
95 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@class"))
96 return 0;
97
98 return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(),
99 ClassLocs.data(),
100 ClassNames.size());
101 }
102
103 ///
104 /// objc-interface:
105 /// objc-class-interface-attributes[opt] objc-class-interface
106 /// objc-category-interface
107 ///
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
114 ///
115 /// objc-category-interface:
116 /// '@' 'interface' identifier '(' identifier[opt] ')'
117 /// objc-protocol-refs[opt]
118 /// objc-interface-decl-list
119 /// @end
120 ///
121 /// objc-superclass:
122 /// ':' identifier
123 ///
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
130 ///
ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,ParsedAttributes & attrs)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
136
137 // Code completion after '@interface'.
138 if (Tok.is(tok::code_completion)) {
139 Actions.CodeCompleteObjCInterfaceDecl(getCurScope());
140 ConsumeCodeCompletionToken();
141 }
142
143 if (Tok.isNot(tok::identifier)) {
144 Diag(Tok, diag::err_expected_ident); // missing class or category name.
145 return 0;
146 }
147
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();
161 }
162
163 // For ObjC2, the category name is optional (not an error).
164 if (Tok.is(tok::identifier)) {
165 categoryId = Tok.getIdentifierInfo();
166 categoryLoc = ConsumeToken();
167 }
168 else if (!getLang().ObjC2) {
169 Diag(Tok, diag::err_expected_ident); // missing category name.
170 return 0;
171 }
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;
176 }
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;
186
187 if (!attrs.empty()) // categories don't support attributes.
188 Diag(Tok, diag::err_objc_no_attributes_on_category);
189
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);
201
202 ParseObjCInterfaceDeclList(CategoryType, tok::objc_not_keyword);
203 return CategoryType;
204 }
205 // Parse a class interface.
206 IdentifierInfo *superClassId = 0;
207 SourceLocation superClassLoc;
208
209 if (Tok.is(tok::colon)) { // a super class is specified.
210 ConsumeToken();
211
212 // Code completion of superclass names.
213 if (Tok.is(tok::code_completion)) {
214 Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc);
215 ConsumeCodeCompletionToken();
216 }
217
218 if (Tok.isNot(tok::identifier)) {
219 Diag(Tok, diag::err_expected_ident); // missing super class name.
220 return 0;
221 }
222 superClassId = Tok.getIdentifierInfo();
223 superClassLoc = ConsumeToken();
224 }
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;
233
234 Decl *ClsType =
235 Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc,
236 superClassId, superClassLoc,
237 ProtocolRefs.data(), ProtocolRefs.size(),
238 ProtocolLocs.data(),
239 EndProtoLoc, attrs.getList());
240
241 if (Tok.is(tok::l_brace))
242 ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, atLoc);
243
244 ParseObjCInterfaceDeclList(ClsType, tok::objc_interface);
245 return ClsType;
246 }
247
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;
257
ObjCPropertyCallbackParser::ObjCPropertyCallback258 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) {
264 }
265
invokeParser::ObjCPropertyCallback266 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;
271 }
272 if (FD.BitfieldSize) {
273 P.Diag(AtLoc, diag::err_objc_property_bitfield)
274 << FD.D.getSourceRange();
275 return 0;
276 }
277
278 // Install the property declarator into interfaceDecl.
279 IdentifierInfo *SelName =
280 OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier();
281
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);
300
301 return Property;
302 }
303 };
304
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 ';'
312 ///
313 /// objc-method-requirement: [OBJC2]
314 /// @required
315 /// @optional
316 ///
ParseObjCInterfaceDeclList(Decl * interfaceDecl,tok::ObjCKeywordKind contextKey)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;
323
324 SourceRange AtEnd;
325
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, false);
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;
337 }
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, false);
344 continue;
345 }
346 // Ignore excess semicolons.
347 if (Tok.is(tok::semi)) {
348 ConsumeToken();
349 continue;
350 }
351
352 // If we got to the end of the file, exit the loop.
353 if (Tok.is(tok::eof))
354 break;
355
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();
362 }
363
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;
371
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(AttrFactory);
375 allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs));
376 continue;
377 }
378
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;
385 }
386
387 tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID();
388
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;
397 }
398
399 // Eat the identifier.
400 ConsumeToken();
401
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;
412
413 case tok::objc_implementation:
414 case tok::objc_interface:
415 Diag(Tok, diag::err_objc_missing_end);
416 ConsumeToken();
417 break;
418
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;
428
429 case tok::objc_property:
430 if (!getLang().ObjC2)
431 Diag(AtLoc, diag::err_objc_properties_require_objc2);
432
433 ObjCDeclSpec OCDS;
434 // Parse property attribute list, if any.
435 if (Tok.is(tok::l_paren))
436 ParseObjCPropertyAttribute(OCDS, interfaceDecl);
437
438 ObjCPropertyCallback Callback(*this, interfaceDecl, allProperties,
439 OCDS, AtLoc, MethodImplKind);
440
441 // Parse all the comma separated declarators.
442 DeclSpec DS(AttrFactory);
443 ParseStructDeclaration(DS, Callback);
444
445 ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
446 break;
447 }
448 }
449
450 // We break out of the big loop in two cases: when we see @end or when we see
451 // EOF. In the former case, eat the @end. In the later case, emit an error.
452 if (Tok.is(tok::code_completion)) {
453 Actions.CodeCompleteObjCAtDirective(getCurScope(), ObjCImpDecl, true);
454 ConsumeCodeCompletionToken();
455 } else if (Tok.isObjCAtKeyword(tok::objc_end))
456 ConsumeToken(); // the "end" identifier
457 else
458 Diag(Tok, diag::err_objc_missing_end);
459
460 // Insert collected methods declarations into the @interface object.
461 // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
462 Actions.ActOnAtEnd(getCurScope(), AtEnd, interfaceDecl,
463 allMethods.data(), allMethods.size(),
464 allProperties.data(), allProperties.size(),
465 allTUVariables.data(), allTUVariables.size());
466 }
467
468 /// Parse property attribute declarations.
469 ///
470 /// property-attr-decl: '(' property-attrlist ')'
471 /// property-attrlist:
472 /// property-attribute
473 /// property-attrlist ',' property-attribute
474 /// property-attribute:
475 /// getter '=' identifier
476 /// setter '=' identifier ':'
477 /// readonly
478 /// readwrite
479 /// assign
480 /// retain
481 /// copy
482 /// nonatomic
483 /// atomic
484 /// strong
485 /// weak
486 /// unsafe_unretained
487 ///
ParseObjCPropertyAttribute(ObjCDeclSpec & DS,Decl * ClassDecl)488 void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS, Decl *ClassDecl) {
489 assert(Tok.getKind() == tok::l_paren);
490 SourceLocation LHSLoc = ConsumeParen(); // consume '('
491
492 while (1) {
493 if (Tok.is(tok::code_completion)) {
494 Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS);
495 ConsumeCodeCompletionToken();
496 }
497 const IdentifierInfo *II = Tok.getIdentifierInfo();
498
499 // If this is not an identifier at all, bail out early.
500 if (II == 0) {
501 MatchRHSPunctuation(tok::r_paren, LHSLoc);
502 return;
503 }
504
505 SourceLocation AttrName = ConsumeToken(); // consume last attribute name
506
507 if (II->isStr("readonly"))
508 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly);
509 else if (II->isStr("assign"))
510 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign);
511 else if (II->isStr("unsafe_unretained"))
512 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained);
513 else if (II->isStr("readwrite"))
514 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite);
515 else if (II->isStr("retain"))
516 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain);
517 else if (II->isStr("strong"))
518 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong);
519 else if (II->isStr("copy"))
520 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy);
521 else if (II->isStr("nonatomic"))
522 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic);
523 else if (II->isStr("atomic"))
524 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic);
525 else if (II->isStr("weak"))
526 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak);
527 else if (II->isStr("getter") || II->isStr("setter")) {
528 bool IsSetter = II->getNameStart()[0] == 's';
529
530 // getter/setter require extra treatment.
531 unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter :
532 diag::err_objc_expected_equal_for_getter;
533
534 if (ExpectAndConsume(tok::equal, DiagID, "", tok::r_paren))
535 return;
536
537 if (Tok.is(tok::code_completion)) {
538 if (IsSetter)
539 Actions.CodeCompleteObjCPropertySetter(getCurScope(), ClassDecl);
540 else
541 Actions.CodeCompleteObjCPropertyGetter(getCurScope(), ClassDecl);
542 ConsumeCodeCompletionToken();
543 }
544
545
546 SourceLocation SelLoc;
547 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc);
548
549 if (!SelIdent) {
550 Diag(Tok, diag::err_objc_expected_selector_for_getter_setter)
551 << IsSetter;
552 SkipUntil(tok::r_paren);
553 return;
554 }
555
556 if (IsSetter) {
557 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter);
558 DS.setSetterName(SelIdent);
559
560 if (ExpectAndConsume(tok::colon,
561 diag::err_expected_colon_after_setter_name, "",
562 tok::r_paren))
563 return;
564 } else {
565 DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter);
566 DS.setGetterName(SelIdent);
567 }
568 } else {
569 Diag(AttrName, diag::err_objc_expected_property_attr) << II;
570 SkipUntil(tok::r_paren);
571 return;
572 }
573
574 if (Tok.isNot(tok::comma))
575 break;
576
577 ConsumeToken();
578 }
579
580 MatchRHSPunctuation(tok::r_paren, LHSLoc);
581 }
582
583 /// objc-method-proto:
584 /// objc-instance-method objc-method-decl objc-method-attributes[opt]
585 /// objc-class-method objc-method-decl objc-method-attributes[opt]
586 ///
587 /// objc-instance-method: '-'
588 /// objc-class-method: '+'
589 ///
590 /// objc-method-attributes: [OBJC2]
591 /// __attribute__((deprecated))
592 ///
ParseObjCMethodPrototype(Decl * IDecl,tok::ObjCKeywordKind MethodImplKind,bool MethodDefinition)593 Decl *Parser::ParseObjCMethodPrototype(Decl *IDecl,
594 tok::ObjCKeywordKind MethodImplKind,
595 bool MethodDefinition) {
596 assert((Tok.is(tok::minus) || Tok.is(tok::plus)) && "expected +/-");
597
598 tok::TokenKind methodType = Tok.getKind();
599 SourceLocation mLoc = ConsumeToken();
600 Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, IDecl,MethodImplKind,
601 MethodDefinition);
602 // Since this rule is used for both method declarations and definitions,
603 // the caller is (optionally) responsible for consuming the ';'.
604 return MDecl;
605 }
606
607 /// objc-selector:
608 /// identifier
609 /// one of
610 /// enum struct union if else while do for switch case default
611 /// break continue return goto asm sizeof typeof __alignof
612 /// unsigned long const short volatile signed restrict _Complex
613 /// in out inout bycopy byref oneway int char float double void _Bool
614 ///
ParseObjCSelectorPiece(SourceLocation & SelectorLoc)615 IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) {
616
617 switch (Tok.getKind()) {
618 default:
619 return 0;
620 case tok::ampamp:
621 case tok::ampequal:
622 case tok::amp:
623 case tok::pipe:
624 case tok::tilde:
625 case tok::exclaim:
626 case tok::exclaimequal:
627 case tok::pipepipe:
628 case tok::pipeequal:
629 case tok::caret:
630 case tok::caretequal: {
631 std::string ThisTok(PP.getSpelling(Tok));
632 if (isalpha(ThisTok[0])) {
633 IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data());
634 Tok.setKind(tok::identifier);
635 SelectorLoc = ConsumeToken();
636 return II;
637 }
638 return 0;
639 }
640
641 case tok::identifier:
642 case tok::kw_asm:
643 case tok::kw_auto:
644 case tok::kw_bool:
645 case tok::kw_break:
646 case tok::kw_case:
647 case tok::kw_catch:
648 case tok::kw_char:
649 case tok::kw_class:
650 case tok::kw_const:
651 case tok::kw_const_cast:
652 case tok::kw_continue:
653 case tok::kw_default:
654 case tok::kw_delete:
655 case tok::kw_do:
656 case tok::kw_double:
657 case tok::kw_dynamic_cast:
658 case tok::kw_else:
659 case tok::kw_enum:
660 case tok::kw_explicit:
661 case tok::kw_export:
662 case tok::kw_extern:
663 case tok::kw_false:
664 case tok::kw_float:
665 case tok::kw_for:
666 case tok::kw_friend:
667 case tok::kw_goto:
668 case tok::kw_if:
669 case tok::kw_inline:
670 case tok::kw_int:
671 case tok::kw_long:
672 case tok::kw_mutable:
673 case tok::kw_namespace:
674 case tok::kw_new:
675 case tok::kw_operator:
676 case tok::kw_private:
677 case tok::kw_protected:
678 case tok::kw_public:
679 case tok::kw_register:
680 case tok::kw_reinterpret_cast:
681 case tok::kw_restrict:
682 case tok::kw_return:
683 case tok::kw_short:
684 case tok::kw_signed:
685 case tok::kw_sizeof:
686 case tok::kw_static:
687 case tok::kw_static_cast:
688 case tok::kw_struct:
689 case tok::kw_switch:
690 case tok::kw_template:
691 case tok::kw_this:
692 case tok::kw_throw:
693 case tok::kw_true:
694 case tok::kw_try:
695 case tok::kw_typedef:
696 case tok::kw_typeid:
697 case tok::kw_typename:
698 case tok::kw_typeof:
699 case tok::kw_union:
700 case tok::kw_unsigned:
701 case tok::kw_using:
702 case tok::kw_virtual:
703 case tok::kw_void:
704 case tok::kw_volatile:
705 case tok::kw_wchar_t:
706 case tok::kw_while:
707 case tok::kw__Bool:
708 case tok::kw__Complex:
709 case tok::kw___alignof:
710 IdentifierInfo *II = Tok.getIdentifierInfo();
711 SelectorLoc = ConsumeToken();
712 return II;
713 }
714 }
715
716 /// objc-for-collection-in: 'in'
717 ///
isTokIdentifier_in() const718 bool Parser::isTokIdentifier_in() const {
719 // FIXME: May have to do additional look-ahead to only allow for
720 // valid tokens following an 'in'; such as an identifier, unary operators,
721 // '[' etc.
722 return (getLang().ObjC2 && Tok.is(tok::identifier) &&
723 Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]);
724 }
725
726 /// ParseObjCTypeQualifierList - This routine parses the objective-c's type
727 /// qualifier list and builds their bitmask representation in the input
728 /// argument.
729 ///
730 /// objc-type-qualifiers:
731 /// objc-type-qualifier
732 /// objc-type-qualifiers objc-type-qualifier
733 ///
ParseObjCTypeQualifierList(ObjCDeclSpec & DS,ObjCTypeNameContext Context)734 void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
735 ObjCTypeNameContext Context) {
736 while (1) {
737 if (Tok.is(tok::code_completion)) {
738 Actions.CodeCompleteObjCPassingType(getCurScope(), DS,
739 Context == OTN_ParameterType);
740 ConsumeCodeCompletionToken();
741 }
742
743 if (Tok.isNot(tok::identifier))
744 return;
745
746 const IdentifierInfo *II = Tok.getIdentifierInfo();
747 for (unsigned i = 0; i != objc_NumQuals; ++i) {
748 if (II != ObjCTypeQuals[i])
749 continue;
750
751 ObjCDeclSpec::ObjCDeclQualifier Qual;
752 switch (i) {
753 default: assert(0 && "Unknown decl qualifier");
754 case objc_in: Qual = ObjCDeclSpec::DQ_In; break;
755 case objc_out: Qual = ObjCDeclSpec::DQ_Out; break;
756 case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break;
757 case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break;
758 case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break;
759 case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break;
760 }
761 DS.setObjCDeclQualifier(Qual);
762 ConsumeToken();
763 II = 0;
764 break;
765 }
766
767 // If this wasn't a recognized qualifier, bail out.
768 if (II) return;
769 }
770 }
771
772 /// objc-type-name:
773 /// '(' objc-type-qualifiers[opt] type-name ')'
774 /// '(' objc-type-qualifiers[opt] ')'
775 ///
ParseObjCTypeName(ObjCDeclSpec & DS,ObjCTypeNameContext Context)776 ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS,
777 ObjCTypeNameContext Context) {
778 assert(Tok.is(tok::l_paren) && "expected (");
779
780 SourceLocation LParenLoc = ConsumeParen();
781 SourceLocation TypeStartLoc = Tok.getLocation();
782
783 // Parse type qualifiers, in, inout, etc.
784 ParseObjCTypeQualifierList(DS, Context);
785
786 ParsedType Ty;
787 if (isTypeSpecifierQualifier()) {
788 TypeResult TypeSpec =
789 ParseTypeName(0, Declarator::ObjCPrototypeContext, &DS);
790 if (!TypeSpec.isInvalid())
791 Ty = TypeSpec.get();
792 }
793
794 if (Tok.is(tok::r_paren))
795 ConsumeParen();
796 else if (Tok.getLocation() == TypeStartLoc) {
797 // If we didn't eat any tokens, then this isn't a type.
798 Diag(Tok, diag::err_expected_type);
799 SkipUntil(tok::r_paren);
800 } else {
801 // Otherwise, we found *something*, but didn't get a ')' in the right
802 // place. Emit an error then return what we have as the type.
803 MatchRHSPunctuation(tok::r_paren, LParenLoc);
804 }
805 return Ty;
806 }
807
808 /// objc-method-decl:
809 /// objc-selector
810 /// objc-keyword-selector objc-parmlist[opt]
811 /// objc-type-name objc-selector
812 /// objc-type-name objc-keyword-selector objc-parmlist[opt]
813 ///
814 /// objc-keyword-selector:
815 /// objc-keyword-decl
816 /// objc-keyword-selector objc-keyword-decl
817 ///
818 /// objc-keyword-decl:
819 /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier
820 /// objc-selector ':' objc-keyword-attributes[opt] identifier
821 /// ':' objc-type-name objc-keyword-attributes[opt] identifier
822 /// ':' objc-keyword-attributes[opt] identifier
823 ///
824 /// objc-parmlist:
825 /// objc-parms objc-ellipsis[opt]
826 ///
827 /// objc-parms:
828 /// objc-parms , parameter-declaration
829 ///
830 /// objc-ellipsis:
831 /// , ...
832 ///
833 /// objc-keyword-attributes: [OBJC2]
834 /// __attribute__((unused))
835 ///
ParseObjCMethodDecl(SourceLocation mLoc,tok::TokenKind mType,Decl * IDecl,tok::ObjCKeywordKind MethodImplKind,bool MethodDefinition)836 Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc,
837 tok::TokenKind mType,
838 Decl *IDecl,
839 tok::ObjCKeywordKind MethodImplKind,
840 bool MethodDefinition) {
841 ParsingDeclRAIIObject PD(*this);
842
843 if (Tok.is(tok::code_completion)) {
844 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
845 /*ReturnType=*/ ParsedType(), IDecl);
846 ConsumeCodeCompletionToken();
847 }
848
849 // Parse the return type if present.
850 ParsedType ReturnType;
851 ObjCDeclSpec DSRet;
852 if (Tok.is(tok::l_paren))
853 ReturnType = ParseObjCTypeName(DSRet, OTN_ResultType);
854
855 // If attributes exist before the method, parse them.
856 ParsedAttributes methodAttrs(AttrFactory);
857 if (getLang().ObjC2)
858 MaybeParseGNUAttributes(methodAttrs);
859
860 if (Tok.is(tok::code_completion)) {
861 Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus,
862 ReturnType, IDecl);
863 ConsumeCodeCompletionToken();
864 }
865
866 // Now parse the selector.
867 SourceLocation selLoc;
868 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc);
869
870 // An unnamed colon is valid.
871 if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name.
872 Diag(Tok, diag::err_expected_selector_for_method)
873 << SourceRange(mLoc, Tok.getLocation());
874 // Skip until we get a ; or {}.
875 SkipUntil(tok::r_brace);
876 return 0;
877 }
878
879 llvm::SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
880 if (Tok.isNot(tok::colon)) {
881 // If attributes exist after the method, parse them.
882 if (getLang().ObjC2)
883 MaybeParseGNUAttributes(methodAttrs);
884
885 Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent);
886 Decl *Result
887 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
888 mType, IDecl, DSRet, ReturnType,
889 selLoc, Sel, 0,
890 CParamInfo.data(), CParamInfo.size(),
891 methodAttrs.getList(), MethodImplKind,
892 false, MethodDefinition);
893 PD.complete(Result);
894 return Result;
895 }
896
897 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
898 llvm::SmallVector<Sema::ObjCArgInfo, 12> ArgInfos;
899 ParseScope PrototypeScope(this,
900 Scope::FunctionPrototypeScope|Scope::DeclScope);
901
902 AttributePool allParamAttrs(AttrFactory);
903
904 while (1) {
905 ParsedAttributes paramAttrs(AttrFactory);
906 Sema::ObjCArgInfo ArgInfo;
907
908 // Each iteration parses a single keyword argument.
909 if (Tok.isNot(tok::colon)) {
910 Diag(Tok, diag::err_expected_colon);
911 break;
912 }
913 ConsumeToken(); // Eat the ':'.
914
915 ArgInfo.Type = ParsedType();
916 if (Tok.is(tok::l_paren)) // Parse the argument type if present.
917 ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, OTN_ParameterType);
918
919 // If attributes exist before the argument name, parse them.
920 ArgInfo.ArgAttrs = 0;
921 if (getLang().ObjC2) {
922 MaybeParseGNUAttributes(paramAttrs);
923 ArgInfo.ArgAttrs = paramAttrs.getList();
924 }
925
926 // Code completion for the next piece of the selector.
927 if (Tok.is(tok::code_completion)) {
928 ConsumeCodeCompletionToken();
929 KeyIdents.push_back(SelIdent);
930 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
931 mType == tok::minus,
932 /*AtParameterName=*/true,
933 ReturnType,
934 KeyIdents.data(),
935 KeyIdents.size());
936 KeyIdents.pop_back();
937 break;
938 }
939
940 if (Tok.isNot(tok::identifier)) {
941 Diag(Tok, diag::err_expected_ident); // missing argument name.
942 break;
943 }
944
945 ArgInfo.Name = Tok.getIdentifierInfo();
946 ArgInfo.NameLoc = Tok.getLocation();
947 ConsumeToken(); // Eat the identifier.
948
949 ArgInfos.push_back(ArgInfo);
950 KeyIdents.push_back(SelIdent);
951
952 // Make sure the attributes persist.
953 allParamAttrs.takeAllFrom(paramAttrs.getPool());
954
955 // Code completion for the next piece of the selector.
956 if (Tok.is(tok::code_completion)) {
957 ConsumeCodeCompletionToken();
958 Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(),
959 mType == tok::minus,
960 /*AtParameterName=*/false,
961 ReturnType,
962 KeyIdents.data(),
963 KeyIdents.size());
964 break;
965 }
966
967 // Check for another keyword selector.
968 SourceLocation Loc;
969 SelIdent = ParseObjCSelectorPiece(Loc);
970 if (!SelIdent && Tok.isNot(tok::colon))
971 break;
972 // We have a selector or a colon, continue parsing.
973 }
974
975 bool isVariadic = false;
976
977 // Parse the (optional) parameter list.
978 while (Tok.is(tok::comma)) {
979 ConsumeToken();
980 if (Tok.is(tok::ellipsis)) {
981 isVariadic = true;
982 ConsumeToken();
983 break;
984 }
985 DeclSpec DS(AttrFactory);
986 ParseDeclarationSpecifiers(DS);
987 // Parse the declarator.
988 Declarator ParmDecl(DS, Declarator::PrototypeContext);
989 ParseDeclarator(ParmDecl);
990 IdentifierInfo *ParmII = ParmDecl.getIdentifier();
991 Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
992 CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
993 ParmDecl.getIdentifierLoc(),
994 Param,
995 0));
996
997 }
998
999 // FIXME: Add support for optional parameter list...
1000 // If attributes exist after the method, parse them.
1001 if (getLang().ObjC2)
1002 MaybeParseGNUAttributes(methodAttrs);
1003
1004 if (KeyIdents.size() == 0) {
1005 // Leave prototype scope.
1006 PrototypeScope.Exit();
1007 return 0;
1008 }
1009
1010 Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(),
1011 &KeyIdents[0]);
1012 Decl *Result
1013 = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(),
1014 mType, IDecl, DSRet, ReturnType,
1015 selLoc, Sel, &ArgInfos[0],
1016 CParamInfo.data(), CParamInfo.size(),
1017 methodAttrs.getList(),
1018 MethodImplKind, isVariadic, MethodDefinition);
1019 // Leave prototype scope.
1020 PrototypeScope.Exit();
1021
1022 PD.complete(Result);
1023 return Result;
1024 }
1025
1026 /// objc-protocol-refs:
1027 /// '<' identifier-list '>'
1028 ///
1029 bool Parser::
ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl * > & Protocols,llvm::SmallVectorImpl<SourceLocation> & ProtocolLocs,bool WarnOnDeclarations,SourceLocation & LAngleLoc,SourceLocation & EndLoc)1030 ParseObjCProtocolReferences(llvm::SmallVectorImpl<Decl *> &Protocols,
1031 llvm::SmallVectorImpl<SourceLocation> &ProtocolLocs,
1032 bool WarnOnDeclarations,
1033 SourceLocation &LAngleLoc, SourceLocation &EndLoc) {
1034 assert(Tok.is(tok::less) && "expected <");
1035
1036 LAngleLoc = ConsumeToken(); // the "<"
1037
1038 llvm::SmallVector<IdentifierLocPair, 8> ProtocolIdents;
1039
1040 while (1) {
1041 if (Tok.is(tok::code_completion)) {
1042 Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(),
1043 ProtocolIdents.size());
1044 ConsumeCodeCompletionToken();
1045 }
1046
1047 if (Tok.isNot(tok::identifier)) {
1048 Diag(Tok, diag::err_expected_ident);
1049 SkipUntil(tok::greater);
1050 return true;
1051 }
1052 ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(),
1053 Tok.getLocation()));
1054 ProtocolLocs.push_back(Tok.getLocation());
1055 ConsumeToken();
1056
1057 if (Tok.isNot(tok::comma))
1058 break;
1059 ConsumeToken();
1060 }
1061
1062 // Consume the '>'.
1063 if (Tok.isNot(tok::greater)) {
1064 Diag(Tok, diag::err_expected_greater);
1065 return true;
1066 }
1067
1068 EndLoc = ConsumeAnyToken();
1069
1070 // Convert the list of protocols identifiers into a list of protocol decls.
1071 Actions.FindProtocolDeclaration(WarnOnDeclarations,
1072 &ProtocolIdents[0], ProtocolIdents.size(),
1073 Protocols);
1074 return false;
1075 }
1076
1077 /// \brief Parse the Objective-C protocol qualifiers that follow a typename
1078 /// in a decl-specifier-seq, starting at the '<'.
ParseObjCProtocolQualifiers(DeclSpec & DS)1079 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
1080 assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
1081 assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C");
1082 SourceLocation LAngleLoc, EndProtoLoc;
1083 llvm::SmallVector<Decl *, 8> ProtocolDecl;
1084 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1085 bool Result = ParseObjCProtocolReferences(ProtocolDecl, ProtocolLocs, false,
1086 LAngleLoc, EndProtoLoc);
1087 DS.setProtocolQualifiers(ProtocolDecl.data(), ProtocolDecl.size(),
1088 ProtocolLocs.data(), LAngleLoc);
1089 if (EndProtoLoc.isValid())
1090 DS.SetRangeEnd(EndProtoLoc);
1091 return Result;
1092 }
1093
1094
1095 /// objc-class-instance-variables:
1096 /// '{' objc-instance-variable-decl-list[opt] '}'
1097 ///
1098 /// objc-instance-variable-decl-list:
1099 /// objc-visibility-spec
1100 /// objc-instance-variable-decl ';'
1101 /// ';'
1102 /// objc-instance-variable-decl-list objc-visibility-spec
1103 /// objc-instance-variable-decl-list objc-instance-variable-decl ';'
1104 /// objc-instance-variable-decl-list ';'
1105 ///
1106 /// objc-visibility-spec:
1107 /// @private
1108 /// @protected
1109 /// @public
1110 /// @package [OBJC2]
1111 ///
1112 /// objc-instance-variable-decl:
1113 /// struct-declaration
1114 ///
ParseObjCClassInstanceVariables(Decl * interfaceDecl,tok::ObjCKeywordKind visibility,SourceLocation atLoc)1115 void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl,
1116 tok::ObjCKeywordKind visibility,
1117 SourceLocation atLoc) {
1118 assert(Tok.is(tok::l_brace) && "expected {");
1119 llvm::SmallVector<Decl *, 32> AllIvarDecls;
1120
1121 ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope);
1122
1123 SourceLocation LBraceLoc = ConsumeBrace(); // the "{"
1124
1125 // While we still have something to read, read the instance variables.
1126 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
1127 // Each iteration of this loop reads one objc-instance-variable-decl.
1128
1129 // Check for extraneous top-level semicolon.
1130 if (Tok.is(tok::semi)) {
1131 Diag(Tok, diag::ext_extra_ivar_semi)
1132 << FixItHint::CreateRemoval(Tok.getLocation());
1133 ConsumeToken();
1134 continue;
1135 }
1136
1137 // Set the default visibility to private.
1138 if (Tok.is(tok::at)) { // parse objc-visibility-spec
1139 ConsumeToken(); // eat the @ sign
1140
1141 if (Tok.is(tok::code_completion)) {
1142 Actions.CodeCompleteObjCAtVisibility(getCurScope());
1143 ConsumeCodeCompletionToken();
1144 }
1145
1146 switch (Tok.getObjCKeywordID()) {
1147 case tok::objc_private:
1148 case tok::objc_public:
1149 case tok::objc_protected:
1150 case tok::objc_package:
1151 visibility = Tok.getObjCKeywordID();
1152 ConsumeToken();
1153 continue;
1154 default:
1155 Diag(Tok, diag::err_objc_illegal_visibility_spec);
1156 continue;
1157 }
1158 }
1159
1160 if (Tok.is(tok::code_completion)) {
1161 Actions.CodeCompleteOrdinaryName(getCurScope(),
1162 Sema::PCC_ObjCInstanceVariableList);
1163 ConsumeCodeCompletionToken();
1164 }
1165
1166 struct ObjCIvarCallback : FieldCallback {
1167 Parser &P;
1168 Decl *IDecl;
1169 tok::ObjCKeywordKind visibility;
1170 llvm::SmallVectorImpl<Decl *> &AllIvarDecls;
1171
1172 ObjCIvarCallback(Parser &P, Decl *IDecl, tok::ObjCKeywordKind V,
1173 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) :
1174 P(P), IDecl(IDecl), visibility(V), AllIvarDecls(AllIvarDecls) {
1175 }
1176
1177 Decl *invoke(FieldDeclarator &FD) {
1178 // Install the declarator into the interface decl.
1179 Decl *Field
1180 = P.Actions.ActOnIvar(P.getCurScope(),
1181 FD.D.getDeclSpec().getSourceRange().getBegin(),
1182 IDecl, FD.D, FD.BitfieldSize, visibility);
1183 if (Field)
1184 AllIvarDecls.push_back(Field);
1185 return Field;
1186 }
1187 } Callback(*this, interfaceDecl, visibility, AllIvarDecls);
1188
1189 // Parse all the comma separated declarators.
1190 DeclSpec DS(AttrFactory);
1191 ParseStructDeclaration(DS, Callback);
1192
1193 if (Tok.is(tok::semi)) {
1194 ConsumeToken();
1195 } else {
1196 Diag(Tok, diag::err_expected_semi_decl_list);
1197 // Skip to end of block or statement
1198 SkipUntil(tok::r_brace, true, true);
1199 }
1200 }
1201 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
1202 Actions.ActOnLastBitfield(RBraceLoc, interfaceDecl, AllIvarDecls);
1203 // Call ActOnFields() even if we don't have any decls. This is useful
1204 // for code rewriting tools that need to be aware of the empty list.
1205 Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl,
1206 AllIvarDecls.data(), AllIvarDecls.size(),
1207 LBraceLoc, RBraceLoc, 0);
1208 return;
1209 }
1210
1211 /// objc-protocol-declaration:
1212 /// objc-protocol-definition
1213 /// objc-protocol-forward-reference
1214 ///
1215 /// objc-protocol-definition:
1216 /// @protocol identifier
1217 /// objc-protocol-refs[opt]
1218 /// objc-interface-decl-list
1219 /// @end
1220 ///
1221 /// objc-protocol-forward-reference:
1222 /// @protocol identifier-list ';'
1223 ///
1224 /// "@protocol identifier ;" should be resolved as "@protocol
1225 /// identifier-list ;": objc-interface-decl-list may not start with a
1226 /// semicolon in the first alternative if objc-protocol-refs are omitted.
ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,ParsedAttributes & attrs)1227 Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
1228 ParsedAttributes &attrs) {
1229 assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
1230 "ParseObjCAtProtocolDeclaration(): Expected @protocol");
1231 ConsumeToken(); // the "protocol" identifier
1232
1233 if (Tok.is(tok::code_completion)) {
1234 Actions.CodeCompleteObjCProtocolDecl(getCurScope());
1235 ConsumeCodeCompletionToken();
1236 }
1237
1238 if (Tok.isNot(tok::identifier)) {
1239 Diag(Tok, diag::err_expected_ident); // missing protocol name.
1240 return 0;
1241 }
1242 // Save the protocol name, then consume it.
1243 IdentifierInfo *protocolName = Tok.getIdentifierInfo();
1244 SourceLocation nameLoc = ConsumeToken();
1245
1246 if (Tok.is(tok::semi)) { // forward declaration of one protocol.
1247 IdentifierLocPair ProtoInfo(protocolName, nameLoc);
1248 ConsumeToken();
1249 return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1,
1250 attrs.getList());
1251 }
1252
1253 if (Tok.is(tok::comma)) { // list of forward declarations.
1254 llvm::SmallVector<IdentifierLocPair, 8> ProtocolRefs;
1255 ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
1256
1257 // Parse the list of forward declarations.
1258 while (1) {
1259 ConsumeToken(); // the ','
1260 if (Tok.isNot(tok::identifier)) {
1261 Diag(Tok, diag::err_expected_ident);
1262 SkipUntil(tok::semi);
1263 return 0;
1264 }
1265 ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
1266 Tok.getLocation()));
1267 ConsumeToken(); // the identifier
1268
1269 if (Tok.isNot(tok::comma))
1270 break;
1271 }
1272 // Consume the ';'.
1273 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@protocol"))
1274 return 0;
1275
1276 return Actions.ActOnForwardProtocolDeclaration(AtLoc,
1277 &ProtocolRefs[0],
1278 ProtocolRefs.size(),
1279 attrs.getList());
1280 }
1281
1282 // Last, and definitely not least, parse a protocol declaration.
1283 SourceLocation LAngleLoc, EndProtoLoc;
1284
1285 llvm::SmallVector<Decl *, 8> ProtocolRefs;
1286 llvm::SmallVector<SourceLocation, 8> ProtocolLocs;
1287 if (Tok.is(tok::less) &&
1288 ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
1289 LAngleLoc, EndProtoLoc))
1290 return 0;
1291
1292 Decl *ProtoType =
1293 Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
1294 ProtocolRefs.data(),
1295 ProtocolRefs.size(),
1296 ProtocolLocs.data(),
1297 EndProtoLoc, attrs.getList());
1298 ParseObjCInterfaceDeclList(ProtoType, tok::objc_protocol);
1299 return ProtoType;
1300 }
1301
1302 /// objc-implementation:
1303 /// objc-class-implementation-prologue
1304 /// objc-category-implementation-prologue
1305 ///
1306 /// objc-class-implementation-prologue:
1307 /// @implementation identifier objc-superclass[opt]
1308 /// objc-class-instance-variables[opt]
1309 ///
1310 /// objc-category-implementation-prologue:
1311 /// @implementation identifier ( identifier )
ParseObjCAtImplementationDeclaration(SourceLocation atLoc)1312 Decl *Parser::ParseObjCAtImplementationDeclaration(
1313 SourceLocation atLoc) {
1314 assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
1315 "ParseObjCAtImplementationDeclaration(): Expected @implementation");
1316 ConsumeToken(); // the "implementation" identifier
1317
1318 // Code completion after '@implementation'.
1319 if (Tok.is(tok::code_completion)) {
1320 Actions.CodeCompleteObjCImplementationDecl(getCurScope());
1321 ConsumeCodeCompletionToken();
1322 }
1323
1324 if (Tok.isNot(tok::identifier)) {
1325 Diag(Tok, diag::err_expected_ident); // missing class or category name.
1326 return 0;
1327 }
1328 // We have a class or category name - consume it.
1329 IdentifierInfo *nameId = Tok.getIdentifierInfo();
1330 SourceLocation nameLoc = ConsumeToken(); // consume class or category name
1331
1332 if (Tok.is(tok::l_paren)) {
1333 // we have a category implementation.
1334 ConsumeParen();
1335 SourceLocation categoryLoc, rparenLoc;
1336 IdentifierInfo *categoryId = 0;
1337
1338 if (Tok.is(tok::code_completion)) {
1339 Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc);
1340 ConsumeCodeCompletionToken();
1341 }
1342
1343 if (Tok.is(tok::identifier)) {
1344 categoryId = Tok.getIdentifierInfo();
1345 categoryLoc = ConsumeToken();
1346 } else {
1347 Diag(Tok, diag::err_expected_ident); // missing category name.
1348 return 0;
1349 }
1350 if (Tok.isNot(tok::r_paren)) {
1351 Diag(Tok, diag::err_expected_rparen);
1352 SkipUntil(tok::r_paren, false); // don't stop at ';'
1353 return 0;
1354 }
1355 rparenLoc = ConsumeParen();
1356 Decl *ImplCatType = Actions.ActOnStartCategoryImplementation(
1357 atLoc, nameId, nameLoc, categoryId,
1358 categoryLoc);
1359 ObjCImpDecl = ImplCatType;
1360 PendingObjCImpDecl.push_back(ObjCImpDecl);
1361 return 0;
1362 }
1363 // We have a class implementation
1364 SourceLocation superClassLoc;
1365 IdentifierInfo *superClassId = 0;
1366 if (Tok.is(tok::colon)) {
1367 // We have a super class
1368 ConsumeToken();
1369 if (Tok.isNot(tok::identifier)) {
1370 Diag(Tok, diag::err_expected_ident); // missing super class name.
1371 return 0;
1372 }
1373 superClassId = Tok.getIdentifierInfo();
1374 superClassLoc = ConsumeToken(); // Consume super class name
1375 }
1376 Decl *ImplClsType = Actions.ActOnStartClassImplementation(
1377 atLoc, nameId, nameLoc,
1378 superClassId, superClassLoc);
1379
1380 if (Tok.is(tok::l_brace)) // we have ivars
1381 ParseObjCClassInstanceVariables(ImplClsType/*FIXME*/,
1382 tok::objc_private, atLoc);
1383 ObjCImpDecl = ImplClsType;
1384 PendingObjCImpDecl.push_back(ObjCImpDecl);
1385
1386 return 0;
1387 }
1388
ParseObjCAtEndDeclaration(SourceRange atEnd)1389 Decl *Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) {
1390 assert(Tok.isObjCAtKeyword(tok::objc_end) &&
1391 "ParseObjCAtEndDeclaration(): Expected @end");
1392 Decl *Result = ObjCImpDecl;
1393 ConsumeToken(); // the "end" identifier
1394 if (ObjCImpDecl) {
1395 Actions.ActOnAtEnd(getCurScope(), atEnd, ObjCImpDecl);
1396 ObjCImpDecl = 0;
1397 PendingObjCImpDecl.pop_back();
1398 }
1399 else {
1400 // missing @implementation
1401 Diag(atEnd.getBegin(), diag::err_expected_implementation);
1402 }
1403 return Result;
1404 }
1405
FinishPendingObjCActions()1406 Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
1407 Actions.DiagnoseUseOfUnimplementedSelectors();
1408 if (PendingObjCImpDecl.empty())
1409 return Actions.ConvertDeclToDeclGroup(0);
1410 Decl *ImpDecl = PendingObjCImpDecl.pop_back_val();
1411 Actions.ActOnAtEnd(getCurScope(), SourceRange(), ImpDecl);
1412 return Actions.ConvertDeclToDeclGroup(ImpDecl);
1413 }
1414
1415 /// compatibility-alias-decl:
1416 /// @compatibility_alias alias-name class-name ';'
1417 ///
ParseObjCAtAliasDeclaration(SourceLocation atLoc)1418 Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) {
1419 assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) &&
1420 "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias");
1421 ConsumeToken(); // consume compatibility_alias
1422 if (Tok.isNot(tok::identifier)) {
1423 Diag(Tok, diag::err_expected_ident);
1424 return 0;
1425 }
1426 IdentifierInfo *aliasId = Tok.getIdentifierInfo();
1427 SourceLocation aliasLoc = ConsumeToken(); // consume alias-name
1428 if (Tok.isNot(tok::identifier)) {
1429 Diag(Tok, diag::err_expected_ident);
1430 return 0;
1431 }
1432 IdentifierInfo *classId = Tok.getIdentifierInfo();
1433 SourceLocation classLoc = ConsumeToken(); // consume class-name;
1434 ExpectAndConsume(tok::semi, diag::err_expected_semi_after,
1435 "@compatibility_alias");
1436 return Actions.ActOnCompatiblityAlias(atLoc, aliasId, aliasLoc,
1437 classId, classLoc);
1438 }
1439
1440 /// property-synthesis:
1441 /// @synthesize property-ivar-list ';'
1442 ///
1443 /// property-ivar-list:
1444 /// property-ivar
1445 /// property-ivar-list ',' property-ivar
1446 ///
1447 /// property-ivar:
1448 /// identifier
1449 /// identifier '=' identifier
1450 ///
ParseObjCPropertySynthesize(SourceLocation atLoc)1451 Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) {
1452 assert(Tok.isObjCAtKeyword(tok::objc_synthesize) &&
1453 "ParseObjCPropertyDynamic(): Expected '@synthesize'");
1454 ConsumeToken(); // consume synthesize
1455
1456 while (true) {
1457 if (Tok.is(tok::code_completion)) {
1458 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1459 ConsumeCodeCompletionToken();
1460 }
1461
1462 if (Tok.isNot(tok::identifier)) {
1463 Diag(Tok, diag::err_synthesized_property_name);
1464 SkipUntil(tok::semi);
1465 return 0;
1466 }
1467
1468 IdentifierInfo *propertyIvar = 0;
1469 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1470 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1471 SourceLocation propertyIvarLoc;
1472 if (Tok.is(tok::equal)) {
1473 // property '=' ivar-name
1474 ConsumeToken(); // consume '='
1475
1476 if (Tok.is(tok::code_completion)) {
1477 Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId,
1478 ObjCImpDecl);
1479 ConsumeCodeCompletionToken();
1480 }
1481
1482 if (Tok.isNot(tok::identifier)) {
1483 Diag(Tok, diag::err_expected_ident);
1484 break;
1485 }
1486 propertyIvar = Tok.getIdentifierInfo();
1487 propertyIvarLoc = ConsumeToken(); // consume ivar-name
1488 }
1489 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, ObjCImpDecl,
1490 propertyId, propertyIvar, propertyIvarLoc);
1491 if (Tok.isNot(tok::comma))
1492 break;
1493 ConsumeToken(); // consume ','
1494 }
1495 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@synthesize");
1496 return 0;
1497 }
1498
1499 /// property-dynamic:
1500 /// @dynamic property-list
1501 ///
1502 /// property-list:
1503 /// identifier
1504 /// property-list ',' identifier
1505 ///
ParseObjCPropertyDynamic(SourceLocation atLoc)1506 Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) {
1507 assert(Tok.isObjCAtKeyword(tok::objc_dynamic) &&
1508 "ParseObjCPropertyDynamic(): Expected '@dynamic'");
1509 ConsumeToken(); // consume dynamic
1510 while (true) {
1511 if (Tok.is(tok::code_completion)) {
1512 Actions.CodeCompleteObjCPropertyDefinition(getCurScope(), ObjCImpDecl);
1513 ConsumeCodeCompletionToken();
1514 }
1515
1516 if (Tok.isNot(tok::identifier)) {
1517 Diag(Tok, diag::err_expected_ident);
1518 SkipUntil(tok::semi);
1519 return 0;
1520 }
1521
1522 IdentifierInfo *propertyId = Tok.getIdentifierInfo();
1523 SourceLocation propertyLoc = ConsumeToken(); // consume property name
1524 Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, ObjCImpDecl,
1525 propertyId, 0, SourceLocation());
1526
1527 if (Tok.isNot(tok::comma))
1528 break;
1529 ConsumeToken(); // consume ','
1530 }
1531 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@dynamic");
1532 return 0;
1533 }
1534
1535 /// objc-throw-statement:
1536 /// throw expression[opt];
1537 ///
ParseObjCThrowStmt(SourceLocation atLoc)1538 StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) {
1539 ExprResult Res;
1540 ConsumeToken(); // consume throw
1541 if (Tok.isNot(tok::semi)) {
1542 Res = ParseExpression();
1543 if (Res.isInvalid()) {
1544 SkipUntil(tok::semi);
1545 return StmtError();
1546 }
1547 }
1548 // consume ';'
1549 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@throw");
1550 return Actions.ActOnObjCAtThrowStmt(atLoc, Res.take(), getCurScope());
1551 }
1552
1553 /// objc-synchronized-statement:
1554 /// @synchronized '(' expression ')' compound-statement
1555 ///
1556 StmtResult
ParseObjCSynchronizedStmt(SourceLocation atLoc)1557 Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) {
1558 ConsumeToken(); // consume synchronized
1559 if (Tok.isNot(tok::l_paren)) {
1560 Diag(Tok, diag::err_expected_lparen_after) << "@synchronized";
1561 return StmtError();
1562 }
1563 ConsumeParen(); // '('
1564 ExprResult Res(ParseExpression());
1565 if (Res.isInvalid()) {
1566 SkipUntil(tok::semi);
1567 return StmtError();
1568 }
1569 if (Tok.isNot(tok::r_paren)) {
1570 Diag(Tok, diag::err_expected_lbrace);
1571 return StmtError();
1572 }
1573 ConsumeParen(); // ')'
1574 if (Tok.isNot(tok::l_brace)) {
1575 Diag(Tok, diag::err_expected_lbrace);
1576 return StmtError();
1577 }
1578 // Enter a scope to hold everything within the compound stmt. Compound
1579 // statements can always hold declarations.
1580 ParseScope BodyScope(this, Scope::DeclScope);
1581
1582 StmtResult SynchBody(ParseCompoundStatementBody());
1583
1584 BodyScope.Exit();
1585 if (SynchBody.isInvalid())
1586 SynchBody = Actions.ActOnNullStmt(Tok.getLocation());
1587 return Actions.ActOnObjCAtSynchronizedStmt(atLoc, Res.take(), SynchBody.take());
1588 }
1589
1590 /// objc-try-catch-statement:
1591 /// @try compound-statement objc-catch-list[opt]
1592 /// @try compound-statement objc-catch-list[opt] @finally compound-statement
1593 ///
1594 /// objc-catch-list:
1595 /// @catch ( parameter-declaration ) compound-statement
1596 /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
1597 /// catch-parameter-declaration:
1598 /// parameter-declaration
1599 /// '...' [OBJC2]
1600 ///
ParseObjCTryStmt(SourceLocation atLoc)1601 StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) {
1602 bool catch_or_finally_seen = false;
1603
1604 ConsumeToken(); // consume try
1605 if (Tok.isNot(tok::l_brace)) {
1606 Diag(Tok, diag::err_expected_lbrace);
1607 return StmtError();
1608 }
1609 StmtVector CatchStmts(Actions);
1610 StmtResult FinallyStmt;
1611 ParseScope TryScope(this, Scope::DeclScope);
1612 StmtResult TryBody(ParseCompoundStatementBody());
1613 TryScope.Exit();
1614 if (TryBody.isInvalid())
1615 TryBody = Actions.ActOnNullStmt(Tok.getLocation());
1616
1617 while (Tok.is(tok::at)) {
1618 // At this point, we need to lookahead to determine if this @ is the start
1619 // of an @catch or @finally. We don't want to consume the @ token if this
1620 // is an @try or @encode or something else.
1621 Token AfterAt = GetLookAheadToken(1);
1622 if (!AfterAt.isObjCAtKeyword(tok::objc_catch) &&
1623 !AfterAt.isObjCAtKeyword(tok::objc_finally))
1624 break;
1625
1626 SourceLocation AtCatchFinallyLoc = ConsumeToken();
1627 if (Tok.isObjCAtKeyword(tok::objc_catch)) {
1628 Decl *FirstPart = 0;
1629 ConsumeToken(); // consume catch
1630 if (Tok.is(tok::l_paren)) {
1631 ConsumeParen();
1632 ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope);
1633 if (Tok.isNot(tok::ellipsis)) {
1634 DeclSpec DS(AttrFactory);
1635 ParseDeclarationSpecifiers(DS);
1636 Declarator ParmDecl(DS, Declarator::ObjCCatchContext);
1637 ParseDeclarator(ParmDecl);
1638
1639 // Inform the actions module about the declarator, so it
1640 // gets added to the current scope.
1641 FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl);
1642 } else
1643 ConsumeToken(); // consume '...'
1644
1645 SourceLocation RParenLoc;
1646
1647 if (Tok.is(tok::r_paren))
1648 RParenLoc = ConsumeParen();
1649 else // Skip over garbage, until we get to ')'. Eat the ')'.
1650 SkipUntil(tok::r_paren, true, false);
1651
1652 StmtResult CatchBody(true);
1653 if (Tok.is(tok::l_brace))
1654 CatchBody = ParseCompoundStatementBody();
1655 else
1656 Diag(Tok, diag::err_expected_lbrace);
1657 if (CatchBody.isInvalid())
1658 CatchBody = Actions.ActOnNullStmt(Tok.getLocation());
1659
1660 StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc,
1661 RParenLoc,
1662 FirstPart,
1663 CatchBody.take());
1664 if (!Catch.isInvalid())
1665 CatchStmts.push_back(Catch.release());
1666
1667 } else {
1668 Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after)
1669 << "@catch clause";
1670 return StmtError();
1671 }
1672 catch_or_finally_seen = true;
1673 } else {
1674 assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?");
1675 ConsumeToken(); // consume finally
1676 ParseScope FinallyScope(this, Scope::DeclScope);
1677
1678 StmtResult FinallyBody(true);
1679 if (Tok.is(tok::l_brace))
1680 FinallyBody = ParseCompoundStatementBody();
1681 else
1682 Diag(Tok, diag::err_expected_lbrace);
1683 if (FinallyBody.isInvalid())
1684 FinallyBody = Actions.ActOnNullStmt(Tok.getLocation());
1685 FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc,
1686 FinallyBody.take());
1687 catch_or_finally_seen = true;
1688 break;
1689 }
1690 }
1691 if (!catch_or_finally_seen) {
1692 Diag(atLoc, diag::err_missing_catch_finally);
1693 return StmtError();
1694 }
1695
1696 return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.take(),
1697 move_arg(CatchStmts),
1698 FinallyStmt.take());
1699 }
1700
1701 /// objc-autoreleasepool-statement:
1702 /// @autoreleasepool compound-statement
1703 ///
1704 StmtResult
ParseObjCAutoreleasePoolStmt(SourceLocation atLoc)1705 Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) {
1706 ConsumeToken(); // consume autoreleasepool
1707 if (Tok.isNot(tok::l_brace)) {
1708 Diag(Tok, diag::err_expected_lbrace);
1709 return StmtError();
1710 }
1711 // Enter a scope to hold everything within the compound stmt. Compound
1712 // statements can always hold declarations.
1713 ParseScope BodyScope(this, Scope::DeclScope);
1714
1715 StmtResult AutoreleasePoolBody(ParseCompoundStatementBody());
1716
1717 BodyScope.Exit();
1718 if (AutoreleasePoolBody.isInvalid())
1719 AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation());
1720 return Actions.ActOnObjCAutoreleasePoolStmt(atLoc,
1721 AutoreleasePoolBody.take());
1722 }
1723
1724 /// objc-method-def: objc-method-proto ';'[opt] '{' body '}'
1725 ///
ParseObjCMethodDefinition()1726 Decl *Parser::ParseObjCMethodDefinition() {
1727 Decl *MDecl = ParseObjCMethodPrototype(ObjCImpDecl);
1728
1729 PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(),
1730 "parsing Objective-C method");
1731
1732 // parse optional ';'
1733 if (Tok.is(tok::semi)) {
1734 if (ObjCImpDecl) {
1735 Diag(Tok, diag::warn_semicolon_before_method_body)
1736 << FixItHint::CreateRemoval(Tok.getLocation());
1737 }
1738 ConsumeToken();
1739 }
1740
1741 // We should have an opening brace now.
1742 if (Tok.isNot(tok::l_brace)) {
1743 Diag(Tok, diag::err_expected_method_body);
1744
1745 // Skip over garbage, until we get to '{'. Don't eat the '{'.
1746 SkipUntil(tok::l_brace, true, true);
1747
1748 // If we didn't find the '{', bail out.
1749 if (Tok.isNot(tok::l_brace))
1750 return 0;
1751 }
1752 SourceLocation BraceLoc = Tok.getLocation();
1753
1754 // Enter a scope for the method body.
1755 ParseScope BodyScope(this,
1756 Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope);
1757
1758 // Tell the actions module that we have entered a method definition with the
1759 // specified Declarator for the method.
1760 Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
1761
1762 if (PP.isCodeCompletionEnabled()) {
1763 if (trySkippingFunctionBodyForCodeCompletion()) {
1764 BodyScope.Exit();
1765 return Actions.ActOnFinishFunctionBody(MDecl, 0);
1766 }
1767 }
1768
1769 StmtResult FnBody(ParseCompoundStatementBody());
1770
1771 // If the function body could not be parsed, make a bogus compoundstmt.
1772 if (FnBody.isInvalid())
1773 FnBody = Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
1774 MultiStmtArg(Actions), false);
1775
1776 // Leave the function body scope.
1777 BodyScope.Exit();
1778
1779 // TODO: Pass argument information.
1780 Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
1781 return MDecl;
1782 }
1783
ParseObjCAtStatement(SourceLocation AtLoc)1784 StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) {
1785 if (Tok.is(tok::code_completion)) {
1786 Actions.CodeCompleteObjCAtStatement(getCurScope());
1787 ConsumeCodeCompletionToken();
1788 return StmtError();
1789 }
1790
1791 if (Tok.isObjCAtKeyword(tok::objc_try))
1792 return ParseObjCTryStmt(AtLoc);
1793
1794 if (Tok.isObjCAtKeyword(tok::objc_throw))
1795 return ParseObjCThrowStmt(AtLoc);
1796
1797 if (Tok.isObjCAtKeyword(tok::objc_synchronized))
1798 return ParseObjCSynchronizedStmt(AtLoc);
1799
1800 if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool))
1801 return ParseObjCAutoreleasePoolStmt(AtLoc);
1802
1803 ExprResult Res(ParseExpressionWithLeadingAt(AtLoc));
1804 if (Res.isInvalid()) {
1805 // If the expression is invalid, skip ahead to the next semicolon. Not
1806 // doing this opens us up to the possibility of infinite loops if
1807 // ParseExpression does not consume any tokens.
1808 SkipUntil(tok::semi);
1809 return StmtError();
1810 }
1811
1812 // Otherwise, eat the semicolon.
1813 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1814 return Actions.ActOnExprStmt(Actions.MakeFullExpr(Res.take()));
1815 }
1816
ParseObjCAtExpression(SourceLocation AtLoc)1817 ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) {
1818 switch (Tok.getKind()) {
1819 case tok::code_completion:
1820 Actions.CodeCompleteObjCAtExpression(getCurScope());
1821 ConsumeCodeCompletionToken();
1822 return ExprError();
1823
1824 case tok::string_literal: // primary-expression: string-literal
1825 case tok::wide_string_literal:
1826 return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
1827 default:
1828 if (Tok.getIdentifierInfo() == 0)
1829 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1830
1831 switch (Tok.getIdentifierInfo()->getObjCKeywordID()) {
1832 case tok::objc_encode:
1833 return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc));
1834 case tok::objc_protocol:
1835 return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc));
1836 case tok::objc_selector:
1837 return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc));
1838 default:
1839 return ExprError(Diag(AtLoc, diag::err_unexpected_at));
1840 }
1841 }
1842 }
1843
1844 /// \brirg Parse the receiver of an Objective-C++ message send.
1845 ///
1846 /// This routine parses the receiver of a message send in
1847 /// Objective-C++ either as a type or as an expression. Note that this
1848 /// routine must not be called to parse a send to 'super', since it
1849 /// has no way to return such a result.
1850 ///
1851 /// \param IsExpr Whether the receiver was parsed as an expression.
1852 ///
1853 /// \param TypeOrExpr If the receiver was parsed as an expression (\c
1854 /// IsExpr is true), the parsed expression. If the receiver was parsed
1855 /// as a type (\c IsExpr is false), the parsed type.
1856 ///
1857 /// \returns True if an error occurred during parsing or semantic
1858 /// analysis, in which case the arguments do not have valid
1859 /// values. Otherwise, returns false for a successful parse.
1860 ///
1861 /// objc-receiver: [C++]
1862 /// 'super' [not parsed here]
1863 /// expression
1864 /// simple-type-specifier
1865 /// typename-specifier
ParseObjCXXMessageReceiver(bool & IsExpr,void * & TypeOrExpr)1866 bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) {
1867 InMessageExpressionRAIIObject InMessage(*this, true);
1868
1869 if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
1870 Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope))
1871 TryAnnotateTypeOrScopeToken();
1872
1873 if (!isCXXSimpleTypeSpecifier()) {
1874 // objc-receiver:
1875 // expression
1876 ExprResult Receiver = ParseExpression();
1877 if (Receiver.isInvalid())
1878 return true;
1879
1880 IsExpr = true;
1881 TypeOrExpr = Receiver.take();
1882 return false;
1883 }
1884
1885 // objc-receiver:
1886 // typename-specifier
1887 // simple-type-specifier
1888 // expression (that starts with one of the above)
1889 DeclSpec DS(AttrFactory);
1890 ParseCXXSimpleTypeSpecifier(DS);
1891
1892 if (Tok.is(tok::l_paren)) {
1893 // If we see an opening parentheses at this point, we are
1894 // actually parsing an expression that starts with a
1895 // function-style cast, e.g.,
1896 //
1897 // postfix-expression:
1898 // simple-type-specifier ( expression-list [opt] )
1899 // typename-specifier ( expression-list [opt] )
1900 //
1901 // Parse the remainder of this case, then the (optional)
1902 // postfix-expression suffix, followed by the (optional)
1903 // right-hand side of the binary expression. We have an
1904 // instance method.
1905 ExprResult Receiver = ParseCXXTypeConstructExpression(DS);
1906 if (!Receiver.isInvalid())
1907 Receiver = ParsePostfixExpressionSuffix(Receiver.take());
1908 if (!Receiver.isInvalid())
1909 Receiver = ParseRHSOfBinaryExpression(Receiver.take(), prec::Comma);
1910 if (Receiver.isInvalid())
1911 return true;
1912
1913 IsExpr = true;
1914 TypeOrExpr = Receiver.take();
1915 return false;
1916 }
1917
1918 // We have a class message. Turn the simple-type-specifier or
1919 // typename-specifier we parsed into a type and parse the
1920 // remainder of the class message.
1921 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1922 TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1923 if (Type.isInvalid())
1924 return true;
1925
1926 IsExpr = false;
1927 TypeOrExpr = Type.get().getAsOpaquePtr();
1928 return false;
1929 }
1930
1931 /// \brief Determine whether the parser is currently referring to a an
1932 /// Objective-C message send, using a simplified heuristic to avoid overhead.
1933 ///
1934 /// This routine will only return true for a subset of valid message-send
1935 /// expressions.
isSimpleObjCMessageExpression()1936 bool Parser::isSimpleObjCMessageExpression() {
1937 assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
1938 "Incorrect start for isSimpleObjCMessageExpression");
1939 return GetLookAheadToken(1).is(tok::identifier) &&
1940 GetLookAheadToken(2).is(tok::identifier);
1941 }
1942
isStartOfObjCClassMessageMissingOpenBracket()1943 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
1944 if (!getLang().ObjC1 || !NextToken().is(tok::identifier) ||
1945 InMessageExpression)
1946 return false;
1947
1948
1949 ParsedType Type;
1950
1951 if (Tok.is(tok::annot_typename))
1952 Type = getTypeAnnotation(Tok);
1953 else if (Tok.is(tok::identifier))
1954 Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(),
1955 getCurScope());
1956 else
1957 return false;
1958
1959 if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) {
1960 const Token &AfterNext = GetLookAheadToken(2);
1961 if (AfterNext.is(tok::colon) || AfterNext.is(tok::r_square)) {
1962 if (Tok.is(tok::identifier))
1963 TryAnnotateTypeOrScopeToken();
1964
1965 return Tok.is(tok::annot_typename);
1966 }
1967 }
1968
1969 return false;
1970 }
1971
1972 /// objc-message-expr:
1973 /// '[' objc-receiver objc-message-args ']'
1974 ///
1975 /// objc-receiver: [C]
1976 /// 'super'
1977 /// expression
1978 /// class-name
1979 /// type-name
1980 ///
ParseObjCMessageExpression()1981 ExprResult Parser::ParseObjCMessageExpression() {
1982 assert(Tok.is(tok::l_square) && "'[' expected");
1983 SourceLocation LBracLoc = ConsumeBracket(); // consume '['
1984
1985 if (Tok.is(tok::code_completion)) {
1986 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
1987 ConsumeCodeCompletionToken();
1988 SkipUntil(tok::r_square);
1989 return ExprError();
1990 }
1991
1992 InMessageExpressionRAIIObject InMessage(*this, true);
1993
1994 if (getLang().CPlusPlus) {
1995 // We completely separate the C and C++ cases because C++ requires
1996 // more complicated (read: slower) parsing.
1997
1998 // Handle send to super.
1999 // FIXME: This doesn't benefit from the same typo-correction we
2000 // get in Objective-C.
2001 if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super &&
2002 NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope())
2003 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2004 ParsedType(), 0);
2005
2006 // Parse the receiver, which is either a type or an expression.
2007 bool IsExpr;
2008 void *TypeOrExpr = NULL;
2009 if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) {
2010 SkipUntil(tok::r_square);
2011 return ExprError();
2012 }
2013
2014 if (IsExpr)
2015 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2016 ParsedType(),
2017 static_cast<Expr*>(TypeOrExpr));
2018
2019 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2020 ParsedType::getFromOpaquePtr(TypeOrExpr),
2021 0);
2022 }
2023
2024 if (Tok.is(tok::identifier)) {
2025 IdentifierInfo *Name = Tok.getIdentifierInfo();
2026 SourceLocation NameLoc = Tok.getLocation();
2027 ParsedType ReceiverType;
2028 switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc,
2029 Name == Ident_super,
2030 NextToken().is(tok::period),
2031 ReceiverType)) {
2032 case Sema::ObjCSuperMessage:
2033 return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(),
2034 ParsedType(), 0);
2035
2036 case Sema::ObjCClassMessage:
2037 if (!ReceiverType) {
2038 SkipUntil(tok::r_square);
2039 return ExprError();
2040 }
2041
2042 ConsumeToken(); // the type name
2043
2044 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2045 ReceiverType, 0);
2046
2047 case Sema::ObjCInstanceMessage:
2048 // Fall through to parse an expression.
2049 break;
2050 }
2051 }
2052
2053 // Otherwise, an arbitrary expression can be the receiver of a send.
2054 ExprResult Res(ParseExpression());
2055 if (Res.isInvalid()) {
2056 SkipUntil(tok::r_square);
2057 return move(Res);
2058 }
2059
2060 return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(),
2061 ParsedType(), Res.take());
2062 }
2063
2064 /// \brief Parse the remainder of an Objective-C message following the
2065 /// '[' objc-receiver.
2066 ///
2067 /// This routine handles sends to super, class messages (sent to a
2068 /// class name), and instance messages (sent to an object), and the
2069 /// target is represented by \p SuperLoc, \p ReceiverType, or \p
2070 /// ReceiverExpr, respectively. Only one of these parameters may have
2071 /// a valid value.
2072 ///
2073 /// \param LBracLoc The location of the opening '['.
2074 ///
2075 /// \param SuperLoc If this is a send to 'super', the location of the
2076 /// 'super' keyword that indicates a send to the superclass.
2077 ///
2078 /// \param ReceiverType If this is a class message, the type of the
2079 /// class we are sending a message to.
2080 ///
2081 /// \param ReceiverExpr If this is an instance message, the expression
2082 /// used to compute the receiver object.
2083 ///
2084 /// objc-message-args:
2085 /// objc-selector
2086 /// objc-keywordarg-list
2087 ///
2088 /// objc-keywordarg-list:
2089 /// objc-keywordarg
2090 /// objc-keywordarg-list objc-keywordarg
2091 ///
2092 /// objc-keywordarg:
2093 /// selector-name[opt] ':' objc-keywordexpr
2094 ///
2095 /// objc-keywordexpr:
2096 /// nonempty-expr-list
2097 ///
2098 /// nonempty-expr-list:
2099 /// assignment-expression
2100 /// nonempty-expr-list , assignment-expression
2101 ///
2102 ExprResult
ParseObjCMessageExpressionBody(SourceLocation LBracLoc,SourceLocation SuperLoc,ParsedType ReceiverType,ExprArg ReceiverExpr)2103 Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc,
2104 SourceLocation SuperLoc,
2105 ParsedType ReceiverType,
2106 ExprArg ReceiverExpr) {
2107 InMessageExpressionRAIIObject InMessage(*this, true);
2108
2109 if (Tok.is(tok::code_completion)) {
2110 if (SuperLoc.isValid())
2111 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, 0, 0,
2112 false);
2113 else if (ReceiverType)
2114 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, 0, 0,
2115 false);
2116 else
2117 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2118 0, 0, false);
2119 ConsumeCodeCompletionToken();
2120 }
2121
2122 // Parse objc-selector
2123 SourceLocation Loc;
2124 IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc);
2125
2126 SourceLocation SelectorLoc = Loc;
2127
2128 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2129 ExprVector KeyExprs(Actions);
2130
2131 if (Tok.is(tok::colon)) {
2132 while (1) {
2133 // Each iteration parses a single keyword argument.
2134 KeyIdents.push_back(selIdent);
2135
2136 if (Tok.isNot(tok::colon)) {
2137 Diag(Tok, diag::err_expected_colon);
2138 // We must manually skip to a ']', otherwise the expression skipper will
2139 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2140 // the enclosing expression.
2141 SkipUntil(tok::r_square);
2142 return ExprError();
2143 }
2144
2145 ConsumeToken(); // Eat the ':'.
2146 /// Parse the expression after ':'
2147
2148 if (Tok.is(tok::code_completion)) {
2149 if (SuperLoc.isValid())
2150 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2151 KeyIdents.data(),
2152 KeyIdents.size(),
2153 /*AtArgumentEpression=*/true);
2154 else if (ReceiverType)
2155 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2156 KeyIdents.data(),
2157 KeyIdents.size(),
2158 /*AtArgumentEpression=*/true);
2159 else
2160 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2161 KeyIdents.data(),
2162 KeyIdents.size(),
2163 /*AtArgumentEpression=*/true);
2164
2165 ConsumeCodeCompletionToken();
2166 SkipUntil(tok::r_square);
2167 return ExprError();
2168 }
2169
2170 ExprResult Res(ParseAssignmentExpression());
2171 if (Res.isInvalid()) {
2172 // We must manually skip to a ']', otherwise the expression skipper will
2173 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2174 // the enclosing expression.
2175 SkipUntil(tok::r_square);
2176 return move(Res);
2177 }
2178
2179 // We have a valid expression.
2180 KeyExprs.push_back(Res.release());
2181
2182 // Code completion after each argument.
2183 if (Tok.is(tok::code_completion)) {
2184 if (SuperLoc.isValid())
2185 Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc,
2186 KeyIdents.data(),
2187 KeyIdents.size(),
2188 /*AtArgumentEpression=*/false);
2189 else if (ReceiverType)
2190 Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType,
2191 KeyIdents.data(),
2192 KeyIdents.size(),
2193 /*AtArgumentEpression=*/false);
2194 else
2195 Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr,
2196 KeyIdents.data(),
2197 KeyIdents.size(),
2198 /*AtArgumentEpression=*/false);
2199 ConsumeCodeCompletionToken();
2200 SkipUntil(tok::r_square);
2201 return ExprError();
2202 }
2203
2204 // Check for another keyword selector.
2205 selIdent = ParseObjCSelectorPiece(Loc);
2206 if (!selIdent && Tok.isNot(tok::colon))
2207 break;
2208 // We have a selector or a colon, continue parsing.
2209 }
2210 // Parse the, optional, argument list, comma separated.
2211 while (Tok.is(tok::comma)) {
2212 ConsumeToken(); // Eat the ','.
2213 /// Parse the expression after ','
2214 ExprResult Res(ParseAssignmentExpression());
2215 if (Res.isInvalid()) {
2216 // We must manually skip to a ']', otherwise the expression skipper will
2217 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2218 // the enclosing expression.
2219 SkipUntil(tok::r_square);
2220 return move(Res);
2221 }
2222
2223 // We have a valid expression.
2224 KeyExprs.push_back(Res.release());
2225 }
2226 } else if (!selIdent) {
2227 Diag(Tok, diag::err_expected_ident); // missing selector name.
2228
2229 // We must manually skip to a ']', otherwise the expression skipper will
2230 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2231 // the enclosing expression.
2232 SkipUntil(tok::r_square);
2233 return ExprError();
2234 }
2235
2236 if (Tok.isNot(tok::r_square)) {
2237 if (Tok.is(tok::identifier))
2238 Diag(Tok, diag::err_expected_colon);
2239 else
2240 Diag(Tok, diag::err_expected_rsquare);
2241 // We must manually skip to a ']', otherwise the expression skipper will
2242 // stop at the ']' when it skips to the ';'. We want it to skip beyond
2243 // the enclosing expression.
2244 SkipUntil(tok::r_square);
2245 return ExprError();
2246 }
2247
2248 SourceLocation RBracLoc = ConsumeBracket(); // consume ']'
2249
2250 unsigned nKeys = KeyIdents.size();
2251 if (nKeys == 0)
2252 KeyIdents.push_back(selIdent);
2253 Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]);
2254
2255 if (SuperLoc.isValid())
2256 return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel,
2257 LBracLoc, SelectorLoc, RBracLoc,
2258 MultiExprArg(Actions,
2259 KeyExprs.take(),
2260 KeyExprs.size()));
2261 else if (ReceiverType)
2262 return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel,
2263 LBracLoc, SelectorLoc, RBracLoc,
2264 MultiExprArg(Actions,
2265 KeyExprs.take(),
2266 KeyExprs.size()));
2267 return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel,
2268 LBracLoc, SelectorLoc, RBracLoc,
2269 MultiExprArg(Actions,
2270 KeyExprs.take(),
2271 KeyExprs.size()));
2272 }
2273
ParseObjCStringLiteral(SourceLocation AtLoc)2274 ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) {
2275 ExprResult Res(ParseStringLiteralExpression());
2276 if (Res.isInvalid()) return move(Res);
2277
2278 // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string
2279 // expressions. At this point, we know that the only valid thing that starts
2280 // with '@' is an @"".
2281 llvm::SmallVector<SourceLocation, 4> AtLocs;
2282 ExprVector AtStrings(Actions);
2283 AtLocs.push_back(AtLoc);
2284 AtStrings.push_back(Res.release());
2285
2286 while (Tok.is(tok::at)) {
2287 AtLocs.push_back(ConsumeToken()); // eat the @.
2288
2289 // Invalid unless there is a string literal.
2290 if (!isTokenStringLiteral())
2291 return ExprError(Diag(Tok, diag::err_objc_concat_string));
2292
2293 ExprResult Lit(ParseStringLiteralExpression());
2294 if (Lit.isInvalid())
2295 return move(Lit);
2296
2297 AtStrings.push_back(Lit.release());
2298 }
2299
2300 return Owned(Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.take(),
2301 AtStrings.size()));
2302 }
2303
2304 /// objc-encode-expression:
2305 /// @encode ( type-name )
2306 ExprResult
ParseObjCEncodeExpression(SourceLocation AtLoc)2307 Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) {
2308 assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!");
2309
2310 SourceLocation EncLoc = ConsumeToken();
2311
2312 if (Tok.isNot(tok::l_paren))
2313 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode");
2314
2315 SourceLocation LParenLoc = ConsumeParen();
2316
2317 TypeResult Ty = ParseTypeName();
2318
2319 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2320
2321 if (Ty.isInvalid())
2322 return ExprError();
2323
2324 return Owned(Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, LParenLoc,
2325 Ty.get(), RParenLoc));
2326 }
2327
2328 /// objc-protocol-expression
2329 /// @protocol ( protocol-name )
2330 ExprResult
ParseObjCProtocolExpression(SourceLocation AtLoc)2331 Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) {
2332 SourceLocation ProtoLoc = ConsumeToken();
2333
2334 if (Tok.isNot(tok::l_paren))
2335 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol");
2336
2337 SourceLocation LParenLoc = ConsumeParen();
2338
2339 if (Tok.isNot(tok::identifier))
2340 return ExprError(Diag(Tok, diag::err_expected_ident));
2341
2342 IdentifierInfo *protocolId = Tok.getIdentifierInfo();
2343 ConsumeToken();
2344
2345 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2346
2347 return Owned(Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc,
2348 LParenLoc, RParenLoc));
2349 }
2350
2351 /// objc-selector-expression
2352 /// @selector '(' objc-keyword-selector ')'
ParseObjCSelectorExpression(SourceLocation AtLoc)2353 ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) {
2354 SourceLocation SelectorLoc = ConsumeToken();
2355
2356 if (Tok.isNot(tok::l_paren))
2357 return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector");
2358
2359 llvm::SmallVector<IdentifierInfo *, 12> KeyIdents;
2360 SourceLocation LParenLoc = ConsumeParen();
2361 SourceLocation sLoc;
2362
2363 if (Tok.is(tok::code_completion)) {
2364 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2365 KeyIdents.size());
2366 ConsumeCodeCompletionToken();
2367 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2368 return ExprError();
2369 }
2370
2371 IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc);
2372 if (!SelIdent && // missing selector name.
2373 Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2374 return ExprError(Diag(Tok, diag::err_expected_ident));
2375
2376 KeyIdents.push_back(SelIdent);
2377 unsigned nColons = 0;
2378 if (Tok.isNot(tok::r_paren)) {
2379 while (1) {
2380 if (Tok.is(tok::coloncolon)) { // Handle :: in C++.
2381 ++nColons;
2382 KeyIdents.push_back(0);
2383 } else if (Tok.isNot(tok::colon))
2384 return ExprError(Diag(Tok, diag::err_expected_colon));
2385
2386 ++nColons;
2387 ConsumeToken(); // Eat the ':' or '::'.
2388 if (Tok.is(tok::r_paren))
2389 break;
2390
2391 if (Tok.is(tok::code_completion)) {
2392 Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents.data(),
2393 KeyIdents.size());
2394 ConsumeCodeCompletionToken();
2395 MatchRHSPunctuation(tok::r_paren, LParenLoc);
2396 return ExprError();
2397 }
2398
2399 // Check for another keyword selector.
2400 SourceLocation Loc;
2401 SelIdent = ParseObjCSelectorPiece(Loc);
2402 KeyIdents.push_back(SelIdent);
2403 if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon))
2404 break;
2405 }
2406 }
2407 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
2408 Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]);
2409 return Owned(Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc,
2410 LParenLoc, RParenLoc));
2411 }
2412