SemaExprObjC.cpp revision 60d7b3a319d84d688752be3870615ac0f111fb16
1//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
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 semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeLoc.h"
21#include "llvm/ADT/SmallString.h"
22#include "clang/Lex/Preprocessor.h"
23
24using namespace clang;
25
26Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
27                                              ExprTy **strings,
28                                              unsigned NumStrings) {
29  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
30
31  // Most ObjC strings are formed out of a single piece.  However, we *can*
32  // have strings formed out of multiple @ strings with multiple pptokens in
33  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
34  // StringLiteral for ObjCStringLiteral to hold onto.
35  StringLiteral *S = Strings[0];
36
37  // If we have a multi-part string, merge it all together.
38  if (NumStrings != 1) {
39    // Concatenate objc strings.
40    llvm::SmallString<128> StrBuf;
41    llvm::SmallVector<SourceLocation, 8> StrLocs;
42
43    for (unsigned i = 0; i != NumStrings; ++i) {
44      S = Strings[i];
45
46      // ObjC strings can't be wide.
47      if (S->isWide()) {
48        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
49          << S->getSourceRange();
50        return true;
51      }
52
53      // Append the string.
54      StrBuf += S->getString();
55
56      // Get the locations of the string tokens.
57      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
58    }
59
60    // Create the aggregate string with the appropriate content and location
61    // information.
62    S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
63                              Context.getPointerType(Context.CharTy),
64                              &StrLocs[0], StrLocs.size());
65  }
66
67  // Verify that this composite string is acceptable for ObjC strings.
68  if (CheckObjCString(S))
69    return true;
70
71  // Initialize the constant string interface lazily. This assumes
72  // the NSString interface is seen in this translation unit. Note: We
73  // don't use NSConstantString, since the runtime team considers this
74  // interface private (even though it appears in the header files).
75  QualType Ty = Context.getObjCConstantStringInterface();
76  if (!Ty.isNull()) {
77    Ty = Context.getObjCObjectPointerType(Ty);
78  } else if (getLangOptions().NoConstantCFStrings) {
79    IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
80    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
81                                     LookupOrdinaryName);
82    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
83      Context.setObjCConstantStringInterface(StrIF);
84      Ty = Context.getObjCConstantStringInterface();
85      Ty = Context.getObjCObjectPointerType(Ty);
86    } else {
87      // If there is no NSConstantString interface defined then treat this
88      // as error and recover from it.
89      Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
90        << S->getSourceRange();
91      Ty = Context.getObjCIdType();
92    }
93  } else {
94    IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
95    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
96                                     LookupOrdinaryName);
97    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
98      Context.setObjCConstantStringInterface(StrIF);
99      Ty = Context.getObjCConstantStringInterface();
100      Ty = Context.getObjCObjectPointerType(Ty);
101    } else {
102      // If there is no NSString interface defined then treat constant
103      // strings as untyped objects and let the runtime figure it out later.
104      Ty = Context.getObjCIdType();
105    }
106  }
107
108  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
109}
110
111Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
112                                      TypeSourceInfo *EncodedTypeInfo,
113                                      SourceLocation RParenLoc) {
114  QualType EncodedType = EncodedTypeInfo->getType();
115  QualType StrTy;
116  if (EncodedType->isDependentType())
117    StrTy = Context.DependentTy;
118  else {
119    std::string Str;
120    Context.getObjCEncodingForType(EncodedType, Str);
121
122    // The type of @encode is the same as the type of the corresponding string,
123    // which is an array type.
124    StrTy = Context.CharTy;
125    // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
126    if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
127      StrTy.addConst();
128    StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
129                                         ArrayType::Normal, 0);
130  }
131
132  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
133}
134
135Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
136                                                 SourceLocation EncodeLoc,
137                                                 SourceLocation LParenLoc,
138                                                 ParsedType ty,
139                                                 SourceLocation RParenLoc) {
140  // FIXME: Preserve type source info ?
141  TypeSourceInfo *TInfo;
142  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
143  if (!TInfo)
144    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
145                                             PP.getLocForEndOfToken(LParenLoc));
146
147  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
148}
149
150Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
151                                                   SourceLocation AtLoc,
152                                                   SourceLocation SelLoc,
153                                                   SourceLocation LParenLoc,
154                                                   SourceLocation RParenLoc) {
155  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
156                             SourceRange(LParenLoc, RParenLoc), false, false);
157  if (!Method)
158    Method = LookupFactoryMethodInGlobalPool(Sel,
159                                          SourceRange(LParenLoc, RParenLoc));
160  if (!Method)
161    Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
162
163  llvm::DenseMap<Selector, SourceLocation>::iterator Pos
164    = ReferencedSelectors.find(Sel);
165  if (Pos == ReferencedSelectors.end())
166    ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
167
168  QualType Ty = Context.getObjCSelType();
169  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
170}
171
172Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
173                                                   SourceLocation AtLoc,
174                                                   SourceLocation ProtoLoc,
175                                                   SourceLocation LParenLoc,
176                                                   SourceLocation RParenLoc) {
177  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
178  if (!PDecl) {
179    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
180    return true;
181  }
182
183  QualType Ty = Context.getObjCProtoType();
184  if (Ty.isNull())
185    return true;
186  Ty = Context.getObjCObjectPointerType(Ty);
187  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
188}
189
190bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
191                                     Selector Sel, ObjCMethodDecl *Method,
192                                     bool isClassMessage,
193                                     SourceLocation lbrac, SourceLocation rbrac,
194                                     QualType &ReturnType) {
195  if (!Method) {
196    // Apply default argument promotion as for (C99 6.5.2.2p6).
197    for (unsigned i = 0; i != NumArgs; i++) {
198      if (Args[i]->isTypeDependent())
199        continue;
200
201      DefaultArgumentPromotion(Args[i]);
202    }
203
204    unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
205                                       diag::warn_inst_method_not_found;
206    Diag(lbrac, DiagID)
207      << Sel << isClassMessage << SourceRange(lbrac, rbrac);
208    ReturnType = Context.getObjCIdType();
209    return false;
210  }
211
212  ReturnType = Method->getSendResultType();
213
214  unsigned NumNamedArgs = Sel.getNumArgs();
215  // Method might have more arguments than selector indicates. This is due
216  // to addition of c-style arguments in method.
217  if (Method->param_size() > Sel.getNumArgs())
218    NumNamedArgs = Method->param_size();
219  // FIXME. This need be cleaned up.
220  if (NumArgs < NumNamedArgs) {
221    Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
222    << NumNamedArgs << NumArgs;
223    return false;
224  }
225
226  bool IsError = false;
227  for (unsigned i = 0; i < NumNamedArgs; i++) {
228    // We can't do any type-checking on a type-dependent argument.
229    if (Args[i]->isTypeDependent())
230      continue;
231
232    Expr *argExpr = Args[i];
233
234    ParmVarDecl *Param = Method->param_begin()[i];
235    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
236
237    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
238                            Param->getType(),
239                            PDiag(diag::err_call_incomplete_argument)
240                              << argExpr->getSourceRange()))
241      return true;
242
243    InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
244    ExprResult ArgE = PerformCopyInitialization(Entity,
245                                                      SourceLocation(),
246                                                      Owned(argExpr->Retain()));
247    if (ArgE.isInvalid())
248      IsError = true;
249    else
250      Args[i] = ArgE.takeAs<Expr>();
251  }
252
253  // Promote additional arguments to variadic methods.
254  if (Method->isVariadic()) {
255    for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
256      if (Args[i]->isTypeDependent())
257        continue;
258
259      IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
260    }
261  } else {
262    // Check for extra arguments to non-variadic methods.
263    if (NumArgs != NumNamedArgs) {
264      Diag(Args[NumNamedArgs]->getLocStart(),
265           diag::err_typecheck_call_too_many_args)
266        << 2 /*method*/ << NumNamedArgs << NumArgs
267        << Method->getSourceRange()
268        << SourceRange(Args[NumNamedArgs]->getLocStart(),
269                       Args[NumArgs-1]->getLocEnd());
270    }
271  }
272
273  DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
274  return IsError;
275}
276
277bool Sema::isSelfExpr(Expr *RExpr) {
278  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
279    if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
280      return true;
281  return false;
282}
283
284// Helper method for ActOnClassMethod/ActOnInstanceMethod.
285// Will search "local" class/category implementations for a method decl.
286// If failed, then we search in class's root for an instance method.
287// Returns 0 if no method is found.
288ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
289                                          ObjCInterfaceDecl *ClassDecl) {
290  ObjCMethodDecl *Method = 0;
291  // lookup in class and all superclasses
292  while (ClassDecl && !Method) {
293    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
294      Method = ImpDecl->getClassMethod(Sel);
295
296    // Look through local category implementations associated with the class.
297    if (!Method)
298      Method = ClassDecl->getCategoryClassMethod(Sel);
299
300    // Before we give up, check if the selector is an instance method.
301    // But only in the root. This matches gcc's behaviour and what the
302    // runtime expects.
303    if (!Method && !ClassDecl->getSuperClass()) {
304      Method = ClassDecl->lookupInstanceMethod(Sel);
305      // Look through local category implementations associated
306      // with the root class.
307      if (!Method)
308        Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
309    }
310
311    ClassDecl = ClassDecl->getSuperClass();
312  }
313  return Method;
314}
315
316ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
317                                              ObjCInterfaceDecl *ClassDecl) {
318  ObjCMethodDecl *Method = 0;
319  while (ClassDecl && !Method) {
320    // If we have implementations in scope, check "private" methods.
321    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
322      Method = ImpDecl->getInstanceMethod(Sel);
323
324    // Look through local category implementations associated with the class.
325    if (!Method)
326      Method = ClassDecl->getCategoryInstanceMethod(Sel);
327    ClassDecl = ClassDecl->getSuperClass();
328  }
329  return Method;
330}
331
332/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
333/// objective C interface.  This is a property reference expression.
334ExprResult Sema::
335HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
336                          Expr *BaseExpr, DeclarationName MemberName,
337                          SourceLocation MemberLoc) {
338  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
339  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
340  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
341
342  // Search for a declared property first.
343  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
344    // Check whether we can reference this property.
345    if (DiagnoseUseOfDecl(PD, MemberLoc))
346      return ExprError();
347    QualType ResTy = PD->getType();
348    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
349    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
350    if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
351      ResTy = Getter->getSendResultType();
352    return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
353                                                   MemberLoc, BaseExpr));
354  }
355  // Check protocols on qualified interfaces.
356  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
357       E = OPT->qual_end(); I != E; ++I)
358    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
359      // Check whether we can reference this property.
360      if (DiagnoseUseOfDecl(PD, MemberLoc))
361        return ExprError();
362
363      return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
364                                                     MemberLoc, BaseExpr));
365    }
366  // If that failed, look for an "implicit" property by seeing if the nullary
367  // selector is implemented.
368
369  // FIXME: The logic for looking up nullary and unary selectors should be
370  // shared with the code in ActOnInstanceMessage.
371
372  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
373  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
374
375  // If this reference is in an @implementation, check for 'private' methods.
376  if (!Getter)
377    Getter = IFace->lookupPrivateInstanceMethod(Sel);
378
379  // Look through local category implementations associated with the class.
380  if (!Getter)
381    Getter = IFace->getCategoryInstanceMethod(Sel);
382  if (Getter) {
383    // Check if we can reference this property.
384    if (DiagnoseUseOfDecl(Getter, MemberLoc))
385      return ExprError();
386  }
387  // If we found a getter then this may be a valid dot-reference, we
388  // will look for the matching setter, in case it is needed.
389  Selector SetterSel =
390    SelectorTable::constructSetterName(PP.getIdentifierTable(),
391                                       PP.getSelectorTable(), Member);
392  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
393  if (!Setter) {
394    // If this reference is in an @implementation, also check for 'private'
395    // methods.
396    Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
397  }
398  // Look through local category implementations associated with the class.
399  if (!Setter)
400    Setter = IFace->getCategoryInstanceMethod(SetterSel);
401
402  if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
403    return ExprError();
404
405  if (Getter) {
406    QualType PType;
407    PType = Getter->getSendResultType();
408    return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
409                                    Setter, MemberLoc, BaseExpr));
410  }
411
412  // Attempt to correct for typos in property names.
413  LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
414  if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
415      Res.getAsSingle<ObjCPropertyDecl>()) {
416    DeclarationName TypoResult = Res.getLookupName();
417    Diag(MemberLoc, diag::err_property_not_found_suggest)
418      << MemberName << QualType(OPT, 0) << TypoResult
419      << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
420    ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
421    Diag(Property->getLocation(), diag::note_previous_decl)
422      << Property->getDeclName();
423    return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
424  }
425
426  Diag(MemberLoc, diag::err_property_not_found)
427    << MemberName << QualType(OPT, 0);
428  if (Setter && !Getter)
429    Diag(Setter->getLocation(), diag::note_getter_unavailable)
430      << MemberName << BaseExpr->getSourceRange();
431  return ExprError();
432}
433
434
435
436ExprResult Sema::
437ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
438                          IdentifierInfo &propertyName,
439                          SourceLocation receiverNameLoc,
440                          SourceLocation propertyNameLoc) {
441
442  IdentifierInfo *receiverNamePtr = &receiverName;
443  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
444                                                  receiverNameLoc);
445  if (IFace == 0) {
446    // If the "receiver" is 'super' in a method, handle it as an expression-like
447    // property reference.
448    if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
449      if (receiverNamePtr->isStr("super")) {
450        if (CurMethod->isInstanceMethod()) {
451          QualType T =
452            Context.getObjCInterfaceType(CurMethod->getClassInterface());
453          T = Context.getObjCObjectPointerType(T);
454          Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
455
456          return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
457                                           SuperExpr, &propertyName,
458                                           propertyNameLoc);
459        }
460
461        // Otherwise, if this is a class method, try dispatching to our
462        // superclass.
463        IFace = CurMethod->getClassInterface()->getSuperClass();
464      }
465
466    if (IFace == 0) {
467      Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
468      return ExprError();
469    }
470  }
471
472  // Search for a declared property first.
473  Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
474  ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
475
476  // If this reference is in an @implementation, check for 'private' methods.
477  if (!Getter)
478    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
479      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
480        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
481          Getter = ImpDecl->getClassMethod(Sel);
482
483  if (Getter) {
484    // FIXME: refactor/share with ActOnMemberReference().
485    // Check if we can reference this property.
486    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
487      return ExprError();
488  }
489
490  // Look for the matching setter, in case it is needed.
491  Selector SetterSel =
492    SelectorTable::constructSetterName(PP.getIdentifierTable(),
493                                       PP.getSelectorTable(), &propertyName);
494
495  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
496  if (!Setter) {
497    // If this reference is in an @implementation, also check for 'private'
498    // methods.
499    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
500      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
501        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
502          Setter = ImpDecl->getClassMethod(SetterSel);
503  }
504  // Look through local category implementations associated with the class.
505  if (!Setter)
506    Setter = IFace->getCategoryClassMethod(SetterSel);
507
508  if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
509    return ExprError();
510
511  if (Getter || Setter) {
512    QualType PType;
513
514    if (Getter)
515      PType = Getter->getSendResultType();
516    else {
517      for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
518           E = Setter->param_end(); PI != E; ++PI)
519        PType = (*PI)->getType();
520    }
521    return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
522                                  Getter, PType, Setter,
523                                  propertyNameLoc, IFace, receiverNameLoc));
524  }
525  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
526                     << &propertyName << Context.getObjCInterfaceType(IFace));
527}
528
529Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
530                                               IdentifierInfo *Name,
531                                               SourceLocation NameLoc,
532                                               bool IsSuper,
533                                               bool HasTrailingDot,
534                                               ParsedType &ReceiverType) {
535  ReceiverType = ParsedType();
536
537  // If the identifier is "super" and there is no trailing dot, we're
538  // messaging super.
539  if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
540    return ObjCSuperMessage;
541
542  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
543  LookupName(Result, S);
544
545  switch (Result.getResultKind()) {
546  case LookupResult::NotFound:
547    // Normal name lookup didn't find anything. If we're in an
548    // Objective-C method, look for ivars. If we find one, we're done!
549    // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
550    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
551      ObjCInterfaceDecl *ClassDeclared;
552      if (Method->getClassInterface()->lookupInstanceVariable(Name,
553                                                              ClassDeclared))
554        return ObjCInstanceMessage;
555    }
556
557    // Break out; we'll perform typo correction below.
558    break;
559
560  case LookupResult::NotFoundInCurrentInstantiation:
561  case LookupResult::FoundOverloaded:
562  case LookupResult::FoundUnresolvedValue:
563  case LookupResult::Ambiguous:
564    Result.suppressDiagnostics();
565    return ObjCInstanceMessage;
566
567  case LookupResult::Found: {
568    // We found something. If it's a type, then we have a class
569    // message. Otherwise, it's an instance message.
570    NamedDecl *ND = Result.getFoundDecl();
571    QualType T;
572    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
573      T = Context.getObjCInterfaceType(Class);
574    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
575      T = Context.getTypeDeclType(Type);
576    else
577      return ObjCInstanceMessage;
578
579    //  We have a class message, and T is the type we're
580    //  messaging. Build source-location information for it.
581    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
582    ReceiverType = CreateParsedType(T, TSInfo);
583    return ObjCClassMessage;
584  }
585  }
586
587  // Determine our typo-correction context.
588  CorrectTypoContext CTC = CTC_Expression;
589  if (ObjCMethodDecl *Method = getCurMethodDecl())
590    if (Method->getClassInterface() &&
591        Method->getClassInterface()->getSuperClass())
592      CTC = CTC_ObjCMessageReceiver;
593
594  if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
595    if (Result.isSingleResult()) {
596      // If we found a declaration, correct when it refers to an Objective-C
597      // class.
598      NamedDecl *ND = Result.getFoundDecl();
599      if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
600        Diag(NameLoc, diag::err_unknown_receiver_suggest)
601          << Name << Result.getLookupName()
602          << FixItHint::CreateReplacement(SourceRange(NameLoc),
603                                          ND->getNameAsString());
604        Diag(ND->getLocation(), diag::note_previous_decl)
605          << Corrected;
606
607        QualType T = Context.getObjCInterfaceType(Class);
608        TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
609        ReceiverType = CreateParsedType(T, TSInfo);
610        return ObjCClassMessage;
611      }
612    } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
613               Corrected.getAsIdentifierInfo()->isStr("super")) {
614      // If we've found the keyword "super", this is a send to super.
615      Diag(NameLoc, diag::err_unknown_receiver_suggest)
616        << Name << Corrected
617        << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
618      Name = Corrected.getAsIdentifierInfo();
619      return ObjCSuperMessage;
620    }
621  }
622
623  // Fall back: let the parser try to parse it as an instance message.
624  return ObjCInstanceMessage;
625}
626
627ExprResult Sema::ActOnSuperMessage(Scope *S,
628                                               SourceLocation SuperLoc,
629                                               Selector Sel,
630                                               SourceLocation LBracLoc,
631                                               SourceLocation SelectorLoc,
632                                               SourceLocation RBracLoc,
633                                               MultiExprArg Args) {
634  // Determine whether we are inside a method or not.
635  ObjCMethodDecl *Method = getCurMethodDecl();
636  if (!Method) {
637    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
638    return ExprError();
639  }
640
641  ObjCInterfaceDecl *Class = Method->getClassInterface();
642  if (!Class) {
643    Diag(SuperLoc, diag::error_no_super_class_message)
644      << Method->getDeclName();
645    return ExprError();
646  }
647
648  ObjCInterfaceDecl *Super = Class->getSuperClass();
649  if (!Super) {
650    // The current class does not have a superclass.
651    Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
652    return ExprError();
653  }
654
655  // We are in a method whose class has a superclass, so 'super'
656  // is acting as a keyword.
657  if (Method->isInstanceMethod()) {
658    // Since we are in an instance method, this is an instance
659    // message to the superclass instance.
660    QualType SuperTy = Context.getObjCInterfaceType(Super);
661    SuperTy = Context.getObjCObjectPointerType(SuperTy);
662    return BuildInstanceMessage(0, SuperTy, SuperLoc,
663                                Sel, /*Method=*/0, LBracLoc, RBracLoc,
664                                move(Args));
665  }
666
667  // Since we are in a class method, this is a class message to
668  // the superclass.
669  return BuildClassMessage(/*ReceiverTypeInfo=*/0,
670                           Context.getObjCInterfaceType(Super),
671                           SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
672                           move(Args));
673}
674
675/// \brief Build an Objective-C class message expression.
676///
677/// This routine takes care of both normal class messages and
678/// class messages to the superclass.
679///
680/// \param ReceiverTypeInfo Type source information that describes the
681/// receiver of this message. This may be NULL, in which case we are
682/// sending to the superclass and \p SuperLoc must be a valid source
683/// location.
684
685/// \param ReceiverType The type of the object receiving the
686/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
687/// type as that refers to. For a superclass send, this is the type of
688/// the superclass.
689///
690/// \param SuperLoc The location of the "super" keyword in a
691/// superclass message.
692///
693/// \param Sel The selector to which the message is being sent.
694///
695/// \param Method The method that this class message is invoking, if
696/// already known.
697///
698/// \param LBracLoc The location of the opening square bracket ']'.
699///
700/// \param RBrac The location of the closing square bracket ']'.
701///
702/// \param Args The message arguments.
703ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
704                                               QualType ReceiverType,
705                                               SourceLocation SuperLoc,
706                                               Selector Sel,
707                                               ObjCMethodDecl *Method,
708                                               SourceLocation LBracLoc,
709                                               SourceLocation RBracLoc,
710                                               MultiExprArg ArgsIn) {
711  if (ReceiverType->isDependentType()) {
712    // If the receiver type is dependent, we can't type-check anything
713    // at this point. Build a dependent expression.
714    unsigned NumArgs = ArgsIn.size();
715    Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
716    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
717    return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
718                                         ReceiverTypeInfo, Sel, /*Method=*/0,
719                                         Args, NumArgs, RBracLoc));
720  }
721
722  SourceLocation Loc = SuperLoc.isValid()? SuperLoc
723             : ReceiverTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
724
725  // Find the class to which we are sending this message.
726  ObjCInterfaceDecl *Class = 0;
727  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
728  if (!ClassType || !(Class = ClassType->getInterface())) {
729    Diag(Loc, diag::err_invalid_receiver_class_message)
730      << ReceiverType;
731    return ExprError();
732  }
733  assert(Class && "We don't know which class we're messaging?");
734
735  // Find the method we are messaging.
736  if (!Method) {
737    if (Class->isForwardDecl()) {
738      // A forward class used in messaging is treated as a 'Class'
739      Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
740      Method = LookupFactoryMethodInGlobalPool(Sel,
741                                               SourceRange(LBracLoc, RBracLoc));
742      if (Method)
743        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
744          << Method->getDeclName();
745    }
746    if (!Method)
747      Method = Class->lookupClassMethod(Sel);
748
749    // If we have an implementation in scope, check "private" methods.
750    if (!Method)
751      Method = LookupPrivateClassMethod(Sel, Class);
752
753    if (Method && DiagnoseUseOfDecl(Method, Loc))
754      return ExprError();
755  }
756
757  // Check the argument types and determine the result type.
758  QualType ReturnType;
759  unsigned NumArgs = ArgsIn.size();
760  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
761  if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
762                                LBracLoc, RBracLoc, ReturnType))
763    return ExprError();
764
765  // Construct the appropriate ObjCMessageExpr.
766  Expr *Result;
767  if (SuperLoc.isValid())
768    Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
769                                     SuperLoc, /*IsInstanceSuper=*/false,
770                                     ReceiverType, Sel, Method, Args,
771                                     NumArgs, RBracLoc);
772  else
773    Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
774                                     ReceiverTypeInfo, Sel, Method, Args,
775                                     NumArgs, RBracLoc);
776  return MaybeBindToTemporary(Result);
777}
778
779// ActOnClassMessage - used for both unary and keyword messages.
780// ArgExprs is optional - if it is present, the number of expressions
781// is obtained from Sel.getNumArgs().
782ExprResult Sema::ActOnClassMessage(Scope *S,
783                                               ParsedType Receiver,
784                                               Selector Sel,
785                                               SourceLocation LBracLoc,
786                                               SourceLocation SelectorLoc,
787                                               SourceLocation RBracLoc,
788                                               MultiExprArg Args) {
789  TypeSourceInfo *ReceiverTypeInfo;
790  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
791  if (ReceiverType.isNull())
792    return ExprError();
793
794
795  if (!ReceiverTypeInfo)
796    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
797
798  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
799                           /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
800                           LBracLoc, RBracLoc, move(Args));
801}
802
803/// \brief Build an Objective-C instance message expression.
804///
805/// This routine takes care of both normal instance messages and
806/// instance messages to the superclass instance.
807///
808/// \param Receiver The expression that computes the object that will
809/// receive this message. This may be empty, in which case we are
810/// sending to the superclass instance and \p SuperLoc must be a valid
811/// source location.
812///
813/// \param ReceiverType The (static) type of the object receiving the
814/// message. When a \p Receiver expression is provided, this is the
815/// same type as that expression. For a superclass instance send, this
816/// is a pointer to the type of the superclass.
817///
818/// \param SuperLoc The location of the "super" keyword in a
819/// superclass instance message.
820///
821/// \param Sel The selector to which the message is being sent.
822///
823/// \param Method The method that this instance message is invoking, if
824/// already known.
825///
826/// \param LBracLoc The location of the opening square bracket ']'.
827///
828/// \param RBrac The location of the closing square bracket ']'.
829///
830/// \param Args The message arguments.
831ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
832                                                  QualType ReceiverType,
833                                                  SourceLocation SuperLoc,
834                                                  Selector Sel,
835                                                  ObjCMethodDecl *Method,
836                                                  SourceLocation LBracLoc,
837                                                  SourceLocation RBracLoc,
838                                                  MultiExprArg ArgsIn) {
839  // If we have a receiver expression, perform appropriate promotions
840  // and determine receiver type.
841  if (Receiver) {
842    if (Receiver->isTypeDependent()) {
843      // If the receiver is type-dependent, we can't type-check anything
844      // at this point. Build a dependent expression.
845      unsigned NumArgs = ArgsIn.size();
846      Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
847      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
848      return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
849                                           LBracLoc, Receiver, Sel,
850                                           /*Method=*/0, Args, NumArgs,
851                                           RBracLoc));
852    }
853
854    // If necessary, apply function/array conversion to the receiver.
855    // C99 6.7.5.3p[7,8].
856    DefaultFunctionArrayLvalueConversion(Receiver);
857    ReceiverType = Receiver->getType();
858  }
859
860  // The location of the receiver.
861  SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
862
863  if (!Method) {
864    // Handle messages to id.
865    bool receiverIsId = ReceiverType->isObjCIdType();
866    if (receiverIsId || ReceiverType->isBlockPointerType() ||
867        (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
868      Method = LookupInstanceMethodInGlobalPool(Sel,
869                                                SourceRange(LBracLoc, RBracLoc),
870                                                receiverIsId);
871      if (!Method)
872        Method = LookupFactoryMethodInGlobalPool(Sel,
873                                                 SourceRange(LBracLoc, RBracLoc),
874                                                 receiverIsId);
875    } else if (ReceiverType->isObjCClassType() ||
876               ReceiverType->isObjCQualifiedClassType()) {
877      // Handle messages to Class.
878      if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
879        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
880          // First check the public methods in the class interface.
881          Method = ClassDecl->lookupClassMethod(Sel);
882
883          if (!Method)
884            Method = LookupPrivateClassMethod(Sel, ClassDecl);
885
886          // FIXME: if we still haven't found a method, we need to look in
887          // protocols (if we have qualifiers).
888        }
889        if (Method && DiagnoseUseOfDecl(Method, Loc))
890          return ExprError();
891      }
892      if (!Method) {
893        // If not messaging 'self', look for any factory method named 'Sel'.
894        if (!Receiver || !isSelfExpr(Receiver)) {
895          Method = LookupFactoryMethodInGlobalPool(Sel,
896                                               SourceRange(LBracLoc, RBracLoc),
897                                                   true);
898          if (!Method) {
899            // If no class (factory) method was found, check if an _instance_
900            // method of the same name exists in the root class only.
901            Method = LookupInstanceMethodInGlobalPool(Sel,
902                                               SourceRange(LBracLoc, RBracLoc),
903                                                      true);
904            if (Method)
905                if (const ObjCInterfaceDecl *ID =
906                  dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
907                if (ID->getSuperClass())
908                  Diag(Loc, diag::warn_root_inst_method_not_found)
909                    << Sel << SourceRange(LBracLoc, RBracLoc);
910              }
911          }
912        }
913      }
914    } else {
915      ObjCInterfaceDecl* ClassDecl = 0;
916
917      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
918      // long as one of the protocols implements the selector (if not, warn).
919      if (const ObjCObjectPointerType *QIdTy
920                                   = ReceiverType->getAsObjCQualifiedIdType()) {
921        // Search protocols for instance methods.
922        for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
923               E = QIdTy->qual_end(); I != E; ++I) {
924          ObjCProtocolDecl *PDecl = *I;
925          if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
926            break;
927          // Since we aren't supporting "Class<foo>", look for a class method.
928          if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
929            break;
930        }
931      } else if (const ObjCObjectPointerType *OCIType
932                   = ReceiverType->getAsObjCInterfacePointerType()) {
933        // We allow sending a message to a pointer to an interface (an object).
934        ClassDecl = OCIType->getInterfaceDecl();
935        // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
936        // faster than the following method (which can do *many* linear searches).
937        // The idea is to add class info to MethodPool.
938        Method = ClassDecl->lookupInstanceMethod(Sel);
939
940        if (!Method) {
941          // Search protocol qualifiers.
942          for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
943                 E = OCIType->qual_end(); QI != E; ++QI) {
944            if ((Method = (*QI)->lookupInstanceMethod(Sel)))
945              break;
946          }
947        }
948        if (!Method) {
949          // If we have implementations in scope, check "private" methods.
950          Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
951
952          if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
953            // If we still haven't found a method, look in the global pool. This
954            // behavior isn't very desirable, however we need it for GCC
955            // compatibility. FIXME: should we deviate??
956            if (OCIType->qual_empty()) {
957              Method = LookupInstanceMethodInGlobalPool(Sel,
958                                                 SourceRange(LBracLoc, RBracLoc));
959              if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
960                Diag(Loc, diag::warn_maynot_respond)
961                  << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
962            }
963          }
964        }
965        if (Method && DiagnoseUseOfDecl(Method, Loc))
966          return ExprError();
967      } else if (!Context.getObjCIdType().isNull() &&
968                 (ReceiverType->isPointerType() ||
969                  ReceiverType->isIntegerType())) {
970        // Implicitly convert integers and pointers to 'id' but emit a warning.
971        Diag(Loc, diag::warn_bad_receiver_type)
972          << ReceiverType
973          << Receiver->getSourceRange();
974        if (ReceiverType->isPointerType())
975          ImpCastExprToType(Receiver, Context.getObjCIdType(),
976                            CastExpr::CK_BitCast);
977        else
978          ImpCastExprToType(Receiver, Context.getObjCIdType(),
979                            CastExpr::CK_IntegralToPointer);
980        ReceiverType = Receiver->getType();
981      }
982      else if (getLangOptions().CPlusPlus &&
983               !PerformContextuallyConvertToObjCId(Receiver)) {
984        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
985          Receiver = ICE->getSubExpr();
986          ReceiverType = Receiver->getType();
987        }
988        return BuildInstanceMessage(Receiver,
989                                    ReceiverType,
990                                    SuperLoc,
991                                    Sel,
992                                    Method,
993                                    LBracLoc,
994                                    RBracLoc,
995                                    move(ArgsIn));
996      } else {
997        // Reject other random receiver types (e.g. structs).
998        Diag(Loc, diag::err_bad_receiver_type)
999          << ReceiverType << Receiver->getSourceRange();
1000        return ExprError();
1001      }
1002    }
1003  }
1004
1005  // Check the message arguments.
1006  unsigned NumArgs = ArgsIn.size();
1007  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1008  QualType ReturnType;
1009  if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1010                                LBracLoc, RBracLoc, ReturnType))
1011    return ExprError();
1012
1013  if (!ReturnType->isVoidType()) {
1014    if (RequireCompleteType(LBracLoc, ReturnType,
1015                            diag::err_illegal_message_expr_incomplete_type))
1016      return ExprError();
1017  }
1018
1019  // Construct the appropriate ObjCMessageExpr instance.
1020  Expr *Result;
1021  if (SuperLoc.isValid())
1022    Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1023                                     SuperLoc,  /*IsInstanceSuper=*/true,
1024                                     ReceiverType, Sel, Method,
1025                                     Args, NumArgs, RBracLoc);
1026  else
1027    Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1028                                     Sel, Method, Args, NumArgs, RBracLoc);
1029  return MaybeBindToTemporary(Result);
1030}
1031
1032// ActOnInstanceMessage - used for both unary and keyword messages.
1033// ArgExprs is optional - if it is present, the number of expressions
1034// is obtained from Sel.getNumArgs().
1035ExprResult Sema::ActOnInstanceMessage(Scope *S,
1036                                      Expr *Receiver,
1037                                      Selector Sel,
1038                                      SourceLocation LBracLoc,
1039                                      SourceLocation SelectorLoc,
1040                                      SourceLocation RBracLoc,
1041                                      MultiExprArg Args) {
1042  if (!Receiver)
1043    return ExprError();
1044
1045  return BuildInstanceMessage(Receiver, Receiver->getType(),
1046                              /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1047                              LBracLoc, RBracLoc, move(Args));
1048}
1049
1050