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