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