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