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