SemaExprObjC.cpp revision f366d51179f775531c88c7040f00cecc58cdffd0
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 "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprObjC.h"
18#include "llvm/ADT/SmallString.h"
19#include "clang/Lex/Preprocessor.h"
20
21using namespace clang;
22
23Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
24                                              ExprTy **strings,
25                                              unsigned NumStrings) {
26  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
27
28  // Most ObjC strings are formed out of a single piece.  However, we *can*
29  // have strings formed out of multiple @ strings with multiple pptokens in
30  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
31  // StringLiteral for ObjCStringLiteral to hold onto.
32  StringLiteral *S = Strings[0];
33
34  // If we have a multi-part string, merge it all together.
35  if (NumStrings != 1) {
36    // Concatenate objc strings.
37    llvm::SmallString<128> StrBuf;
38    llvm::SmallVector<SourceLocation, 8> StrLocs;
39
40    for (unsigned i = 0; i != NumStrings; ++i) {
41      S = Strings[i];
42
43      // ObjC strings can't be wide.
44      if (S->isWide()) {
45        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
46          << S->getSourceRange();
47        return true;
48      }
49
50      // Get the string data.
51      StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
52
53      // Get the locations of the string tokens.
54      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
55
56      // Free the temporary string.
57      S->Destroy(Context);
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.getPointerType(Ty);
78  } else {
79    IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
80    NamedDecl *IF = LookupName(TUScope, NSIdent, LookupOrdinaryName);
81    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
82      Context.setObjCConstantStringInterface(StrIF);
83      Ty = Context.getObjCConstantStringInterface();
84      Ty = Context.getPointerType(Ty);
85    } else {
86      // If there is no NSString interface defined then treat constant
87      // strings as untyped objects and let the runtime figure it out later.
88      Ty = Context.getObjCIdType();
89    }
90  }
91
92  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
93}
94
95Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
96                                                 SourceLocation EncodeLoc,
97                                                 SourceLocation LParenLoc,
98                                                 TypeTy *ty,
99                                                 SourceLocation RParenLoc) {
100  QualType EncodedType = QualType::getFromOpaquePtr(ty);
101
102  std::string Str;
103  Context.getObjCEncodingForType(EncodedType, Str);
104
105  // The type of @encode is the same as the type of the corresponding string,
106  // which is an array type.
107  QualType StrTy = Context.CharTy;
108  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
109  if (getLangOptions().CPlusPlus)
110    StrTy.addConst();
111  StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
112                                       ArrayType::Normal, 0);
113
114  return new (Context) ObjCEncodeExpr(StrTy, EncodedType, AtLoc, RParenLoc);
115}
116
117Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
118                                                   SourceLocation AtLoc,
119                                                   SourceLocation SelLoc,
120                                                   SourceLocation LParenLoc,
121                                                   SourceLocation RParenLoc) {
122  QualType Ty = Context.getObjCSelType();
123  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
124}
125
126Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
127                                                   SourceLocation AtLoc,
128                                                   SourceLocation ProtoLoc,
129                                                   SourceLocation LParenLoc,
130                                                   SourceLocation RParenLoc) {
131  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId);
132  if (!PDecl) {
133    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
134    return true;
135  }
136
137  QualType Ty = Context.getObjCProtoType();
138  if (Ty.isNull())
139    return true;
140  Ty = Context.getPointerType(Ty);
141  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
142}
143
144bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
145                                     Selector Sel, ObjCMethodDecl *Method,
146                                     bool isClassMessage,
147                                     SourceLocation lbrac, SourceLocation rbrac,
148                                     QualType &ReturnType) {
149  if (!Method) {
150    // Apply default argument promotion as for (C99 6.5.2.2p6).
151    for (unsigned i = 0; i != NumArgs; i++)
152      DefaultArgumentPromotion(Args[i]);
153
154    unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
155                                       diag::warn_inst_method_not_found;
156    Diag(lbrac, DiagID)
157      << Sel << isClassMessage << SourceRange(lbrac, rbrac);
158    ReturnType = Context.getObjCIdType();
159    return false;
160  }
161
162  ReturnType = Method->getResultType();
163
164  unsigned NumNamedArgs = Sel.getNumArgs();
165  assert(NumArgs >= NumNamedArgs && "Too few arguments for selector!");
166
167  bool IsError = false;
168  for (unsigned i = 0; i < NumNamedArgs; i++) {
169    Expr *argExpr = Args[i];
170    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
171
172    QualType lhsType = Method->param_begin()[i]->getType();
173    QualType rhsType = argExpr->getType();
174
175    // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
176    if (lhsType->isArrayType())
177      lhsType = Context.getArrayDecayedType(lhsType);
178    else if (lhsType->isFunctionType())
179      lhsType = Context.getPointerType(lhsType);
180
181    AssignConvertType Result =
182      CheckSingleAssignmentConstraints(lhsType, argExpr);
183    if (Args[i] != argExpr) // The expression was converted.
184      Args[i] = argExpr; // Make sure we store the converted expression.
185
186    IsError |=
187      DiagnoseAssignmentResult(Result, argExpr->getLocStart(), lhsType, rhsType,
188                               argExpr, "sending");
189  }
190
191  // Promote additional arguments to variadic methods.
192  if (Method->isVariadic()) {
193    for (unsigned i = NumNamedArgs; i < NumArgs; ++i)
194      IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod);
195  } else {
196    // Check for extra arguments to non-variadic methods.
197    if (NumArgs != NumNamedArgs) {
198      Diag(Args[NumNamedArgs]->getLocStart(),
199           diag::err_typecheck_call_too_many_args)
200        << 2 /*method*/ << Method->getSourceRange()
201        << SourceRange(Args[NumNamedArgs]->getLocStart(),
202                       Args[NumArgs-1]->getLocEnd());
203    }
204  }
205
206  return IsError;
207}
208
209bool Sema::isSelfExpr(Expr *RExpr) {
210  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
211    if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
212      return true;
213  return false;
214}
215
216// Helper method for ActOnClassMethod/ActOnInstanceMethod.
217// Will search "local" class/category implementations for a method decl.
218// If failed, then we search in class's root for an instance method.
219// Returns 0 if no method is found.
220ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
221                                          ObjCInterfaceDecl *ClassDecl) {
222  ObjCMethodDecl *Method = 0;
223  // lookup in class and all superclasses
224  while (ClassDecl && !Method) {
225    if (ObjCImplementationDecl *ImpDecl
226          = LookupObjCImplementation(ClassDecl->getIdentifier()))
227      Method = ImpDecl->getClassMethod(Context, Sel);
228
229    // Look through local category implementations associated with the class.
230    if (!Method) {
231      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) {
232        if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl)
233          Method = ObjCCategoryImpls[i]->getClassMethod(Context, Sel);
234      }
235    }
236
237    // Before we give up, check if the selector is an instance method.
238    // But only in the root. This matches gcc's behaviour and what the
239    // runtime expects.
240    if (!Method && !ClassDecl->getSuperClass()) {
241      Method = ClassDecl->lookupInstanceMethod(Context, Sel);
242      // Look through local category implementations associated
243      // with the root class.
244      if (!Method)
245        Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
246    }
247
248    ClassDecl = ClassDecl->getSuperClass();
249  }
250  return Method;
251}
252
253ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
254                                              ObjCInterfaceDecl *ClassDecl) {
255  ObjCMethodDecl *Method = 0;
256  while (ClassDecl && !Method) {
257    // If we have implementations in scope, check "private" methods.
258    if (ObjCImplementationDecl *ImpDecl
259          = LookupObjCImplementation(ClassDecl->getIdentifier()))
260      Method = ImpDecl->getInstanceMethod(Context, Sel);
261
262    // Look through local category implementations associated with the class.
263    if (!Method) {
264      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) {
265        if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl)
266          Method = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
267      }
268    }
269    ClassDecl = ClassDecl->getSuperClass();
270  }
271  return Method;
272}
273
274Action::OwningExprResult Sema::ActOnClassPropertyRefExpr(
275  IdentifierInfo &receiverName,
276  IdentifierInfo &propertyName,
277  SourceLocation &receiverNameLoc,
278  SourceLocation &propertyNameLoc) {
279
280  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(&receiverName);
281
282  // Search for a declared property first.
283
284  Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
285  ObjCMethodDecl *Getter = IFace->lookupClassMethod(Context, Sel);
286
287  // If this reference is in an @implementation, check for 'private' methods.
288  if (!Getter)
289    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
290      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
291        if (ObjCImplementationDecl *ImpDecl
292              = LookupObjCImplementation(ClassDecl->getIdentifier()))
293          Getter = ImpDecl->getClassMethod(Context, Sel);
294
295  if (Getter) {
296    // FIXME: refactor/share with ActOnMemberReference().
297    // Check if we can reference this property.
298    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
299      return ExprError();
300  }
301
302  // Look for the matching setter, in case it is needed.
303  Selector SetterSel =
304    SelectorTable::constructSetterName(PP.getIdentifierTable(),
305                                       PP.getSelectorTable(), &propertyName);
306
307  ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
308  if (!Setter) {
309    // If this reference is in an @implementation, also check for 'private'
310    // methods.
311    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
312      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
313        if (ObjCImplementationDecl *ImpDecl
314              = LookupObjCImplementation(ClassDecl->getIdentifier()))
315          Setter = ImpDecl->getClassMethod(Context, SetterSel);
316  }
317  // Look through local category implementations associated with the class.
318  if (!Setter) {
319    for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
320      if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
321        Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
322    }
323  }
324
325  if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
326    return ExprError();
327
328  if (Getter || Setter) {
329    QualType PType;
330
331    if (Getter)
332      PType = Getter->getResultType();
333    else {
334      for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
335           E = Setter->param_end(); PI != E; ++PI)
336        PType = (*PI)->getType();
337    }
338    return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, Setter,
339                                  propertyNameLoc, IFace, receiverNameLoc));
340  }
341  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
342                     << &propertyName << Context.getObjCInterfaceType(IFace));
343}
344
345
346// ActOnClassMessage - used for both unary and keyword messages.
347// ArgExprs is optional - if it is present, the number of expressions
348// is obtained from Sel.getNumArgs().
349Sema::ExprResult Sema::ActOnClassMessage(
350  Scope *S,
351  IdentifierInfo *receiverName, Selector Sel,
352  SourceLocation lbrac, SourceLocation receiverLoc,
353  SourceLocation selectorLoc, SourceLocation rbrac,
354  ExprTy **Args, unsigned NumArgs)
355{
356  assert(receiverName && "missing receiver class name");
357
358  Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
359  ObjCInterfaceDecl* ClassDecl = 0;
360  bool isSuper = false;
361
362  if (receiverName->isStr("super")) {
363    if (getCurMethodDecl()) {
364      isSuper = true;
365      ObjCInterfaceDecl *OID = getCurMethodDecl()->getClassInterface();
366      if (!OID)
367        return Diag(lbrac, diag::error_no_super_class_message)
368                      << getCurMethodDecl()->getDeclName();
369      ClassDecl = OID->getSuperClass();
370      if (!ClassDecl)
371        return Diag(lbrac, diag::error_no_super_class) << OID->getDeclName();
372      if (getCurMethodDecl()->isInstanceMethod()) {
373        QualType superTy = Context.getObjCInterfaceType(ClassDecl);
374        superTy = Context.getPointerType(superTy);
375        ExprResult ReceiverExpr = new (Context) ObjCSuperExpr(SourceLocation(),
376                                                              superTy);
377        // We are really in an instance method, redirect.
378        return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac,
379                                    selectorLoc, rbrac, Args, NumArgs);
380      }
381      // We are sending a message to 'super' within a class method. Do nothing,
382      // the receiver will pass through as 'super' (how convenient:-).
383    } else {
384      // 'super' has been used outside a method context. If a variable named
385      // 'super' has been declared, redirect. If not, produce a diagnostic.
386      NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName);
387      ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl);
388      if (VD) {
389        ExprResult ReceiverExpr = new (Context) DeclRefExpr(VD, VD->getType(),
390                                                            receiverLoc);
391        // We are really in an instance method, redirect.
392        return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac,
393                                    selectorLoc, rbrac, Args, NumArgs);
394      }
395      return Diag(receiverLoc, diag::err_undeclared_var_use) << receiverName;
396    }
397  } else
398    ClassDecl = getObjCInterfaceDecl(receiverName);
399
400  // The following code allows for the following GCC-ism:
401  //
402  //  typedef XCElementDisplayRect XCElementGraphicsRect;
403  //
404  //  @implementation XCRASlice
405  //  - whatever { // Note that XCElementGraphicsRect is a typedef name.
406  //    _sGraphicsDelegate =[[XCElementGraphicsRect alloc] init];
407  //  }
408  //
409  // If necessary, the following lookup could move to getObjCInterfaceDecl().
410  if (!ClassDecl) {
411    NamedDecl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName);
412    if (TypedefDecl *OCTD = dyn_cast_or_null<TypedefDecl>(IDecl)) {
413      const ObjCInterfaceType *OCIT;
414      OCIT = OCTD->getUnderlyingType()->getAsObjCInterfaceType();
415      if (!OCIT) {
416        Diag(receiverLoc, diag::err_invalid_receiver_to_message);
417        return true;
418      }
419      ClassDecl = OCIT->getDecl();
420    }
421  }
422  assert(ClassDecl && "missing interface declaration");
423  ObjCMethodDecl *Method = 0;
424  QualType returnType;
425  if (ClassDecl->isForwardDecl()) {
426    // A forward class used in messaging is tread as a 'Class'
427    Diag(lbrac, diag::warn_receiver_forward_class) << ClassDecl->getDeclName();
428    Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac,rbrac));
429    if (Method)
430      Diag(Method->getLocation(), diag::note_method_sent_forward_class)
431        << Method->getDeclName();
432  }
433  if (!Method)
434    Method = ClassDecl->lookupClassMethod(Context, Sel);
435
436  // If we have an implementation in scope, check "private" methods.
437  if (!Method)
438    Method = LookupPrivateClassMethod(Sel, ClassDecl);
439
440  if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
441    return true;
442
443  if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, true,
444                                lbrac, rbrac, returnType))
445    return true;
446
447  // If we have the ObjCInterfaceDecl* for the class that is receiving
448  // the message, use that to construct the ObjCMessageExpr.  Otherwise
449  // pass on the IdentifierInfo* for the class.
450  // FIXME: need to do a better job handling 'super' usage within a class
451  // For now, we simply pass the "super" identifier through (which isn't
452  // consistent with instance methods.
453  if (isSuper)
454    return new (Context) ObjCMessageExpr(receiverName, Sel, returnType, Method,
455                                         lbrac, rbrac, ArgExprs, NumArgs);
456  else
457    return new (Context) ObjCMessageExpr(ClassDecl, Sel, returnType, Method,
458                                         lbrac, rbrac, ArgExprs, NumArgs);
459}
460
461// ActOnInstanceMessage - used for both unary and keyword messages.
462// ArgExprs is optional - if it is present, the number of expressions
463// is obtained from Sel.getNumArgs().
464Sema::ExprResult Sema::ActOnInstanceMessage(ExprTy *receiver, Selector Sel,
465                                            SourceLocation lbrac,
466                                            SourceLocation receiverLoc,
467                                            SourceLocation rbrac,
468                                            ExprTy **Args, unsigned NumArgs) {
469  assert(receiver && "missing receiver expression");
470
471  Expr **ArgExprs = reinterpret_cast<Expr **>(Args);
472  Expr *RExpr = static_cast<Expr *>(receiver);
473
474  // If necessary, apply function/array conversion to the receiver.
475  // C99 6.7.5.3p[7,8].
476  DefaultFunctionArrayConversion(RExpr);
477
478  QualType returnType;
479  QualType ReceiverCType =
480    Context.getCanonicalType(RExpr->getType()).getUnqualifiedType();
481
482  // Handle messages to 'super'.
483  if (isa<ObjCSuperExpr>(RExpr)) {
484    ObjCMethodDecl *Method = 0;
485    if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
486      // If we have an interface in scope, check 'super' methods.
487      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
488        if (ObjCInterfaceDecl *SuperDecl = ClassDecl->getSuperClass()) {
489          Method = SuperDecl->lookupInstanceMethod(Context, Sel);
490
491          if (!Method)
492            // If we have implementations in scope, check "private" methods.
493            Method = LookupPrivateInstanceMethod(Sel, SuperDecl);
494        }
495    }
496
497    if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
498      return true;
499
500    if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
501                                  lbrac, rbrac, returnType))
502      return true;
503    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
504                                         rbrac, ArgExprs, NumArgs);
505  }
506
507  // Handle messages to id.
508  if (ReceiverCType == Context.getCanonicalType(Context.getObjCIdType()) ||
509      ReceiverCType->isBlockPointerType()) {
510    ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(
511                               Sel, SourceRange(lbrac,rbrac));
512    if (!Method)
513      Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac, rbrac));
514    if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
515                                  lbrac, rbrac, returnType))
516      return true;
517    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
518                                         rbrac, ArgExprs, NumArgs);
519  }
520
521  // Handle messages to Class.
522  if (ReceiverCType == Context.getCanonicalType(Context.getObjCClassType())) {
523    ObjCMethodDecl *Method = 0;
524
525    if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
526      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
527        // First check the public methods in the class interface.
528        Method = ClassDecl->lookupClassMethod(Context, Sel);
529
530        if (!Method)
531          Method = LookupPrivateClassMethod(Sel, ClassDecl);
532      }
533      if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
534        return true;
535    }
536    if (!Method) {
537      // If not messaging 'self', look for any factory method named 'Sel'.
538      if (!isSelfExpr(RExpr)) {
539        Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac,rbrac));
540        if (!Method) {
541          // If no class (factory) method was found, check if an _instance_
542          // method of the same name exists in the root class only.
543          Method = LookupInstanceMethodInGlobalPool(
544                                   Sel, SourceRange(lbrac,rbrac));
545          if (Method)
546              if (const ObjCInterfaceDecl *ID =
547                dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
548              if (ID->getSuperClass())
549                Diag(lbrac, diag::warn_root_inst_method_not_found)
550                  << Sel << SourceRange(lbrac, rbrac);
551            }
552        }
553      }
554    }
555    if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
556                                  lbrac, rbrac, returnType))
557      return true;
558    return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
559                                         rbrac, ArgExprs, NumArgs);
560  }
561
562  ObjCMethodDecl *Method = 0;
563  ObjCInterfaceDecl* ClassDecl = 0;
564
565  // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
566  // long as one of the protocols implements the selector (if not, warn).
567  if (ObjCQualifiedIdType *QIT = dyn_cast<ObjCQualifiedIdType>(ReceiverCType)) {
568    // Search protocols for instance methods.
569    for (unsigned i = 0; i < QIT->getNumProtocols(); i++) {
570      ObjCProtocolDecl *PDecl = QIT->getProtocols(i);
571      if (PDecl && (Method = PDecl->lookupInstanceMethod(Context, Sel)))
572        break;
573      // Since we aren't supporting "Class<foo>", look for a class method.
574      if (PDecl && (Method = PDecl->lookupClassMethod(Context, Sel)))
575        break;
576    }
577  } else if (const ObjCInterfaceType *OCIType =
578                ReceiverCType->getAsPointerToObjCInterfaceType()) {
579    // We allow sending a message to a pointer to an interface (an object).
580
581    ClassDecl = OCIType->getDecl();
582    // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
583    // faster than the following method (which can do *many* linear searches).
584    // The idea is to add class info to InstanceMethodPool.
585    Method = ClassDecl->lookupInstanceMethod(Context, Sel);
586
587    if (!Method) {
588      // Search protocol qualifiers.
589      for (ObjCQualifiedInterfaceType::qual_iterator QI = OCIType->qual_begin(),
590           E = OCIType->qual_end(); QI != E; ++QI) {
591        if ((Method = (*QI)->lookupInstanceMethod(Context, Sel)))
592          break;
593      }
594    }
595    if (!Method) {
596      // If we have implementations in scope, check "private" methods.
597      Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
598
599      if (!Method && !isSelfExpr(RExpr)) {
600        // If we still haven't found a method, look in the global pool. This
601        // behavior isn't very desirable, however we need it for GCC
602        // compatibility. FIXME: should we deviate??
603        if (OCIType->qual_empty()) {
604          Method = LookupInstanceMethodInGlobalPool(
605                               Sel, SourceRange(lbrac,rbrac));
606          if (Method && !OCIType->getDecl()->isForwardDecl())
607            Diag(lbrac, diag::warn_maynot_respond)
608              << OCIType->getDecl()->getIdentifier()->getName() << Sel;
609        }
610      }
611    }
612    if (Method && DiagnoseUseOfDecl(Method, receiverLoc))
613      return true;
614  } else if (!Context.getObjCIdType().isNull() &&
615             (ReceiverCType->isPointerType() ||
616              (ReceiverCType->isIntegerType() &&
617               ReceiverCType->isScalarType()))) {
618    // Implicitly convert integers and pointers to 'id' but emit a warning.
619    Diag(lbrac, diag::warn_bad_receiver_type)
620      << RExpr->getType() << RExpr->getSourceRange();
621    ImpCastExprToType(RExpr, Context.getObjCIdType());
622  } else {
623    // Reject other random receiver types (e.g. structs).
624    Diag(lbrac, diag::err_bad_receiver_type)
625      << RExpr->getType() << RExpr->getSourceRange();
626    return true;
627  }
628
629  if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false,
630                                lbrac, rbrac, returnType))
631    return true;
632  return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac,
633                                       rbrac, ArgExprs, NumArgs);
634}
635
636//===----------------------------------------------------------------------===//
637// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
638//===----------------------------------------------------------------------===//
639
640/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
641/// inheritance hierarchy of 'rProto'.
642static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
643                                           ObjCProtocolDecl *rProto) {
644  if (lProto == rProto)
645    return true;
646  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
647       E = rProto->protocol_end(); PI != E; ++PI)
648    if (ProtocolCompatibleWithProtocol(lProto, *PI))
649      return true;
650  return false;
651}
652
653/// ClassImplementsProtocol - Checks that 'lProto' protocol
654/// has been implemented in IDecl class, its super class or categories (if
655/// lookupCategory is true).
656static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
657                                    ObjCInterfaceDecl *IDecl,
658                                    bool lookupCategory,
659                                    bool RHSIsQualifiedID = false) {
660
661  // 1st, look up the class.
662  const ObjCList<ObjCProtocolDecl> &Protocols =
663    IDecl->getReferencedProtocols();
664
665  for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
666       E = Protocols.end(); PI != E; ++PI) {
667    if (ProtocolCompatibleWithProtocol(lProto, *PI))
668      return true;
669    // This is dubious and is added to be compatible with gcc.
670    // In gcc, it is also allowed assigning a protocol-qualified 'id'
671    // type to a LHS object when protocol in qualified LHS is in list
672    // of protocols in the rhs 'id' object. This IMO, should be a bug.
673    // FIXME: Treat this as an extension, and flag this as an error when
674    //  GCC extensions are not enabled.
675    if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto))
676      return true;
677  }
678
679  // 2nd, look up the category.
680  if (lookupCategory)
681    for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
682         CDecl = CDecl->getNextClassCategory()) {
683      for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
684           E = CDecl->protocol_end(); PI != E; ++PI)
685        if (ProtocolCompatibleWithProtocol(lProto, *PI))
686          return true;
687    }
688
689  // 3rd, look up the super class(s)
690  if (IDecl->getSuperClass())
691    return
692      ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory,
693                              RHSIsQualifiedID);
694
695  return false;
696}
697
698/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
699/// ObjCQualifiedIDType.
700/// FIXME: Move to ASTContext::typesAreCompatible() and friends.
701bool Sema::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
702                                             bool compare) {
703  // Allow id<P..> and an 'id' or void* type in all cases.
704  if (const PointerType *PT = lhs->getAsPointerType()) {
705    QualType PointeeTy = PT->getPointeeType();
706    if (PointeeTy->isVoidType() ||
707        Context.isObjCIdStructType(PointeeTy) ||
708        Context.isObjCClassStructType(PointeeTy))
709      return true;
710  } else if (const PointerType *PT = rhs->getAsPointerType()) {
711    QualType PointeeTy = PT->getPointeeType();
712    if (PointeeTy->isVoidType() ||
713        Context.isObjCIdStructType(PointeeTy) ||
714        Context.isObjCClassStructType(PointeeTy))
715      return true;
716  }
717
718  if (const ObjCQualifiedIdType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
719    const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType();
720    const ObjCQualifiedInterfaceType *rhsQI = 0;
721    QualType rtype;
722
723    if (!rhsQID) {
724      // Not comparing two ObjCQualifiedIdType's?
725      if (!rhs->isPointerType()) return false;
726
727      rtype = rhs->getAsPointerType()->getPointeeType();
728      rhsQI = rtype->getAsObjCQualifiedInterfaceType();
729      if (rhsQI == 0) {
730        // If the RHS is a unqualified interface pointer "NSString*",
731        // make sure we check the class hierarchy.
732        if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) {
733          ObjCInterfaceDecl *rhsID = IT->getDecl();
734          for (unsigned i = 0; i != lhsQID->getNumProtocols(); ++i) {
735            // when comparing an id<P> on lhs with a static type on rhs,
736            // see if static class implements all of id's protocols, directly or
737            // through its super class and categories.
738            if (!ClassImplementsProtocol(lhsQID->getProtocols(i), rhsID, true))
739              return false;
740          }
741          return true;
742        }
743      }
744    }
745
746    ObjCQualifiedIdType::qual_iterator RHSProtoI, RHSProtoE;
747    if (rhsQI) { // We have a qualified interface (e.g. "NSObject<Proto> *").
748      RHSProtoI = rhsQI->qual_begin();
749      RHSProtoE = rhsQI->qual_end();
750    } else if (rhsQID) { // We have a qualified id (e.g. "id<Proto> *").
751      RHSProtoI = rhsQID->qual_begin();
752      RHSProtoE = rhsQID->qual_end();
753    } else {
754      return false;
755    }
756
757    for (unsigned i =0; i < lhsQID->getNumProtocols(); i++) {
758      ObjCProtocolDecl *lhsProto = lhsQID->getProtocols(i);
759      bool match = false;
760
761      // when comparing an id<P> on lhs with a static type on rhs,
762      // see if static class implements all of id's protocols, directly or
763      // through its super class and categories.
764      for (; RHSProtoI != RHSProtoE; ++RHSProtoI) {
765        ObjCProtocolDecl *rhsProto = *RHSProtoI;
766        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
767            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
768          match = true;
769          break;
770        }
771      }
772      if (rhsQI) {
773        // If the RHS is a qualified interface pointer "NSString<P>*",
774        // make sure we check the class hierarchy.
775        if (const ObjCInterfaceType *IT = rtype->getAsObjCInterfaceType()) {
776          ObjCInterfaceDecl *rhsID = IT->getDecl();
777          for (unsigned i = 0; i != lhsQID->getNumProtocols(); ++i) {
778            // when comparing an id<P> on lhs with a static type on rhs,
779            // see if static class implements all of id's protocols, directly or
780            // through its super class and categories.
781            if (ClassImplementsProtocol(lhsQID->getProtocols(i), rhsID, true)) {
782              match = true;
783              break;
784            }
785          }
786        }
787      }
788      if (!match)
789        return false;
790    }
791
792    return true;
793  }
794
795  const ObjCQualifiedIdType *rhsQID = rhs->getAsObjCQualifiedIdType();
796  assert(rhsQID && "One of the LHS/RHS should be id<x>");
797
798  if (!lhs->isPointerType())
799    return false;
800
801  QualType ltype = lhs->getAsPointerType()->getPointeeType();
802  if (const ObjCQualifiedInterfaceType *lhsQI =
803         ltype->getAsObjCQualifiedInterfaceType()) {
804    ObjCQualifiedIdType::qual_iterator LHSProtoI = lhsQI->qual_begin();
805    ObjCQualifiedIdType::qual_iterator LHSProtoE = lhsQI->qual_end();
806    for (; LHSProtoI != LHSProtoE; ++LHSProtoI) {
807      bool match = false;
808      ObjCProtocolDecl *lhsProto = *LHSProtoI;
809      for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) {
810        ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j);
811        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
812            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
813          match = true;
814          break;
815        }
816      }
817      if (!match)
818        return false;
819    }
820    return true;
821  }
822
823  if (const ObjCInterfaceType *IT = ltype->getAsObjCInterfaceType()) {
824    // for static type vs. qualified 'id' type, check that class implements
825    // all of 'id's protocols.
826    ObjCInterfaceDecl *lhsID = IT->getDecl();
827    for (unsigned j = 0; j < rhsQID->getNumProtocols(); j++) {
828      ObjCProtocolDecl *rhsProto = rhsQID->getProtocols(j);
829      if (!ClassImplementsProtocol(rhsProto, lhsID, compare, true))
830        return false;
831    }
832    return true;
833  }
834  return false;
835}
836
837