SemaDeclObjC.cpp revision 22b6e0682d69173b4282853aded2f9253f3e2c15
1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
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 declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/Parse/DeclSpec.h"
19using namespace clang;
20
21/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
22/// and user declared, in the method definition's AST.
23void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) {
24  assert(getCurMethodDecl() == 0 && "Method parsing confused");
25  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D.getAs<Decl>());
26
27  // If we don't have a valid method decl, simply return.
28  if (!MDecl)
29    return;
30
31  // Allow the rest of sema to find private method decl implementations.
32  if (MDecl->isInstanceMethod())
33    AddInstanceMethodToGlobalPool(MDecl);
34  else
35    AddFactoryMethodToGlobalPool(MDecl);
36
37  // Allow all of Sema to see that we are entering a method definition.
38  PushDeclContext(FnBodyScope, MDecl);
39
40  // Create Decl objects for each parameter, entrring them in the scope for
41  // binding to their use.
42
43  // Insert the invisible arguments, self and _cmd!
44  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
45
46  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
47  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
48
49  // Introduce all of the other parameters into this scope.
50  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
51       E = MDecl->param_end(); PI != E; ++PI)
52    if ((*PI)->getIdentifier())
53      PushOnScopeChains(*PI, FnBodyScope);
54}
55
56Sema::DeclPtrTy Sema::
57ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
58                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
59                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
60                         const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs,
61                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
62  assert(ClassName && "Missing class identifier");
63
64  // Check for another declaration kind with the same name.
65  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
66  if (PrevDecl && PrevDecl->isTemplateParameter()) {
67    // Maybe we will complain about the shadowed template parameter.
68    DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
69    // Just pretend that we didn't see the previous declaration.
70    PrevDecl = 0;
71  }
72
73  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
74    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
75    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
76  }
77
78  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
79  if (IDecl) {
80    // Class already seen. Is it a forward declaration?
81    if (!IDecl->isForwardDecl()) {
82      IDecl->setInvalidDecl();
83      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
84      Diag(IDecl->getLocation(), diag::note_previous_definition);
85
86      // Return the previous class interface.
87      // FIXME: don't leak the objects passed in!
88      return DeclPtrTy::make(IDecl);
89    } else {
90      IDecl->setLocation(AtInterfaceLoc);
91      IDecl->setForwardDecl(false);
92    }
93  } else {
94    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
95                                      ClassName, ClassLoc);
96    if (AttrList)
97      ProcessDeclAttributeList(IDecl, AttrList);
98
99    ObjCInterfaceDecls[ClassName] = IDecl;
100    // FIXME: PushOnScopeChains
101    CurContext->addDecl(IDecl);
102    // Remember that this needs to be removed when the scope is popped.
103    TUScope->AddDecl(DeclPtrTy::make(IDecl));
104  }
105
106  if (SuperName) {
107    // Check if a different kind of symbol declared in this scope.
108    PrevDecl = LookupName(TUScope, SuperName, LookupOrdinaryName);
109
110    ObjCInterfaceDecl *SuperClassDecl =
111                                  dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
112
113    // Diagnose classes that inherit from deprecated classes.
114    if (SuperClassDecl)
115      (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
116
117    if (PrevDecl && SuperClassDecl == 0) {
118      // The previous declaration was not a class decl. Check if we have a
119      // typedef. If we do, get the underlying class type.
120      if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
121        QualType T = TDecl->getUnderlyingType();
122        if (T->isObjCInterfaceType()) {
123          if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl())
124            SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
125        }
126      }
127
128      // This handles the following case:
129      //
130      // typedef int SuperClass;
131      // @interface MyClass : SuperClass {} @end
132      //
133      if (!SuperClassDecl) {
134        Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
135        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
136      }
137    }
138
139    if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
140      if (!SuperClassDecl)
141        Diag(SuperLoc, diag::err_undef_superclass)
142          << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
143      else if (SuperClassDecl->isForwardDecl())
144        Diag(SuperLoc, diag::err_undef_superclass)
145          << SuperClassDecl->getDeclName() << ClassName
146          << SourceRange(AtInterfaceLoc, ClassLoc);
147    }
148    IDecl->setSuperClass(SuperClassDecl);
149    IDecl->setSuperClassLoc(SuperLoc);
150    IDecl->setLocEnd(SuperLoc);
151  } else { // we have a root class.
152    IDecl->setLocEnd(ClassLoc);
153  }
154
155  /// Check then save referenced protocols.
156  if (NumProtoRefs) {
157    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
158                           Context);
159    IDecl->setLocEnd(EndProtoLoc);
160  }
161
162  CheckObjCDeclScope(IDecl);
163  return DeclPtrTy::make(IDecl);
164}
165
166/// ActOnCompatiblityAlias - this action is called after complete parsing of
167/// @compatibility_alias declaration. It sets up the alias relationships.
168Sema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
169                                             IdentifierInfo *AliasName,
170                                             SourceLocation AliasLocation,
171                                             IdentifierInfo *ClassName,
172                                             SourceLocation ClassLocation) {
173  // Look for previous declaration of alias name
174  NamedDecl *ADecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
175  if (ADecl) {
176    if (isa<ObjCCompatibleAliasDecl>(ADecl))
177      Diag(AliasLocation, diag::warn_previous_alias_decl);
178    else
179      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
180    Diag(ADecl->getLocation(), diag::note_previous_declaration);
181    return DeclPtrTy();
182  }
183  // Check for class declaration
184  NamedDecl *CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
185  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
186    QualType T = TDecl->getUnderlyingType();
187    if (T->isObjCInterfaceType()) {
188      if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl()) {
189        ClassName = IDecl->getIdentifier();
190        CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
191      }
192    }
193  }
194  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
195  if (CDecl == 0) {
196    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
197    if (CDeclU)
198      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
199    return DeclPtrTy();
200  }
201
202  // Everything checked out, instantiate a new alias declaration AST.
203  ObjCCompatibleAliasDecl *AliasDecl =
204    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
205
206  ObjCAliasDecls[AliasName] = AliasDecl;
207
208  // FIXME: PushOnScopeChains?
209  CurContext->addDecl(AliasDecl);
210  if (!CheckObjCDeclScope(AliasDecl))
211    TUScope->AddDecl(DeclPtrTy::make(AliasDecl));
212
213  return DeclPtrTy::make(AliasDecl);
214}
215
216void Sema::CheckForwardProtocolDeclarationForCircularDependency(
217  IdentifierInfo *PName,
218  SourceLocation &Ploc, SourceLocation PrevLoc,
219  const ObjCList<ObjCProtocolDecl> &PList)
220{
221  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
222       E = PList.end(); I != E; ++I) {
223
224    if (ObjCProtocolDecl *PDecl = ObjCProtocols[(*I)->getIdentifier()]) {
225      if (PDecl->getIdentifier() == PName) {
226        Diag(Ploc, diag::err_protocol_has_circular_dependency);
227        Diag(PrevLoc, diag::note_previous_definition);
228      }
229      CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
230        PDecl->getLocation(), PDecl->getReferencedProtocols());
231    }
232  }
233}
234
235Sema::DeclPtrTy
236Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
237                                  IdentifierInfo *ProtocolName,
238                                  SourceLocation ProtocolLoc,
239                                  const DeclPtrTy *ProtoRefs,
240                                  unsigned NumProtoRefs,
241                                  SourceLocation EndProtoLoc,
242                                  AttributeList *AttrList) {
243  // FIXME: Deal with AttrList.
244  assert(ProtocolName && "Missing protocol identifier");
245  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
246  if (PDecl) {
247    // Protocol already seen. Better be a forward protocol declaration
248    if (!PDecl->isForwardDecl()) {
249      PDecl->setInvalidDecl();
250      Diag(ProtocolLoc, diag::err_duplicate_protocol_def) << ProtocolName;
251      Diag(PDecl->getLocation(), diag::note_previous_definition);
252      // Just return the protocol we already had.
253      // FIXME: don't leak the objects passed in!
254      return DeclPtrTy::make(PDecl);
255    }
256    ObjCList<ObjCProtocolDecl> PList;
257    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
258    CheckForwardProtocolDeclarationForCircularDependency(
259      ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
260    PList.Destroy(Context);
261
262    // Make sure the cached decl gets a valid start location.
263    PDecl->setLocation(AtProtoInterfaceLoc);
264    PDecl->setForwardDecl(false);
265  } else {
266    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
267                                     AtProtoInterfaceLoc,ProtocolName);
268    // FIXME: PushOnScopeChains?
269    CurContext->addDecl(PDecl);
270    PDecl->setForwardDecl(false);
271    ObjCProtocols[ProtocolName] = PDecl;
272  }
273  if (AttrList)
274    ProcessDeclAttributeList(PDecl, AttrList);
275  if (NumProtoRefs) {
276    /// Check then save referenced protocols.
277    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,Context);
278    PDecl->setLocEnd(EndProtoLoc);
279  }
280
281  CheckObjCDeclScope(PDecl);
282  return DeclPtrTy::make(PDecl);
283}
284
285/// FindProtocolDeclaration - This routine looks up protocols and
286/// issues an error if they are not declared. It returns list of
287/// protocol declarations in its 'Protocols' argument.
288void
289Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
290                              const IdentifierLocPair *ProtocolId,
291                              unsigned NumProtocols,
292                              llvm::SmallVectorImpl<DeclPtrTy> &Protocols) {
293  for (unsigned i = 0; i != NumProtocols; ++i) {
294    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
295    if (!PDecl) {
296      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
297        << ProtocolId[i].first;
298      continue;
299    }
300
301    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
302
303    // If this is a forward declaration and we are supposed to warn in this
304    // case, do it.
305    if (WarnOnDeclarations && PDecl->isForwardDecl())
306      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
307        << ProtocolId[i].first;
308    Protocols.push_back(DeclPtrTy::make(PDecl));
309  }
310}
311
312/// DiagnosePropertyMismatch - Compares two properties for their
313/// attributes and types and warns on a variety of inconsistencies.
314///
315void
316Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
317                               ObjCPropertyDecl *SuperProperty,
318                               const IdentifierInfo *inheritedName) {
319  ObjCPropertyDecl::PropertyAttributeKind CAttr =
320  Property->getPropertyAttributes();
321  ObjCPropertyDecl::PropertyAttributeKind SAttr =
322  SuperProperty->getPropertyAttributes();
323  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
324      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
325    Diag(Property->getLocation(), diag::warn_readonly_property)
326      << Property->getDeclName() << inheritedName;
327  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
328      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
329    Diag(Property->getLocation(), diag::warn_property_attribute)
330      << Property->getDeclName() << "copy" << inheritedName;
331  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
332           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
333    Diag(Property->getLocation(), diag::warn_property_attribute)
334      << Property->getDeclName() << "retain" << inheritedName;
335
336  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
337      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
338    Diag(Property->getLocation(), diag::warn_property_attribute)
339      << Property->getDeclName() << "atomic" << inheritedName;
340  if (Property->getSetterName() != SuperProperty->getSetterName())
341    Diag(Property->getLocation(), diag::warn_property_attribute)
342      << Property->getDeclName() << "setter" << inheritedName;
343  if (Property->getGetterName() != SuperProperty->getGetterName())
344    Diag(Property->getLocation(), diag::warn_property_attribute)
345      << Property->getDeclName() << "getter" << inheritedName;
346
347  QualType LHSType =
348    Context.getCanonicalType(SuperProperty->getType());
349  QualType RHSType =
350    Context.getCanonicalType(Property->getType());
351
352  if (!Context.typesAreCompatible(LHSType, RHSType)) {
353    // FIXME: Incorporate this test with typesAreCompatible.
354    if (LHSType->isObjCQualifiedIdType() && RHSType->isObjCQualifiedIdType())
355      if (ObjCQualifiedIdTypesAreCompatible(LHSType, RHSType, false))
356        return;
357    Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
358      << Property->getType() << SuperProperty->getType() << inheritedName;
359  }
360}
361
362/// ComparePropertiesInBaseAndSuper - This routine compares property
363/// declarations in base and its super class, if any, and issues
364/// diagnostics in a variety of inconsistant situations.
365///
366void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
367  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
368  if (!SDecl)
369    return;
370  // FIXME: O(N^2)
371  for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(),
372       E = SDecl->prop_end(); S != E; ++S) {
373    ObjCPropertyDecl *SuperPDecl = (*S);
374    // Does property in super class has declaration in current class?
375    for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(),
376         E = IDecl->prop_end(); I != E; ++I) {
377      ObjCPropertyDecl *PDecl = (*I);
378      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
379          DiagnosePropertyMismatch(PDecl, SuperPDecl,
380                                   SDecl->getIdentifier());
381    }
382  }
383}
384
385/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
386/// of properties declared in a protocol and adds them to the list
387/// of properties for current class/category if it is not there already.
388void
389Sema::MergeOneProtocolPropertiesIntoClass(Decl *CDecl,
390                                          ObjCProtocolDecl *PDecl) {
391  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
392  if (!IDecl) {
393    // Category
394    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
395    assert (CatDecl && "MergeOneProtocolPropertiesIntoClass");
396    for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
397         E = PDecl->prop_end(); P != E; ++P) {
398      ObjCPropertyDecl *Pr = (*P);
399      ObjCCategoryDecl::prop_iterator CP, CE;
400      // Is this property already in  category's list of properties?
401      for (CP = CatDecl->prop_begin(), CE = CatDecl->prop_end();
402           CP != CE; ++CP)
403        if ((*CP)->getIdentifier() == Pr->getIdentifier())
404          break;
405      if (CP != CE)
406        // Property protocol already exist in class. Diagnose any mismatch.
407        DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
408    }
409    return;
410  }
411  for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
412       E = PDecl->prop_end(); P != E; ++P) {
413    ObjCPropertyDecl *Pr = (*P);
414    ObjCInterfaceDecl::prop_iterator CP, CE;
415    // Is this property already in  class's list of properties?
416    for (CP = IDecl->prop_begin(), CE = IDecl->prop_end();
417         CP != CE; ++CP)
418      if ((*CP)->getIdentifier() == Pr->getIdentifier())
419        break;
420    if (CP != CE)
421      // Property protocol already exist in class. Diagnose any mismatch.
422      DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
423    }
424}
425
426/// MergeProtocolPropertiesIntoClass - This routine merges properties
427/// declared in 'MergeItsProtocols' objects (which can be a class or an
428/// inherited protocol into the list of properties for class/category 'CDecl'
429///
430void Sema::MergeProtocolPropertiesIntoClass(Decl *CDecl,
431                                            DeclPtrTy MergeItsProtocols) {
432  Decl *ClassDecl = MergeItsProtocols.getAs<Decl>();
433  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
434
435  if (!IDecl) {
436    // Category
437    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
438    assert (CatDecl && "MergeProtocolPropertiesIntoClass");
439    if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
440      for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
441           E = MDecl->protocol_end(); P != E; ++P)
442      // Merge properties of category (*P) into IDECL's
443      MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
444
445      // Go thru the list of protocols for this category and recursively merge
446      // their properties into this class as well.
447      for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
448           E = CatDecl->protocol_end(); P != E; ++P)
449        MergeProtocolPropertiesIntoClass(CatDecl, DeclPtrTy::make(*P));
450    } else {
451      ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
452      for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
453           E = MD->protocol_end(); P != E; ++P)
454        MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
455    }
456    return;
457  }
458
459  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
460    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
461         E = MDecl->protocol_end(); P != E; ++P)
462      // Merge properties of class (*P) into IDECL's
463      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
464
465    // Go thru the list of protocols for this class and recursively merge
466    // their properties into this class as well.
467    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
468         E = IDecl->protocol_end(); P != E; ++P)
469      MergeProtocolPropertiesIntoClass(IDecl, DeclPtrTy::make(*P));
470  } else {
471    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
472    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
473         E = MD->protocol_end(); P != E; ++P)
474      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
475  }
476}
477
478/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
479/// a class method in its extension.
480///
481void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
482                                            ObjCInterfaceDecl *ID) {
483  if (!ID)
484    return;  // Possibly due to previous error
485
486  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
487  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
488       e =  ID->meth_end(); i != e; ++i) {
489    ObjCMethodDecl *MD = *i;
490    MethodMap[MD->getSelector()] = MD;
491  }
492
493  if (MethodMap.empty())
494    return;
495  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
496       e =  CAT->meth_end(); i != e; ++i) {
497    ObjCMethodDecl *Method = *i;
498    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
499    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
500      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
501            << Method->getDeclName();
502      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
503    }
504  }
505}
506
507/// ActOnForwardProtocolDeclaration -
508Action::DeclPtrTy
509Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
510                                      const IdentifierLocPair *IdentList,
511                                      unsigned NumElts,
512                                      AttributeList *attrList) {
513  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
514
515  for (unsigned i = 0; i != NumElts; ++i) {
516    IdentifierInfo *Ident = IdentList[i].first;
517    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
518    if (PDecl == 0) { // Not already seen?
519      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
520                                       IdentList[i].second, Ident);
521      // FIXME: PushOnScopeChains?
522      CurContext->addDecl(PDecl);
523    }
524    if (attrList)
525      ProcessDeclAttributeList(PDecl, attrList);
526    Protocols.push_back(PDecl);
527  }
528
529  ObjCForwardProtocolDecl *PDecl =
530    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
531                                    &Protocols[0], Protocols.size());
532  CurContext->addDecl(PDecl);
533  CheckObjCDeclScope(PDecl);
534  return DeclPtrTy::make(PDecl);
535}
536
537Sema::DeclPtrTy Sema::
538ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
539                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
540                            IdentifierInfo *CategoryName,
541                            SourceLocation CategoryLoc,
542                            const DeclPtrTy *ProtoRefs,
543                            unsigned NumProtoRefs,
544                            SourceLocation EndProtoLoc) {
545  ObjCCategoryDecl *CDecl =
546    ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, CategoryName);
547  // FIXME: PushOnScopeChains?
548  CurContext->addDecl(CDecl);
549
550  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
551  /// Check that class of this category is already completely declared.
552  if (!IDecl || IDecl->isForwardDecl()) {
553    CDecl->setInvalidDecl();
554    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
555    return DeclPtrTy::make(CDecl);
556  }
557
558  CDecl->setClassInterface(IDecl);
559
560  // If the interface is deprecated, warn about it.
561  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
562
563  /// Check for duplicate interface declaration for this category
564  ObjCCategoryDecl *CDeclChain;
565  for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
566       CDeclChain = CDeclChain->getNextClassCategory()) {
567    if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
568      Diag(CategoryLoc, diag::warn_dup_category_def)
569      << ClassName << CategoryName;
570      Diag(CDeclChain->getLocation(), diag::note_previous_definition);
571      break;
572    }
573  }
574  if (!CDeclChain)
575    CDecl->insertNextClassCategory();
576
577  if (NumProtoRefs) {
578    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,Context);
579    CDecl->setLocEnd(EndProtoLoc);
580  }
581
582  CheckObjCDeclScope(CDecl);
583  return DeclPtrTy::make(CDecl);
584}
585
586/// ActOnStartCategoryImplementation - Perform semantic checks on the
587/// category implementation declaration and build an ObjCCategoryImplDecl
588/// object.
589Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
590                      SourceLocation AtCatImplLoc,
591                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
592                      IdentifierInfo *CatName, SourceLocation CatLoc) {
593  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
594  ObjCCategoryImplDecl *CDecl =
595    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
596                                 IDecl);
597  /// Check that class of this category is already completely declared.
598  if (!IDecl || IDecl->isForwardDecl())
599    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
600
601  // FIXME: PushOnScopeChains?
602  CurContext->addDecl(CDecl);
603
604  /// TODO: Check that CatName, category name, is not used in another
605  // implementation.
606  ObjCCategoryImpls.push_back(CDecl);
607
608  CheckObjCDeclScope(CDecl);
609  return DeclPtrTy::make(CDecl);
610}
611
612Sema::DeclPtrTy Sema::ActOnStartClassImplementation(
613                      SourceLocation AtClassImplLoc,
614                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
615                      IdentifierInfo *SuperClassname,
616                      SourceLocation SuperClassLoc) {
617  ObjCInterfaceDecl* IDecl = 0;
618  // Check for another declaration kind with the same name.
619  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
620  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
621    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
622    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
623  }  else {
624    // Is there an interface declaration of this class; if not, warn!
625    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
626    if (!IDecl)
627      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
628  }
629
630  // Check that super class name is valid class name
631  ObjCInterfaceDecl* SDecl = 0;
632  if (SuperClassname) {
633    // Check if a different kind of symbol declared in this scope.
634    PrevDecl = LookupName(TUScope, SuperClassname, LookupOrdinaryName);
635    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
636      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
637        << SuperClassname;
638      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
639    } else {
640      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
641      if (!SDecl)
642        Diag(SuperClassLoc, diag::err_undef_superclass)
643          << SuperClassname << ClassName;
644      else if (IDecl && IDecl->getSuperClass() != SDecl) {
645        // This implementation and its interface do not have the same
646        // super class.
647        Diag(SuperClassLoc, diag::err_conflicting_super_class)
648          << SDecl->getDeclName();
649        Diag(SDecl->getLocation(), diag::note_previous_definition);
650      }
651    }
652  }
653
654  if (!IDecl) {
655    // Legacy case of @implementation with no corresponding @interface.
656    // Build, chain & install the interface decl into the identifier.
657
658    // FIXME: Do we support attributes on the @implementation? If so
659    // we should copy them over.
660    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
661                                      ClassName, ClassLoc, false, true);
662    ObjCInterfaceDecls[ClassName] = IDecl;
663    IDecl->setSuperClass(SDecl);
664    IDecl->setLocEnd(ClassLoc);
665
666    // FIXME: PushOnScopeChains?
667    CurContext->addDecl(IDecl);
668    // Remember that this needs to be removed when the scope is popped.
669    TUScope->AddDecl(DeclPtrTy::make(IDecl));
670  }
671
672  ObjCImplementationDecl* IMPDecl =
673    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
674                                   IDecl, SDecl);
675
676  // FIXME: PushOnScopeChains?
677  CurContext->addDecl(IMPDecl);
678
679  if (CheckObjCDeclScope(IMPDecl))
680    return DeclPtrTy::make(IMPDecl);
681
682  // Check that there is no duplicate implementation of this class.
683  if (ObjCImplementations[ClassName])
684    // FIXME: Don't leak everything!
685    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
686  else // add it to the list.
687    ObjCImplementations[ClassName] = IMPDecl;
688  return DeclPtrTy::make(IMPDecl);
689}
690
691void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
692                                    ObjCIvarDecl **ivars, unsigned numIvars,
693                                    SourceLocation RBrace) {
694  assert(ImpDecl && "missing implementation decl");
695  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
696  if (!IDecl)
697    return;
698  /// Check case of non-existing @interface decl.
699  /// (legacy objective-c @implementation decl without an @interface decl).
700  /// Add implementations's ivar to the synthesize class's ivar list.
701  if (IDecl->ImplicitInterfaceDecl()) {
702    IDecl->setIVarList(ivars, numIvars, Context);
703    IDecl->setLocEnd(RBrace);
704    return;
705  }
706  // If implementation has empty ivar list, just return.
707  if (numIvars == 0)
708    return;
709
710  assert(ivars && "missing @implementation ivars");
711
712  // Check interface's Ivar list against those in the implementation.
713  // names and types must match.
714  //
715  unsigned j = 0;
716  ObjCInterfaceDecl::ivar_iterator
717    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
718  for (; numIvars > 0 && IVI != IVE; ++IVI) {
719    ObjCIvarDecl* ImplIvar = ivars[j++];
720    ObjCIvarDecl* ClsIvar = *IVI;
721    assert (ImplIvar && "missing implementation ivar");
722    assert (ClsIvar && "missing class ivar");
723
724    // First, make sure the types match.
725    if (Context.getCanonicalType(ImplIvar->getType()) !=
726        Context.getCanonicalType(ClsIvar->getType())) {
727      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
728        << ImplIvar->getIdentifier()
729        << ImplIvar->getType() << ClsIvar->getType();
730      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
731    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
732      Expr *ImplBitWidth = ImplIvar->getBitWidth();
733      Expr *ClsBitWidth = ClsIvar->getBitWidth();
734      if (ImplBitWidth->getIntegerConstantExprValue(Context).getZExtValue() !=
735          ClsBitWidth->getIntegerConstantExprValue(Context).getZExtValue()) {
736        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
737          << ImplIvar->getIdentifier();
738        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
739      }
740    }
741    // Make sure the names are identical.
742    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
743      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
744        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
745      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
746    }
747    --numIvars;
748  }
749
750  if (numIvars > 0)
751    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
752  else if (IVI != IVE)
753    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
754}
755
756void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
757                               bool &IncompleteImpl) {
758  if (!IncompleteImpl) {
759    Diag(ImpLoc, diag::warn_incomplete_impl);
760    IncompleteImpl = true;
761  }
762  Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName();
763}
764
765void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
766                                       ObjCMethodDecl *IntfMethodDecl) {
767  bool err = false;
768  QualType ImpMethodQType =
769    Context.getCanonicalType(ImpMethodDecl->getResultType());
770  QualType IntfMethodQType =
771    Context.getCanonicalType(IntfMethodDecl->getResultType());
772  if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType))
773    err = true;
774  else for (ObjCMethodDecl::param_iterator IM=ImpMethodDecl->param_begin(),
775            IF=IntfMethodDecl->param_begin(),
776            EM=ImpMethodDecl->param_end(); IM!=EM; ++IM, IF++) {
777    ImpMethodQType = Context.getCanonicalType((*IM)->getType());
778    IntfMethodQType = Context.getCanonicalType((*IF)->getType());
779    if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType)) {
780      err = true;
781      break;
782    }
783  }
784  if (err) {
785    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_types)
786    << ImpMethodDecl->getDeclName();
787    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
788  }
789}
790
791/// isPropertyReadonly - Return true if property is readonly, by searching
792/// for the property in the class and in its categories and implementations
793///
794bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl,
795                              ObjCInterfaceDecl *IDecl) {
796  // by far the most common case.
797  if (!PDecl->isReadOnly())
798    return false;
799  // Even if property is ready only, if interface has a user defined setter,
800  // it is not considered read only.
801  if (IDecl->getInstanceMethod(PDecl->getSetterName()))
802    return false;
803
804  // Main class has the property as 'readonly'. Must search
805  // through the category list to see if the property's
806  // attribute has been over-ridden to 'readwrite'.
807  for (ObjCCategoryDecl *Category = IDecl->getCategoryList();
808       Category; Category = Category->getNextClassCategory()) {
809    // Even if property is ready only, if a category has a user defined setter,
810    // it is not considered read only.
811    if (Category->getInstanceMethod(PDecl->getSetterName()))
812      return false;
813    ObjCPropertyDecl *P =
814    Category->FindPropertyDeclaration(PDecl->getIdentifier());
815    if (P && !P->isReadOnly())
816      return false;
817  }
818
819  // Also, check for definition of a setter method in the implementation if
820  // all else failed.
821  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) {
822    if (ObjCImplementationDecl *IMD =
823        dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) {
824      if (IMD->getInstanceMethod(PDecl->getSetterName()))
825        return false;
826    }
827    else if (ObjCCategoryImplDecl *CIMD =
828             dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
829      if (CIMD->getInstanceMethod(PDecl->getSetterName()))
830        return false;
831    }
832  }
833  // Lastly, look through the implementation (if one is in scope).
834  if (ObjCImplementationDecl *ImpDecl =
835        ObjCImplementations[IDecl->getIdentifier()])
836    if (ImpDecl->getInstanceMethod(PDecl->getSetterName()))
837      return false;
838  return true;
839}
840
841/// FIXME: Type hierarchies in Objective-C can be deep. We could most
842/// likely improve the efficiency of selector lookups and type
843/// checking by associating with each protocol / interface / category
844/// the flattened instance tables. If we used an immutable set to keep
845/// the table then it wouldn't add significant memory cost and it
846/// would be handy for lookups.
847
848/// CheckProtocolMethodDefs - This routine checks unimplemented methods
849/// Declared in protocol, and those referenced by it.
850void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
851                                   ObjCProtocolDecl *PDecl,
852                                   bool& IncompleteImpl,
853                                   const llvm::DenseSet<Selector> &InsMap,
854                                   const llvm::DenseSet<Selector> &ClsMap,
855                                   ObjCInterfaceDecl *IDecl) {
856  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
857
858  // If a method lookup fails locally we still need to look and see if
859  // the method was implemented by a base class or an inherited
860  // protocol. This lookup is slow, but occurs rarely in correct code
861  // and otherwise would terminate in a warning.
862
863  // check unimplemented instance methods.
864  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
865       E = PDecl->instmeth_end(); I != E; ++I) {
866    ObjCMethodDecl *method = *I;
867    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
868        !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
869        (!Super || !Super->lookupInstanceMethod(method->getSelector())))
870      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
871  }
872  // check unimplemented class methods
873  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
874       E = PDecl->classmeth_end(); I != E; ++I) {
875    ObjCMethodDecl *method = *I;
876    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
877        !ClsMap.count(method->getSelector()) &&
878        (!Super || !Super->lookupClassMethod(method->getSelector())))
879      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
880  }
881  // Check on this protocols's referenced protocols, recursively.
882  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
883       E = PDecl->protocol_end(); PI != E; ++PI)
884    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
885}
886
887void Sema::ImplMethodsVsClassMethods(ObjCImplDecl* IMPDecl,
888                                     ObjCContainerDecl* CDecl,
889                                     bool IncompleteImpl) {
890  llvm::DenseSet<Selector> InsMap;
891  // Check and see if instance methods in class interface have been
892  // implemented in the implementation class.
893  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
894       E = IMPDecl->instmeth_end(); I != E; ++I)
895    InsMap.insert((*I)->getSelector());
896
897  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
898       E = CDecl->instmeth_end(); I != E; ++I) {
899    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector())) {
900      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
901      continue;
902    }
903
904    ObjCMethodDecl *ImpMethodDecl =
905      IMPDecl->getInstanceMethod((*I)->getSelector());
906    ObjCMethodDecl *IntfMethodDecl =
907      CDecl->getInstanceMethod((*I)->getSelector());
908    assert(IntfMethodDecl &&
909           "IntfMethodDecl is null in ImplMethodsVsClassMethods");
910    // ImpMethodDecl may be null as in a @dynamic property.
911    if (ImpMethodDecl)
912      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
913  }
914
915  llvm::DenseSet<Selector> ClsMap;
916  // Check and see if class methods in class interface have been
917  // implemented in the implementation class.
918  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
919       E = IMPDecl->classmeth_end(); I != E; ++I)
920    ClsMap.insert((*I)->getSelector());
921
922  for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
923       E = CDecl->classmeth_end(); I != E; ++I)
924    if (!ClsMap.count((*I)->getSelector()))
925      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
926    else {
927      ObjCMethodDecl *ImpMethodDecl =
928        IMPDecl->getClassMethod((*I)->getSelector());
929      ObjCMethodDecl *IntfMethodDecl =
930        CDecl->getClassMethod((*I)->getSelector());
931      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
932    }
933
934
935  // Check the protocol list for unimplemented methods in the @implementation
936  // class.
937  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
938    for (ObjCCategoryDecl::protocol_iterator PI = I->protocol_begin(),
939         E = I->protocol_end(); PI != E; ++PI)
940      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
941                              InsMap, ClsMap, I);
942    // Check class extensions (unnamed categories)
943    for (ObjCCategoryDecl *Categories = I->getCategoryList();
944         Categories; Categories = Categories->getNextClassCategory()) {
945      if (!Categories->getIdentifier()) {
946        ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl);
947        break;
948      }
949    }
950  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
951    for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
952         E = C->protocol_end(); PI != E; ++PI)
953      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
954                              InsMap, ClsMap, C->getClassInterface());
955  } else
956    assert(false && "invalid ObjCContainerDecl type.");
957}
958
959/// ActOnForwardClassDeclaration -
960Action::DeclPtrTy
961Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
962                                   IdentifierInfo **IdentList,
963                                   unsigned NumElts) {
964  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
965
966  for (unsigned i = 0; i != NumElts; ++i) {
967    // Check for another declaration kind with the same name.
968    NamedDecl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName);
969    if (PrevDecl && PrevDecl->isTemplateParameter()) {
970      // Maybe we will complain about the shadowed template parameter.
971      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
972      // Just pretend that we didn't see the previous declaration.
973      PrevDecl = 0;
974    }
975
976    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
977      // GCC apparently allows the following idiom:
978      //
979      // typedef NSObject < XCElementTogglerP > XCElementToggler;
980      // @class XCElementToggler;
981      //
982      // FIXME: Make an extension?
983      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
984      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
985        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
986        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
987      }
988    }
989    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
990    if (!IDecl) {  // Not already seen?  Make a forward decl.
991      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
992                                        IdentList[i], SourceLocation(), true);
993      ObjCInterfaceDecls[IdentList[i]] = IDecl;
994
995      // FIXME: PushOnScopeChains?
996      CurContext->addDecl(IDecl);
997      // Remember that this needs to be removed when the scope is popped.
998      TUScope->AddDecl(DeclPtrTy::make(IDecl));
999    }
1000
1001    Interfaces.push_back(IDecl);
1002  }
1003
1004  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1005                                               &Interfaces[0],
1006                                               Interfaces.size());
1007  CurContext->addDecl(CDecl);
1008  CheckObjCDeclScope(CDecl);
1009  return DeclPtrTy::make(CDecl);
1010}
1011
1012
1013/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1014/// returns true, or false, accordingly.
1015/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1016bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1017                                      const ObjCMethodDecl *PrevMethod,
1018                                      bool matchBasedOnSizeAndAlignment) {
1019  QualType T1 = Context.getCanonicalType(Method->getResultType());
1020  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1021
1022  if (T1 != T2) {
1023    // The result types are different.
1024    if (!matchBasedOnSizeAndAlignment)
1025      return false;
1026    // Incomplete types don't have a size and alignment.
1027    if (T1->isIncompleteType() || T2->isIncompleteType())
1028      return false;
1029    // Check is based on size and alignment.
1030    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1031      return false;
1032  }
1033
1034  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1035       E = Method->param_end();
1036  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1037
1038  for (; ParamI != E; ++ParamI, ++PrevI) {
1039    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1040    T1 = Context.getCanonicalType((*ParamI)->getType());
1041    T2 = Context.getCanonicalType((*PrevI)->getType());
1042    if (T1 != T2) {
1043      // The result types are different.
1044      if (!matchBasedOnSizeAndAlignment)
1045        return false;
1046      // Incomplete types don't have a size and alignment.
1047      if (T1->isIncompleteType() || T2->isIncompleteType())
1048        return false;
1049      // Check is based on size and alignment.
1050      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1051        return false;
1052    }
1053  }
1054  return true;
1055}
1056
1057void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1058  ObjCMethodList &Entry = InstanceMethodPool[Method->getSelector()];
1059  if (Entry.Method == 0) {
1060    // Haven't seen a method with this selector name yet - add it.
1061    Entry.Method = Method;
1062    Entry.Next = 0;
1063    return;
1064  }
1065
1066  // We've seen a method with this name, see if we have already seen this type
1067  // signature.
1068  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1069    if (MatchTwoMethodDeclarations(Method, List->Method))
1070      return;
1071
1072  // We have a new signature for an existing method - add it.
1073  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1074  Entry.Next = new ObjCMethodList(Method, Entry.Next);
1075}
1076
1077// FIXME: Finish implementing -Wno-strict-selector-match.
1078ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1079                                                       SourceRange R) {
1080  ObjCMethodList &MethList = InstanceMethodPool[Sel];
1081  bool issueWarning = false;
1082
1083  if (MethList.Method && MethList.Next) {
1084    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1085      // This checks if the methods differ by size & alignment.
1086      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1087        issueWarning = true;
1088  }
1089  if (issueWarning && (MethList.Method && MethList.Next)) {
1090    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1091    Diag(MethList.Method->getLocStart(), diag::note_using_decl)
1092      << MethList.Method->getSourceRange();
1093    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1094      Diag(Next->Method->getLocStart(), diag::note_also_found_decl)
1095        << Next->Method->getSourceRange();
1096  }
1097  return MethList.Method;
1098}
1099
1100void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1101  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
1102  if (!FirstMethod.Method) {
1103    // Haven't seen a method with this selector name yet - add it.
1104    FirstMethod.Method = Method;
1105    FirstMethod.Next = 0;
1106  } else {
1107    // We've seen a method with this name, now check the type signature(s).
1108    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1109
1110    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1111         Next = Next->Next)
1112      match = MatchTwoMethodDeclarations(Method, Next->Method);
1113
1114    if (!match) {
1115      // We have a new signature for an existing method - add it.
1116      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1117      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
1118      FirstMethod.Next = OMI;
1119    }
1120  }
1121}
1122
1123/// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1124/// have the property type and issue diagnostics if they don't.
1125/// Also synthesize a getter/setter method if none exist (and update the
1126/// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1127/// methods is the "right" thing to do.
1128void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1129                               ObjCContainerDecl *CD) {
1130  ObjCMethodDecl *GetterMethod, *SetterMethod;
1131
1132  GetterMethod = CD->getInstanceMethod(property->getGetterName());
1133  SetterMethod = CD->getInstanceMethod(property->getSetterName());
1134
1135  if (GetterMethod &&
1136      GetterMethod->getResultType() != property->getType()) {
1137    Diag(property->getLocation(),
1138         diag::err_accessor_property_type_mismatch)
1139      << property->getDeclName()
1140      << GetterMethod->getSelector();
1141    Diag(GetterMethod->getLocation(), diag::note_declared_at);
1142  }
1143
1144  if (SetterMethod) {
1145    if (Context.getCanonicalType(SetterMethod->getResultType())
1146        != Context.VoidTy)
1147      Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1148    if (SetterMethod->param_size() != 1 ||
1149        ((*SetterMethod->param_begin())->getType() != property->getType())) {
1150      Diag(property->getLocation(),
1151           diag::err_accessor_property_type_mismatch)
1152        << property->getDeclName()
1153        << SetterMethod->getSelector();
1154      Diag(SetterMethod->getLocation(), diag::note_declared_at);
1155    }
1156  }
1157
1158  // Synthesize getter/setter methods if none exist.
1159  // Find the default getter and if one not found, add one.
1160  // FIXME: The synthesized property we set here is misleading. We
1161  // almost always synthesize these methods unless the user explicitly
1162  // provided prototypes (which is odd, but allowed). Sema should be
1163  // typechecking that the declarations jive in that situation (which
1164  // it is not currently).
1165  if (!GetterMethod) {
1166    // No instance method of same name as property getter name was found.
1167    // Declare a getter method and add it to the list of methods
1168    // for this class.
1169    GetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1170                             property->getLocation(), property->getGetterName(),
1171                             property->getType(), CD, true, false, true,
1172                             (property->getPropertyImplementation() ==
1173                              ObjCPropertyDecl::Optional) ?
1174                             ObjCMethodDecl::Optional :
1175                             ObjCMethodDecl::Required);
1176    CD->addDecl(GetterMethod);
1177  } else
1178    // A user declared getter will be synthesize when @synthesize of
1179    // the property with the same name is seen in the @implementation
1180    GetterMethod->setIsSynthesized();
1181  property->setGetterMethodDecl(GetterMethod);
1182
1183  // Skip setter if property is read-only.
1184  if (!property->isReadOnly()) {
1185    // Find the default setter and if one not found, add one.
1186    if (!SetterMethod) {
1187      // No instance method of same name as property setter name was found.
1188      // Declare a setter method and add it to the list of methods
1189      // for this class.
1190      SetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1191                               property->getLocation(),
1192                               property->getSetterName(),
1193                               Context.VoidTy, CD, true, false, true,
1194                               (property->getPropertyImplementation() ==
1195                                ObjCPropertyDecl::Optional) ?
1196                               ObjCMethodDecl::Optional :
1197                               ObjCMethodDecl::Required);
1198      // Invent the arguments for the setter. We don't bother making a
1199      // nice name for the argument.
1200      ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1201                                                  SourceLocation(),
1202                                                  property->getIdentifier(),
1203                                                  property->getType(),
1204                                                  VarDecl::None,
1205                                                  0);
1206      SetterMethod->setMethodParams(&Argument, 1, Context);
1207      CD->addDecl(SetterMethod);
1208    } else
1209      // A user declared setter will be synthesize when @synthesize of
1210      // the property with the same name is seen in the @implementation
1211      SetterMethod->setIsSynthesized();
1212    property->setSetterMethodDecl(SetterMethod);
1213  }
1214  // Add any synthesized methods to the global pool. This allows us to
1215  // handle the following, which is supported by GCC (and part of the design).
1216  //
1217  // @interface Foo
1218  // @property double bar;
1219  // @end
1220  //
1221  // void thisIsUnfortunate() {
1222  //   id foo;
1223  //   double bar = [foo bar];
1224  // }
1225  //
1226  if (GetterMethod)
1227    AddInstanceMethodToGlobalPool(GetterMethod);
1228  if (SetterMethod)
1229    AddInstanceMethodToGlobalPool(SetterMethod);
1230}
1231
1232// Note: For class/category implemenations, allMethods/allProperties is
1233// always null.
1234void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclPtrTy classDecl,
1235                      DeclPtrTy *allMethods, unsigned allNum,
1236                      DeclPtrTy *allProperties, unsigned pNum,
1237                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1238  Decl *ClassDecl = classDecl.getAs<Decl>();
1239
1240  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1241  // always passing in a decl. If the decl has an error, isInvalidDecl()
1242  // should be true.
1243  if (!ClassDecl)
1244    return;
1245
1246  bool isInterfaceDeclKind =
1247        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1248         || isa<ObjCProtocolDecl>(ClassDecl);
1249  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1250
1251  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1252
1253  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1254  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1255  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1256
1257  for (unsigned i = 0; i < allNum; i++ ) {
1258    ObjCMethodDecl *Method =
1259      cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1260
1261    if (!Method) continue;  // Already issued a diagnostic.
1262    if (Method->isInstanceMethod()) {
1263      /// Check for instance method of the same name with incompatible types
1264      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1265      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1266                              : false;
1267      if ((isInterfaceDeclKind && PrevMethod && !match)
1268          || (checkIdenticalMethods && match)) {
1269          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1270            << Method->getDeclName();
1271          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1272      } else {
1273        DC->addDecl(Method);
1274        InsMap[Method->getSelector()] = Method;
1275        /// The following allows us to typecheck messages to "id".
1276        AddInstanceMethodToGlobalPool(Method);
1277      }
1278    }
1279    else {
1280      /// Check for class method of the same name with incompatible types
1281      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1282      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1283                              : false;
1284      if ((isInterfaceDeclKind && PrevMethod && !match)
1285          || (checkIdenticalMethods && match)) {
1286        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1287          << Method->getDeclName();
1288        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1289      } else {
1290        DC->addDecl(Method);
1291        ClsMap[Method->getSelector()] = Method;
1292        /// The following allows us to typecheck messages to "Class".
1293        AddFactoryMethodToGlobalPool(Method);
1294      }
1295    }
1296  }
1297  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1298    // Compares properties declared in this class to those of its
1299    // super class.
1300    ComparePropertiesInBaseAndSuper(I);
1301    MergeProtocolPropertiesIntoClass(I, DeclPtrTy::make(I));
1302  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1303    // Categories are used to extend the class by declaring new methods.
1304    // By the same token, they are also used to add new properties. No
1305    // need to compare the added property to those in the class.
1306
1307    // Merge protocol properties into category
1308    MergeProtocolPropertiesIntoClass(C, DeclPtrTy::make(C));
1309    if (C->getIdentifier() == 0)
1310      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1311  }
1312  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1313    // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1314    // user-defined setter/getter. It also synthesizes setter/getter methods
1315    // and adds them to the DeclContext and global method pools.
1316    for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1317                                          E = CDecl->prop_end(); I != E; ++I)
1318      ProcessPropertyDecl(*I, CDecl);
1319    CDecl->setAtEndLoc(AtEndLoc);
1320  }
1321  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1322    IC->setLocEnd(AtEndLoc);
1323    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1324      ImplMethodsVsClassMethods(IC, IDecl);
1325  } else if (ObjCCategoryImplDecl* CatImplClass =
1326                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1327    CatImplClass->setLocEnd(AtEndLoc);
1328
1329    // Find category interface decl and then check that all methods declared
1330    // in this interface are implemented in the category @implementation.
1331    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1332      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1333           Categories; Categories = Categories->getNextClassCategory()) {
1334        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1335          ImplMethodsVsClassMethods(CatImplClass, Categories);
1336          break;
1337        }
1338      }
1339    }
1340  }
1341  if (isInterfaceDeclKind) {
1342    // Reject invalid vardecls.
1343    for (unsigned i = 0; i != tuvNum; i++) {
1344      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1345      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1346        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1347          if (VDecl->getStorageClass() != VarDecl::Extern &&
1348              VDecl->getStorageClass() != VarDecl::PrivateExtern)
1349            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass)
1350              << cast<NamedDecl>(ClassDecl)->getIdentifier();
1351        }
1352    }
1353  }
1354}
1355
1356
1357/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1358/// objective-c's type qualifier from the parser version of the same info.
1359static Decl::ObjCDeclQualifier
1360CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1361  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1362  if (PQTVal & ObjCDeclSpec::DQ_In)
1363    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1364  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1365    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1366  if (PQTVal & ObjCDeclSpec::DQ_Out)
1367    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1368  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1369    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1370  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1371    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1372  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1373    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1374
1375  return ret;
1376}
1377
1378Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1379    SourceLocation MethodLoc, SourceLocation EndLoc,
1380    tok::TokenKind MethodType, DeclPtrTy classDecl,
1381    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1382    Selector Sel,
1383    // optional arguments. The number of types/arguments is obtained
1384    // from the Sel.getNumArgs().
1385    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1386    llvm::SmallVectorImpl<Declarator> &Cdecls,
1387    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1388    bool isVariadic) {
1389  Decl *ClassDecl = classDecl.getAs<Decl>();
1390
1391  // Make sure we can establish a context for the method.
1392  if (!ClassDecl) {
1393    Diag(MethodLoc, diag::error_missing_method_context);
1394    return DeclPtrTy();
1395  }
1396  QualType resultDeclType;
1397
1398  if (ReturnType) {
1399    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1400
1401    // Methods cannot return interface types. All ObjC objects are
1402    // passed by reference.
1403    if (resultDeclType->isObjCInterfaceType()) {
1404      Diag(MethodLoc, diag::err_object_cannot_be_by_value)
1405           << "returned";
1406      return DeclPtrTy();
1407    }
1408  } else // get the type for "id".
1409    resultDeclType = Context.getObjCIdType();
1410
1411  ObjCMethodDecl* ObjCMethod =
1412    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1413                           cast<DeclContext>(ClassDecl),
1414                           MethodType == tok::minus, isVariadic,
1415                           false,
1416                           MethodDeclKind == tok::objc_optional ?
1417                           ObjCMethodDecl::Optional :
1418                           ObjCMethodDecl::Required);
1419
1420  llvm::SmallVector<ParmVarDecl*, 16> Params;
1421
1422  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
1423    // FIXME: arg->AttrList must be stored too!
1424    QualType argType, originalArgType;
1425
1426    if (ArgTypes[i]) {
1427      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
1428      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1429      if (argType->isArrayType())  { // (char *[]) -> (char **)
1430        originalArgType = argType;
1431        argType = Context.getArrayDecayedType(argType);
1432      }
1433      else if (argType->isFunctionType())
1434        argType = Context.getPointerType(argType);
1435      else if (argType->isObjCInterfaceType()) {
1436        // FIXME! provide more precise location for the parameter
1437        Diag(MethodLoc, diag::err_object_cannot_be_by_value)
1438             << "passed";
1439        ObjCMethod->setInvalidDecl();
1440        return DeclPtrTy();
1441      }
1442    } else
1443      argType = Context.getObjCIdType();
1444    ParmVarDecl* Param;
1445    if (originalArgType.isNull())
1446      Param = ParmVarDecl::Create(Context, ObjCMethod,
1447                                  SourceLocation(/*FIXME*/),
1448                                  ArgNames[i], argType,
1449                                  VarDecl::None, 0);
1450    else
1451      Param = OriginalParmVarDecl::Create(Context, ObjCMethod,
1452                                          SourceLocation(/*FIXME*/),
1453                                          ArgNames[i], argType, originalArgType,
1454                                          VarDecl::None, 0);
1455
1456    Param->setObjCDeclQualifier(
1457      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
1458    Params.push_back(Param);
1459  }
1460
1461  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs(), Context);
1462  ObjCMethod->setObjCDeclQualifier(
1463    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1464  const ObjCMethodDecl *PrevMethod = 0;
1465
1466  if (AttrList)
1467    ProcessDeclAttributeList(ObjCMethod, AttrList);
1468
1469  // For implementations (which can be very "coarse grain"), we add the
1470  // method now. This allows the AST to implement lookup methods that work
1471  // incrementally (without waiting until we parse the @end). It also allows
1472  // us to flag multiple declaration errors as they occur.
1473  if (ObjCImplementationDecl *ImpDecl =
1474        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1475    if (MethodType == tok::minus) {
1476      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1477      ImpDecl->addInstanceMethod(ObjCMethod);
1478    } else {
1479      PrevMethod = ImpDecl->getClassMethod(Sel);
1480      ImpDecl->addClassMethod(ObjCMethod);
1481    }
1482  }
1483  else if (ObjCCategoryImplDecl *CatImpDecl =
1484            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1485    if (MethodType == tok::minus) {
1486      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1487      CatImpDecl->addInstanceMethod(ObjCMethod);
1488    } else {
1489      PrevMethod = CatImpDecl->getClassMethod(Sel);
1490      CatImpDecl->addClassMethod(ObjCMethod);
1491    }
1492  }
1493  if (PrevMethod) {
1494    // You can never have two method definitions with the same name.
1495    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1496      << ObjCMethod->getDeclName();
1497    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1498  }
1499  return DeclPtrTy::make(ObjCMethod);
1500}
1501
1502void Sema::CheckObjCPropertyAttributes(QualType PropertyTy,
1503                                       SourceLocation Loc,
1504                                       unsigned &Attributes) {
1505  // FIXME: Improve the reported location.
1506
1507  // readonly and readwrite/assign/retain/copy conflict.
1508  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1509      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1510                     ObjCDeclSpec::DQ_PR_assign |
1511                     ObjCDeclSpec::DQ_PR_copy |
1512                     ObjCDeclSpec::DQ_PR_retain))) {
1513    const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1514                          "readwrite" :
1515                         (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1516                          "assign" :
1517                         (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1518                          "copy" : "retain";
1519
1520    Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1521                 diag::err_objc_property_attr_mutually_exclusive :
1522                 diag::warn_objc_property_attr_mutually_exclusive)
1523      << "readonly" << which;
1524  }
1525
1526  // Check for copy or retain on non-object types.
1527  if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) &&
1528      !Context.isObjCObjectPointerType(PropertyTy)) {
1529    Diag(Loc, diag::err_objc_property_requires_object)
1530      << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain");
1531    Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain);
1532  }
1533
1534  // Check for more than one of { assign, copy, retain }.
1535  if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1536    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1537      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1538        << "assign" << "copy";
1539      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1540    }
1541    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1542      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1543        << "assign" << "retain";
1544      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1545    }
1546  } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1547    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1548      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1549        << "copy" << "retain";
1550      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1551    }
1552  }
1553
1554  // Warn if user supplied no assignment attribute, property is
1555  // readwrite, and this is an object type.
1556  if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
1557                      ObjCDeclSpec::DQ_PR_retain)) &&
1558      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1559      Context.isObjCObjectPointerType(PropertyTy)) {
1560    // Skip this warning in gc-only mode.
1561    if (getLangOptions().getGCMode() != LangOptions::GCOnly)
1562      Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
1563
1564    // If non-gc code warn that this is likely inappropriate.
1565    if (getLangOptions().getGCMode() == LangOptions::NonGC)
1566      Diag(Loc, diag::warn_objc_property_default_assign_on_object);
1567
1568    // FIXME: Implement warning dependent on NSCopying being
1569    // implemented. See also:
1570    // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
1571    // (please trim this list while you are at it).
1572  }
1573}
1574
1575Sema::DeclPtrTy Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1576                                    FieldDeclarator &FD,
1577                                    ObjCDeclSpec &ODS,
1578                                    Selector GetterSel,
1579                                    Selector SetterSel,
1580                                    DeclPtrTy ClassCategory,
1581                                    bool *isOverridingProperty,
1582                                    tok::ObjCKeywordKind MethodImplKind) {
1583  unsigned Attributes = ODS.getPropertyAttributes();
1584  bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
1585                      // default is readwrite!
1586                      !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
1587  // property is defaulted to 'assign' if it is readwrite and is
1588  // not retain or copy
1589  bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
1590                   (isReadWrite &&
1591                    !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1592                    !(Attributes & ObjCDeclSpec::DQ_PR_copy)));
1593  QualType T = GetTypeForDeclarator(FD.D, S);
1594  Decl *ClassDecl = ClassCategory.getAs<Decl>();
1595
1596  // May modify Attributes.
1597  CheckObjCPropertyAttributes(T, AtLoc, Attributes);
1598
1599  ObjCMethodDecl *SetterDecl = 0;
1600  if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1601    if (!CDecl->getIdentifier()) {
1602      // This is a continuation class. property requires special
1603      // handling.
1604      if (ObjCInterfaceDecl *ICDecl = CDecl->getClassInterface()) {
1605        if (ObjCPropertyDecl *PIDecl =
1606            ICDecl->FindPropertyDeclaration(FD.D.getIdentifier())) {
1607          // property 'PIDecl's readonly attribute will be over-ridden
1608          // with continuation class's readwrite property attribute!
1609          unsigned PIkind = PIDecl->getPropertyAttributes();
1610          if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
1611            if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) !=
1612                (PIkind & ObjCPropertyDecl::OBJC_PR_nonatomic))
1613              Diag(AtLoc, diag::warn_property_attr_mismatch);
1614            // Make the continuation class property attribute Read/Write
1615            Attributes &= ~ObjCPropertyDecl::OBJC_PR_readonly;
1616            Attributes |= ObjCPropertyDecl::OBJC_PR_readwrite;
1617            // FIXME: use a common routine with addPropertyMethods.
1618            SetterDecl =
1619              ObjCMethodDecl::Create(Context, AtLoc, AtLoc, SetterSel,
1620                                     Context.VoidTy,
1621                                     ICDecl,
1622                                     true, false, true,
1623                                     ObjCMethodDecl::Required);
1624            ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterDecl,
1625                                                        SourceLocation(),
1626                                                        FD.D.getIdentifier(),
1627                                                        T, VarDecl::None, 0);
1628            SetterDecl->setMethodParams(&Argument, 1, Context);
1629          }
1630          else {
1631            Diag(AtLoc,
1632                 diag::err_use_continuation_class) << ICDecl->getDeclName();
1633            *isOverridingProperty = true;
1634            return DeclPtrTy();
1635          }
1636        }
1637        // No matching property found in the main class. Just fall thru
1638        // and add property to the anonymous category. It looks like
1639        // it works as is. This category becomes just like a category
1640        // for its primary class.
1641      } else {
1642        Diag(CDecl->getLocation(), diag::err_continuation_class);
1643        *isOverridingProperty = true;
1644        return DeclPtrTy();
1645      }
1646    }
1647
1648  Type *t = T.getTypePtr();
1649  if (t->isArrayType() || t->isFunctionType())
1650    Diag(AtLoc, diag::err_property_type) << T;
1651
1652  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1653  assert(DC && "ClassDecl is not a DeclContext");
1654  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, AtLoc,
1655                                                     FD.D.getIdentifier(), T);
1656  DC->addDecl(PDecl);
1657
1658  ProcessDeclAttributes(PDecl, FD.D);
1659
1660  // Regardless of setter/getter attribute, we save the default getter/setter
1661  // selector names in anticipation of declaration of setter/getter methods.
1662  PDecl->setSetterMethodDecl(SetterDecl);
1663  PDecl->setGetterName(GetterSel);
1664  PDecl->setSetterName(SetterSel);
1665
1666  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
1667    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1668
1669  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
1670    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1671
1672  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
1673    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1674
1675  if (isReadWrite)
1676    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1677
1678  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1679    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1680
1681  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1682    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1683
1684  if (isAssign)
1685    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1686
1687  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
1688    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1689
1690  if (MethodImplKind == tok::objc_required)
1691    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1692  else if (MethodImplKind == tok::objc_optional)
1693    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1694
1695  return DeclPtrTy::make(PDecl);
1696}
1697
1698/// ActOnPropertyImplDecl - This routine performs semantic checks and
1699/// builds the AST node for a property implementation declaration; declared
1700/// as @synthesize or @dynamic.
1701///
1702Sema::DeclPtrTy Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1703                                            SourceLocation PropertyLoc,
1704                                            bool Synthesize,
1705                                            DeclPtrTy ClassCatImpDecl,
1706                                            IdentifierInfo *PropertyId,
1707                                            IdentifierInfo *PropertyIvar) {
1708  Decl *ClassImpDecl = ClassCatImpDecl.getAs<Decl>();
1709  // Make sure we have a context for the property implementation declaration.
1710  if (!ClassImpDecl) {
1711    Diag(AtLoc, diag::error_missing_property_context);
1712    return DeclPtrTy();
1713  }
1714  ObjCPropertyDecl *property = 0;
1715  ObjCInterfaceDecl* IDecl = 0;
1716  // Find the class or category class where this property must have
1717  // a declaration.
1718  ObjCImplementationDecl *IC = 0;
1719  ObjCCategoryImplDecl* CatImplClass = 0;
1720  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1721    IDecl = IC->getClassInterface();
1722    // We always synthesize an interface for an implementation
1723    // without an interface decl. So, IDecl is always non-zero.
1724    assert(IDecl &&
1725           "ActOnPropertyImplDecl - @implementation without @interface");
1726
1727    // Look for this property declaration in the @implementation's @interface
1728    property = IDecl->FindPropertyDeclaration(PropertyId);
1729    if (!property) {
1730      Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
1731      return DeclPtrTy();
1732    }
1733  }
1734  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1735    if (Synthesize) {
1736      Diag(AtLoc, diag::error_synthesize_category_decl);
1737      return DeclPtrTy();
1738    }
1739    IDecl = CatImplClass->getClassInterface();
1740    if (!IDecl) {
1741      Diag(AtLoc, diag::error_missing_property_interface);
1742      return DeclPtrTy();
1743    }
1744    ObjCCategoryDecl *Category =
1745      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1746
1747    // If category for this implementation not found, it is an error which
1748    // has already been reported eralier.
1749    if (!Category)
1750      return DeclPtrTy();
1751    // Look for this property declaration in @implementation's category
1752    property = Category->FindPropertyDeclaration(PropertyId);
1753    if (!property) {
1754      Diag(PropertyLoc, diag::error_bad_category_property_decl)
1755        << Category->getDeclName();
1756      return DeclPtrTy();
1757    }
1758  } else {
1759    Diag(AtLoc, diag::error_bad_property_context);
1760    return DeclPtrTy();
1761  }
1762  ObjCIvarDecl *Ivar = 0;
1763  // Check that we have a valid, previously declared ivar for @synthesize
1764  if (Synthesize) {
1765    // @synthesize
1766    if (!PropertyIvar)
1767      PropertyIvar = PropertyId;
1768    QualType PropType = Context.getCanonicalType(property->getType());
1769    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1770    Ivar = IDecl->lookupInstanceVariable(PropertyIvar);
1771    if (!Ivar) {
1772      if (getLangOptions().ObjCNonFragileABI) {
1773        Ivar = ObjCIvarDecl::Create(Context, CurContext, PropertyLoc,
1774                                    PropertyIvar, PropType,
1775                                    ObjCIvarDecl::Private,
1776                                    (Expr *)0);
1777        property->setPropertyIvarDecl(Ivar);
1778      }
1779      else {
1780        Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
1781        return DeclPtrTy();
1782      }
1783    }
1784    QualType IvarType = Context.getCanonicalType(Ivar->getType());
1785
1786    // Check that type of property and its ivar are type compatible.
1787    if (PropType != IvarType) {
1788      if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) {
1789        Diag(PropertyLoc, diag::error_property_ivar_type)
1790          << property->getDeclName() << Ivar->getDeclName();
1791        return DeclPtrTy();
1792      }
1793
1794      // FIXME! Rules for properties are somewhat different that those
1795      // for assignments. Use a new routine to consolidate all cases;
1796      // specifically for property redeclarations as well as for ivars.
1797      QualType lhsType =Context.getCanonicalType(PropType).getUnqualifiedType();
1798      QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
1799      if (lhsType != rhsType &&
1800          lhsType->isArithmeticType()) {
1801        Diag(PropertyLoc, diag::error_property_ivar_type)
1802        << property->getDeclName() << Ivar->getDeclName();
1803        return DeclPtrTy();
1804      }
1805      // __weak is explicit. So it works on Canonical type.
1806      if (PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak()) {
1807        Diag(PropertyLoc, diag::error_weak_property)
1808        << property->getDeclName() << Ivar->getDeclName();
1809        return DeclPtrTy();
1810      }
1811      if ((Context.isObjCObjectPointerType(property->getType()) ||
1812           PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak()) {
1813        Diag(PropertyLoc, diag::error_strong_property)
1814        << property->getDeclName() << Ivar->getDeclName();
1815        return DeclPtrTy();
1816      }
1817    }
1818  } else if (PropertyIvar) {
1819    // @dynamic
1820    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1821    return DeclPtrTy();
1822  }
1823  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1824  ObjCPropertyImplDecl *PIDecl =
1825    ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
1826                                 property,
1827                                 (Synthesize ?
1828                                  ObjCPropertyImplDecl::Synthesize
1829                                  : ObjCPropertyImplDecl::Dynamic),
1830                                 Ivar);
1831  CurContext->addDecl(PIDecl);
1832  if (IC) {
1833    if (Synthesize)
1834      if (ObjCPropertyImplDecl *PPIDecl =
1835          IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1836        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1837          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1838          << PropertyIvar;
1839        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1840      }
1841
1842    if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplDecl(PropertyId)) {
1843      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1844      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1845      return DeclPtrTy();
1846    }
1847    IC->addPropertyImplementation(PIDecl);
1848  }
1849  else {
1850    if (Synthesize)
1851      if (ObjCPropertyImplDecl *PPIDecl =
1852          CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1853        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1854          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1855          << PropertyIvar;
1856        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1857      }
1858
1859    if (ObjCPropertyImplDecl *PPIDecl =
1860          CatImplClass->FindPropertyImplDecl(PropertyId)) {
1861      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1862      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1863      return DeclPtrTy();
1864    }
1865    CatImplClass->addPropertyImplementation(PIDecl);
1866  }
1867
1868  return DeclPtrTy::make(PIDecl);
1869}
1870
1871bool Sema::CheckObjCDeclScope(Decl *D) {
1872  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1873    return false;
1874
1875  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1876  D->setInvalidDecl();
1877
1878  return true;
1879}
1880
1881/// Collect the instance variables declared in an Objective-C object.  Used in
1882/// the creation of structures from objects using the @defs directive.
1883/// FIXME: This should be consolidated with CollectObjCIvars as it is also
1884/// part of the AST generation logic of @defs.
1885static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
1886                         ASTContext& Ctx,
1887                         llvm::SmallVectorImpl<Sema::DeclPtrTy> &ivars) {
1888  if (Class->getSuperClass())
1889    CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
1890
1891  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1892  for (ObjCInterfaceDecl::ivar_iterator I = Class->ivar_begin(),
1893       E = Class->ivar_end(); I != E; ++I) {
1894    ObjCIvarDecl* ID = *I;
1895    Decl *FD = ObjCAtDefsFieldDecl::Create(Ctx, Record, ID->getLocation(),
1896                                           ID->getIdentifier(), ID->getType(),
1897                                           ID->getBitWidth());
1898    ivars.push_back(Sema::DeclPtrTy::make(FD));
1899  }
1900}
1901
1902/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1903/// instance variables of ClassName into Decls.
1904void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
1905                     IdentifierInfo *ClassName,
1906                     llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
1907  // Check that ClassName is a valid class
1908  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1909  if (!Class) {
1910    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1911    return;
1912  }
1913  // Collect the instance variables
1914  CollectIvars(Class, dyn_cast<RecordDecl>(TagD.getAs<Decl>()), Context, Decls);
1915
1916  // Introduce all of these fields into the appropriate scope.
1917  for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
1918       D != Decls.end(); ++D) {
1919    FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
1920    if (getLangOptions().CPlusPlus)
1921      PushOnScopeChains(cast<FieldDecl>(FD), S);
1922    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
1923      Record->addDecl(FD);
1924  }
1925}
1926
1927