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