SemaDeclObjC.cpp revision 1b63eef830b7a2501f1ab8e8fa38068e5e07ed32
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/Scope.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->isInstance())
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(MDecl);
39
40  // Create Decl objects for each parameter, entrring them in the scope for
41  // binding to their use.
42  struct DeclaratorChunk::ParamInfo PI;
43
44  // Insert the invisible arguments, self and _cmd!
45  PI.Ident = &Context.Idents.get("self");
46  PI.IdentLoc = SourceLocation(); // synthesized vars have a null location.
47  QualType selfTy;
48  if (MDecl->isInstance()) {
49    selfTy = Context.getObjCIdType();
50    if (ObjCInterfaceDecl *OID = MDecl->getClassInterface()) {
51      // There may be no interface context due to error in declaration of the
52      // interface (which has been reported). Recover gracefully
53      selfTy = Context.getObjCInterfaceType(OID);
54      selfTy = Context.getPointerType(selfTy);
55    }
56  } else // we have a factory method.
57    selfTy = Context.getObjCClassType();
58  getCurMethodDecl()->setSelfDecl(CreateImplicitParameter(FnBodyScope,
59        PI.Ident, PI.IdentLoc, selfTy));
60
61  PI.Ident = &Context.Idents.get("_cmd");
62  getCurMethodDecl()->setCmdDecl(CreateImplicitParameter(FnBodyScope,
63        PI.Ident, PI.IdentLoc, Context.getObjCSelType()));
64
65  // Introduce all of the other parameters into this scope.
66  for (unsigned i = 0, e = MDecl->getNumParams(); i != e; ++i) {
67    ParmVarDecl *PDecl = MDecl->getParamDecl(i);
68    IdentifierInfo *II = PDecl->getIdentifier();
69    if (II)
70      PushOnScopeChains(PDecl, FnBodyScope);
71  }
72}
73
74Sema::DeclTy *Sema::
75ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
76                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
77                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
78                         DeclTy * const *ProtoRefs, unsigned NumProtoRefs,
79                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
80  assert(ClassName && "Missing class identifier");
81
82  // Check for another declaration kind with the same name.
83  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
84  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
85    Diag(ClassLoc, diag::err_redefinition_different_kind,
86         ClassName->getName());
87    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
88  }
89
90  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
91  if (IDecl) {
92    // Class already seen. Is it a forward declaration?
93    if (!IDecl->isForwardDecl())
94      Diag(AtInterfaceLoc, diag::err_duplicate_class_def, IDecl->getName());
95    else {
96      IDecl->setLocation(AtInterfaceLoc);
97      IDecl->setForwardDecl(false);
98    }
99  } else {
100    IDecl = ObjCInterfaceDecl::Create(Context, AtInterfaceLoc,
101                                      ClassName, ClassLoc);
102
103    ObjCInterfaceDecls[ClassName] = IDecl;
104    // Remember that this needs to be removed when the scope is popped.
105    TUScope->AddDecl(IDecl);
106  }
107
108  if (SuperName) {
109    ObjCInterfaceDecl* SuperClassEntry = 0;
110    // Check if a different kind of symbol declared in this scope.
111    PrevDecl = LookupDecl(SuperName, Decl::IDNS_Ordinary, TUScope);
112    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
113      Diag(SuperLoc, diag::err_redefinition_different_kind,
114           SuperName->getName());
115      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
116    }
117    else {
118      // Check that super class is previously defined
119      SuperClassEntry = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
120
121      if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
122        Diag(SuperLoc, diag::err_undef_superclass,
123             SuperClassEntry ? SuperClassEntry->getName()
124                             : SuperName->getName(),
125             ClassName->getName(), SourceRange(AtInterfaceLoc, ClassLoc));
126      }
127    }
128    IDecl->setSuperClass(SuperClassEntry);
129    IDecl->setSuperClassLoc(SuperLoc);
130    IDecl->setLocEnd(SuperLoc);
131  } else { // we have a root class.
132    IDecl->setLocEnd(ClassLoc);
133  }
134
135  /// Check then save referenced protocols
136  if (NumProtoRefs) {
137    IDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
138    IDecl->setLocEnd(EndProtoLoc);
139  }
140  return IDecl;
141}
142
143/// ActOnCompatiblityAlias - this action is called after complete parsing of
144/// @compaatibility_alias declaration. It sets up the alias relationships.
145Sema::DeclTy *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
146                                           IdentifierInfo *AliasName,
147                                           SourceLocation AliasLocation,
148                                           IdentifierInfo *ClassName,
149                                           SourceLocation ClassLocation) {
150  // Look for previous declaration of alias name
151  Decl *ADecl = LookupDecl(AliasName, Decl::IDNS_Ordinary, TUScope);
152  if (ADecl) {
153    if (isa<ObjCCompatibleAliasDecl>(ADecl)) {
154      Diag(AliasLocation, diag::warn_previous_alias_decl);
155      Diag(ADecl->getLocation(), diag::warn_previous_declaration);
156    }
157    else {
158      Diag(AliasLocation, diag::err_conflicting_aliasing_type,
159           AliasName->getName());
160      Diag(ADecl->getLocation(), diag::err_previous_declaration);
161    }
162    return 0;
163  }
164  // Check for class declaration
165  Decl *CDeclU = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
166  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
167  if (CDecl == 0) {
168    Diag(ClassLocation, diag::warn_undef_interface, ClassName->getName());
169    if (CDeclU)
170      Diag(CDeclU->getLocation(), diag::warn_previous_declaration);
171    return 0;
172  }
173
174  // Everything checked out, instantiate a new alias declaration AST.
175  ObjCCompatibleAliasDecl *AliasDecl =
176    ObjCCompatibleAliasDecl::Create(Context, AtLoc, AliasName, CDecl);
177
178  ObjCAliasDecls[AliasName] = AliasDecl;
179  TUScope->AddDecl(AliasDecl);
180  return AliasDecl;
181}
182
183Sema::DeclTy *
184Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
185                                  IdentifierInfo *ProtocolName,
186                                  SourceLocation ProtocolLoc,
187                                  DeclTy * const *ProtoRefs,
188                                  unsigned NumProtoRefs,
189                                  SourceLocation EndProtoLoc) {
190  assert(ProtocolName && "Missing protocol identifier");
191  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
192  if (PDecl) {
193    // Protocol already seen. Better be a forward protocol declaration
194    if (!PDecl->isForwardDecl()) {
195      Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
196           ProtocolName->getName());
197      // Just return the protocol we already had.
198      // FIXME: don't leak the objects passed in!
199      return PDecl;
200    }
201
202    PDecl->setForwardDecl(false);
203  } else {
204    PDecl = ObjCProtocolDecl::Create(Context, AtProtoInterfaceLoc,ProtocolName);
205    PDecl->setForwardDecl(false);
206    ObjCProtocols[ProtocolName] = PDecl;
207  }
208
209  if (NumProtoRefs) {
210    /// Check then save referenced protocols.
211    PDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
212    PDecl->setLocEnd(EndProtoLoc);
213  }
214  return PDecl;
215}
216
217/// FindProtocolDeclaration - This routine looks up protocols and
218/// issuer error if they are not declared. It returns list of protocol
219/// declarations in its 'Protocols' argument.
220void
221Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
222                              const IdentifierLocPair *ProtocolId,
223                              unsigned NumProtocols,
224                              llvm::SmallVectorImpl<DeclTy*> &Protocols) {
225  for (unsigned i = 0; i != NumProtocols; ++i) {
226    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
227    if (!PDecl) {
228      Diag(ProtocolId[i].second, diag::err_undeclared_protocol,
229           ProtocolId[i].first->getName());
230      continue;
231    }
232
233    // If this is a forward declaration and we are supposed to warn in this
234    // case, do it.
235    if (WarnOnDeclarations && PDecl->isForwardDecl())
236      Diag(ProtocolId[i].second, diag::warn_undef_protocolref,
237           ProtocolId[i].first->getName());
238    Protocols.push_back(PDecl);
239  }
240}
241
242/// DiagnosePropertyMismatch - Compares two properties for their
243/// attributes and types and warns on a variety of inconsistancies.
244///
245void
246Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
247                               ObjCPropertyDecl *SuperProperty,
248                               const char *inheritedName) {
249  ObjCPropertyDecl::PropertyAttributeKind CAttr =
250  Property->getPropertyAttributes();
251  ObjCPropertyDecl::PropertyAttributeKind SAttr =
252  SuperProperty->getPropertyAttributes();
253  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
254      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
255    Diag(Property->getLocation(), diag::warn_readonly_property,
256               Property->getName(), inheritedName);
257  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
258      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
259    Diag(Property->getLocation(), diag::warn_property_attribute,
260         Property->getName(), "copy", inheritedName,
261         SourceRange());
262  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
263           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
264    Diag(Property->getLocation(), diag::warn_property_attribute,
265         Property->getName(), "retain", inheritedName,
266         SourceRange());
267
268  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
269      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
270    Diag(Property->getLocation(), diag::warn_property_attribute,
271         Property->getName(), "atomic", inheritedName,
272         SourceRange());
273  if (Property->getSetterName() != SuperProperty->getSetterName())
274    Diag(Property->getLocation(), diag::warn_property_attribute,
275         Property->getName(), "setter", inheritedName,
276         SourceRange());
277  if (Property->getGetterName() != SuperProperty->getGetterName())
278    Diag(Property->getLocation(), diag::warn_property_attribute,
279         Property->getName(), "getter", inheritedName,
280         SourceRange());
281
282  if (Context.getCanonicalType(Property->getType()) !=
283          Context.getCanonicalType(SuperProperty->getType()))
284    Diag(Property->getLocation(), diag::warn_property_type,
285         Property->getType().getAsString(),
286         inheritedName);
287
288}
289
290/// ComparePropertiesInBaseAndSuper - This routine compares property
291/// declarations in base and its super class, if any, and issues
292/// diagnostics in a variety of inconsistant situations.
293///
294void
295Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
296  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
297  if (!SDecl)
298    return;
299  for (ObjCInterfaceDecl::classprop_iterator S = SDecl->classprop_begin(),
300       E = SDecl->classprop_end(); S != E; ++S) {
301    ObjCPropertyDecl *SuperPDecl = (*S);
302    // Does property in super class has declaration in current class?
303    for (ObjCInterfaceDecl::classprop_iterator I = IDecl->classprop_begin(),
304         E = IDecl->classprop_end(); I != E; ++I) {
305      ObjCPropertyDecl *PDecl = (*I);
306      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
307          DiagnosePropertyMismatch(PDecl, SuperPDecl, SDecl->getName());
308    }
309  }
310}
311
312/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
313/// of properties declared in a protocol and adds them to the list
314/// of properties for current class if it is not there already.
315void
316Sema::MergeOneProtocolPropertiesIntoClass(ObjCInterfaceDecl *IDecl,
317                                          ObjCProtocolDecl *PDecl)
318{
319  llvm::SmallVector<ObjCPropertyDecl*, 16> mergeProperties;
320  for (ObjCProtocolDecl::classprop_iterator P = PDecl->classprop_begin(),
321       E = PDecl->classprop_end(); P != E; ++P) {
322    ObjCPropertyDecl *Pr = (*P);
323    ObjCInterfaceDecl::classprop_iterator CP, CE;
324    // Is this property already in  class's list of properties?
325    for (CP = IDecl->classprop_begin(), CE = IDecl->classprop_end();
326         CP != CE; ++CP)
327      if ((*CP)->getIdentifier() == Pr->getIdentifier())
328        break;
329    if (CP == CE)
330      // Add this property to list of properties for thie class.
331      mergeProperties.push_back(Pr);
332    else
333      // Property protocol already exist in class. Diagnose any mismatch.
334      DiagnosePropertyMismatch((*CP), Pr, PDecl->getName());
335    }
336  IDecl->mergeProperties(&mergeProperties[0], mergeProperties.size());
337}
338
339/// MergeProtocolPropertiesIntoClass - This routine merges properties
340/// declared in 'MergeItsProtocols' objects (which can be a class or an
341/// inherited protocol into the list of properties for class 'IDecl'
342///
343
344void
345Sema::MergeProtocolPropertiesIntoClass(ObjCInterfaceDecl *IDecl,
346                                       DeclTy *MergeItsProtocols) {
347  Decl *ClassDecl = static_cast<Decl *>(MergeItsProtocols);
348  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
349    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
350         E = MDecl->protocol_end(); P != E; ++P)
351      // Merge properties of class (*P) into IDECL's
352      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
353
354    // Go thru the list of protocols for this class and recursively merge
355    // their properties into this class as well.
356    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
357         E = IDecl->protocol_end(); P != E; ++P)
358      MergeProtocolPropertiesIntoClass(IDecl, *P);
359  } else {
360    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
361    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
362         E = MD->protocol_end(); P != E; ++P)
363      MergeOneProtocolPropertiesIntoClass(IDecl, (*P));
364  }
365}
366
367/// ActOnForwardProtocolDeclaration -
368Action::DeclTy *
369Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
370                                      const IdentifierLocPair *IdentList,
371                                      unsigned NumElts) {
372  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
373
374  for (unsigned i = 0; i != NumElts; ++i) {
375    IdentifierInfo *Ident = IdentList[i].first;
376    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
377    if (PDecl == 0) // Not already seen?
378      PDecl = ObjCProtocolDecl::Create(Context, IdentList[i].second, Ident);
379
380    Protocols.push_back(PDecl);
381  }
382  return ObjCForwardProtocolDecl::Create(Context, AtProtocolLoc,
383                                         &Protocols[0], Protocols.size());
384}
385
386Sema::DeclTy *Sema::
387ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
388                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
389                            IdentifierInfo *CategoryName,
390                            SourceLocation CategoryLoc,
391                            DeclTy * const *ProtoRefs,
392                            unsigned NumProtoRefs,
393                            SourceLocation EndProtoLoc) {
394  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
395
396  ObjCCategoryDecl *CDecl =
397    ObjCCategoryDecl::Create(Context, AtInterfaceLoc, CategoryName);
398  CDecl->setClassInterface(IDecl);
399
400  /// Check that class of this category is already completely declared.
401  if (!IDecl || IDecl->isForwardDecl())
402    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
403  else {
404    /// Check for duplicate interface declaration for this category
405    ObjCCategoryDecl *CDeclChain;
406    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
407         CDeclChain = CDeclChain->getNextClassCategory()) {
408      if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
409        Diag(CategoryLoc, diag::warn_dup_category_def, ClassName->getName(),
410             CategoryName->getName());
411        break;
412      }
413    }
414    if (!CDeclChain)
415      CDecl->insertNextClassCategory();
416  }
417
418  if (NumProtoRefs) {
419    CDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
420    CDecl->setLocEnd(EndProtoLoc);
421  }
422  return CDecl;
423}
424
425/// ActOnStartCategoryImplementation - Perform semantic checks on the
426/// category implementation declaration and build an ObjCCategoryImplDecl
427/// object.
428Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
429                      SourceLocation AtCatImplLoc,
430                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
431                      IdentifierInfo *CatName, SourceLocation CatLoc) {
432  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
433  ObjCCategoryImplDecl *CDecl =
434    ObjCCategoryImplDecl::Create(Context, AtCatImplLoc, CatName, IDecl);
435  /// Check that class of this category is already completely declared.
436  if (!IDecl || IDecl->isForwardDecl())
437    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
438
439  /// TODO: Check that CatName, category name, is not used in another
440  // implementation.
441  return CDecl;
442}
443
444Sema::DeclTy *Sema::ActOnStartClassImplementation(
445                      SourceLocation AtClassImplLoc,
446                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
447                      IdentifierInfo *SuperClassname,
448                      SourceLocation SuperClassLoc) {
449  ObjCInterfaceDecl* IDecl = 0;
450  // Check for another declaration kind with the same name.
451  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
452  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
453    Diag(ClassLoc, diag::err_redefinition_different_kind,
454         ClassName->getName());
455    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
456  }
457  else {
458    // Is there an interface declaration of this class; if not, warn!
459    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
460    if (!IDecl)
461      Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
462  }
463
464  // Check that super class name is valid class name
465  ObjCInterfaceDecl* SDecl = 0;
466  if (SuperClassname) {
467    // Check if a different kind of symbol declared in this scope.
468    PrevDecl = LookupDecl(SuperClassname, Decl::IDNS_Ordinary, TUScope);
469    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
470      Diag(SuperClassLoc, diag::err_redefinition_different_kind,
471           SuperClassname->getName());
472      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
473    }
474    else {
475      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
476      if (!SDecl)
477        Diag(SuperClassLoc, diag::err_undef_superclass,
478             SuperClassname->getName(), ClassName->getName());
479      else if (IDecl && IDecl->getSuperClass() != SDecl) {
480        // This implementation and its interface do not have the same
481        // super class.
482        Diag(SuperClassLoc, diag::err_conflicting_super_class,
483             SDecl->getName());
484        Diag(SDecl->getLocation(), diag::err_previous_definition);
485      }
486    }
487  }
488
489  if (!IDecl) {
490    // Legacy case of @implementation with no corresponding @interface.
491    // Build, chain & install the interface decl into the identifier.
492    IDecl = ObjCInterfaceDecl::Create(Context, AtClassImplLoc, ClassName,
493                                      ClassLoc, false, true);
494    ObjCInterfaceDecls[ClassName] = IDecl;
495    IDecl->setSuperClass(SDecl);
496    IDecl->setLocEnd(ClassLoc);
497
498    // Remember that this needs to be removed when the scope is popped.
499    TUScope->AddDecl(IDecl);
500  }
501
502  ObjCImplementationDecl* IMPDecl =
503    ObjCImplementationDecl::Create(Context, AtClassImplLoc, ClassName,
504                                   IDecl, SDecl);
505
506  // Check that there is no duplicate implementation of this class.
507  if (ObjCImplementations[ClassName])
508    // FIXME: Don't leak everything!
509    Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
510  else // add it to the list.
511    ObjCImplementations[ClassName] = IMPDecl;
512  return IMPDecl;
513}
514
515void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
516                                    ObjCIvarDecl **ivars, unsigned numIvars,
517                                    SourceLocation RBrace) {
518  assert(ImpDecl && "missing implementation decl");
519  ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
520  if (!IDecl)
521    return;
522  /// Check case of non-existing @interface decl.
523  /// (legacy objective-c @implementation decl without an @interface decl).
524  /// Add implementations's ivar to the synthesize class's ivar list.
525  if (IDecl->ImplicitInterfaceDecl()) {
526    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
527    return;
528  }
529  // If implementation has empty ivar list, just return.
530  if (numIvars == 0)
531    return;
532
533  assert(ivars && "missing @implementation ivars");
534
535  // Check interface's Ivar list against those in the implementation.
536  // names and types must match.
537  //
538  unsigned j = 0;
539  ObjCInterfaceDecl::ivar_iterator
540    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
541  for (; numIvars > 0 && IVI != IVE; ++IVI) {
542    ObjCIvarDecl* ImplIvar = ivars[j++];
543    ObjCIvarDecl* ClsIvar = *IVI;
544    assert (ImplIvar && "missing implementation ivar");
545    assert (ClsIvar && "missing class ivar");
546    if (Context.getCanonicalType(ImplIvar->getType()) !=
547        Context.getCanonicalType(ClsIvar->getType())) {
548      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
549           ImplIvar->getIdentifier()->getName());
550      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
551           ClsIvar->getIdentifier()->getName());
552    }
553    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
554    // as error.
555    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
556      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
557           ImplIvar->getIdentifier()->getName());
558      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
559           ClsIvar->getIdentifier()->getName());
560      return;
561    }
562    --numIvars;
563  }
564
565  if (numIvars > 0)
566    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
567  else if (IVI != IVE)
568    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
569}
570
571void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
572                               bool &IncompleteImpl) {
573  if (!IncompleteImpl) {
574    Diag(ImpLoc, diag::warn_incomplete_impl);
575    IncompleteImpl = true;
576  }
577  Diag(ImpLoc, diag::warn_undef_method_impl, method->getSelector().getName());
578}
579
580/// CheckProtocolMethodDefs - This routine checks unimplemented methods
581/// Declared in protocol, and those referenced by it.
582void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
583                                   ObjCProtocolDecl *PDecl,
584                                   bool& IncompleteImpl,
585                                   const llvm::DenseSet<Selector> &InsMap,
586                                   const llvm::DenseSet<Selector> &ClsMap) {
587  // check unimplemented instance methods.
588  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
589       E = PDecl->instmeth_end(); I != E; ++I) {
590    ObjCMethodDecl *method = *I;
591    if (!InsMap.count(method->getSelector()) &&
592        method->getImplementationControl() != ObjCMethodDecl::Optional)
593      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
594  }
595  // check unimplemented class methods
596  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
597       E = PDecl->classmeth_end(); I != E; ++I) {
598    ObjCMethodDecl *method = *I;
599    if (!ClsMap.count(method->getSelector()) &&
600        method->getImplementationControl() != ObjCMethodDecl::Optional)
601      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
602  }
603  // Check on this protocols's referenced protocols, recursively.
604  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
605       E = PDecl->protocol_end(); PI != E; ++PI)
606    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap);
607}
608
609void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
610                                     ObjCInterfaceDecl* IDecl) {
611  llvm::DenseSet<Selector> InsMap;
612  // Check and see if instance methods in class interface have been
613  // implemented in the implementation class.
614  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
615       E = IMPDecl->instmeth_end(); I != E; ++I)
616    InsMap.insert((*I)->getSelector());
617
618  bool IncompleteImpl = false;
619  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
620       E = IDecl->instmeth_end(); I != E; ++I)
621    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector()))
622      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
623
624  llvm::DenseSet<Selector> ClsMap;
625  // Check and see if class methods in class interface have been
626  // implemented in the implementation class.
627  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
628       E = IMPDecl->classmeth_end(); I != E; ++I)
629    ClsMap.insert((*I)->getSelector());
630
631  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
632       E = IDecl->classmeth_end(); I != E; ++I)
633    if (!ClsMap.count((*I)->getSelector()))
634      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
635
636  // Check the protocol list for unimplemented methods in the @implementation
637  // class.
638  const ObjCList<ObjCProtocolDecl> &Protocols =
639    IDecl->getReferencedProtocols();
640  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
641       E = Protocols.end(); I != E; ++I)
642    CheckProtocolMethodDefs(IMPDecl->getLocation(), *I,
643                            IncompleteImpl, InsMap, ClsMap);
644}
645
646/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
647/// category interface is implemented in the category @implementation.
648void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
649                                            ObjCCategoryDecl *CatClassDecl) {
650  llvm::DenseSet<Selector> InsMap;
651  // Check and see if instance methods in category interface have been
652  // implemented in its implementation class.
653  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
654       E = CatImplDecl->instmeth_end(); I != E; ++I)
655    InsMap.insert((*I)->getSelector());
656
657  bool IncompleteImpl = false;
658  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
659       E = CatClassDecl->instmeth_end(); I != E; ++I)
660    if (!InsMap.count((*I)->getSelector()))
661      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
662
663  llvm::DenseSet<Selector> ClsMap;
664  // Check and see if class methods in category interface have been
665  // implemented in its implementation class.
666  for (ObjCCategoryImplDecl::classmeth_iterator
667       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
668       I != E; ++I)
669    ClsMap.insert((*I)->getSelector());
670
671  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
672       E = CatClassDecl->classmeth_end(); I != E; ++I)
673    if (!ClsMap.count((*I)->getSelector()))
674      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
675
676  // Check the protocol list for unimplemented methods in the @implementation
677  // class.
678  for (ObjCCategoryDecl::protocol_iterator PI = CatClassDecl->protocol_begin(),
679       E = CatClassDecl->protocol_end(); PI != E; ++PI)
680    CheckProtocolMethodDefs(CatImplDecl->getLocation(), *PI, IncompleteImpl,
681                            InsMap, ClsMap);
682}
683
684/// ActOnForwardClassDeclaration -
685Action::DeclTy *
686Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
687                                   IdentifierInfo **IdentList, unsigned NumElts)
688{
689  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
690
691  for (unsigned i = 0; i != NumElts; ++i) {
692    // Check for another declaration kind with the same name.
693    Decl *PrevDecl = LookupDecl(IdentList[i], Decl::IDNS_Ordinary, TUScope);
694    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
695      // GCC apparently allows the following idiom:
696      //
697      // typedef NSObject < XCElementTogglerP > XCElementToggler;
698      // @class XCElementToggler;
699      //
700      // FIXME: Make an extension?
701      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
702      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
703        Diag(AtClassLoc, diag::err_redefinition_different_kind,
704             IdentList[i]->getName());
705        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
706      }
707    }
708    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
709    if (!IDecl) {  // Not already seen?  Make a forward decl.
710      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, IdentList[i],
711                                        SourceLocation(), true);
712      ObjCInterfaceDecls[IdentList[i]] = IDecl;
713
714      // Remember that this needs to be removed when the scope is popped.
715      TUScope->AddDecl(IDecl);
716    }
717
718    Interfaces.push_back(IDecl);
719  }
720
721  return ObjCClassDecl::Create(Context, AtClassLoc,
722                               &Interfaces[0], Interfaces.size());
723}
724
725
726/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
727/// returns true, or false, accordingly.
728/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
729bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
730                                      const ObjCMethodDecl *PrevMethod) {
731  if (Context.getCanonicalType(Method->getResultType()) !=
732      Context.getCanonicalType(PrevMethod->getResultType()))
733    return false;
734  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
735    ParmVarDecl *ParamDecl = Method->getParamDecl(i);
736    ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
737    if (Context.getCanonicalType(ParamDecl->getType()) !=
738        Context.getCanonicalType(PrevParamDecl->getType()))
739      return false;
740  }
741  return true;
742}
743
744void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
745  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
746  if (!FirstMethod.Method) {
747    // Haven't seen a method with this selector name yet - add it.
748    FirstMethod.Method = Method;
749    FirstMethod.Next = 0;
750  } else {
751    // We've seen a method with this name, now check the type signature(s).
752    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
753
754    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
755         Next = Next->Next)
756      match = MatchTwoMethodDeclarations(Method, Next->Method);
757
758    if (!match) {
759      // We have a new signature for an existing method - add it.
760      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
761      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
762      FirstMethod.Next = OMI;
763    }
764  }
765}
766
767void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
768  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
769  if (!FirstMethod.Method) {
770    // Haven't seen a method with this selector name yet - add it.
771    FirstMethod.Method = Method;
772    FirstMethod.Next = 0;
773  } else {
774    // We've seen a method with this name, now check the type signature(s).
775    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
776
777    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
778         Next = Next->Next)
779      match = MatchTwoMethodDeclarations(Method, Next->Method);
780
781    if (!match) {
782      // We have a new signature for an existing method - add it.
783      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
784      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
785      FirstMethod.Next = OMI;
786    }
787  }
788}
789
790// Note: For class/category implemenations, allMethods/allProperties is
791// always null.
792void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
793                      DeclTy **allMethods, unsigned allNum,
794                      DeclTy **allProperties, unsigned pNum) {
795  Decl *ClassDecl = static_cast<Decl *>(classDecl);
796
797  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
798  // always passing in a decl. If the decl has an error, isInvalidDecl()
799  // should be true.
800  if (!ClassDecl)
801    return;
802
803  llvm::SmallVector<ObjCMethodDecl*, 32> insMethods;
804  llvm::SmallVector<ObjCMethodDecl*, 16> clsMethods;
805
806  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
807  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
808
809  bool isInterfaceDeclKind =
810        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
811         || isa<ObjCProtocolDecl>(ClassDecl);
812  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
813
814  if (pNum != 0) {
815    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl))
816      IDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
817    else if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
818      CDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
819    else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(ClassDecl))
820          PDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
821    else
822      assert(false && "ActOnAtEnd - property declaration misplaced");
823  }
824
825  for (unsigned i = 0; i < allNum; i++ ) {
826    ObjCMethodDecl *Method =
827      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
828
829    if (!Method) continue;  // Already issued a diagnostic.
830    if (Method->isInstance()) {
831      /// Check for instance method of the same name with incompatible types
832      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
833      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
834                              : false;
835      if (isInterfaceDeclKind && PrevMethod && !match
836          || checkIdenticalMethods && match) {
837          Diag(Method->getLocation(), diag::error_duplicate_method_decl,
838               Method->getSelector().getName());
839          Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
840      } else {
841        insMethods.push_back(Method);
842        InsMap[Method->getSelector()] = Method;
843        /// The following allows us to typecheck messages to "id".
844        AddInstanceMethodToGlobalPool(Method);
845      }
846    }
847    else {
848      /// Check for class method of the same name with incompatible types
849      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
850      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
851                              : false;
852      if (isInterfaceDeclKind && PrevMethod && !match
853          || checkIdenticalMethods && match) {
854        Diag(Method->getLocation(), diag::error_duplicate_method_decl,
855             Method->getSelector().getName());
856        Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
857      } else {
858        clsMethods.push_back(Method);
859        ClsMap[Method->getSelector()] = Method;
860        /// The following allows us to typecheck messages to "Class".
861        AddFactoryMethodToGlobalPool(Method);
862      }
863    }
864  }
865
866  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
867    // Compares properties declaraed in this class to those of its
868    // super class.
869    ComparePropertiesInBaseAndSuper(I);
870    MergeProtocolPropertiesIntoClass(I, I);
871    for (ObjCInterfaceDecl::classprop_iterator P = I->classprop_begin(),
872         E = I->classprop_end(); P != E; ++P) {
873      // FIXME: It would be really nice if we could avoid this. Injecting
874      // methods into the interface makes it hard to distinguish "real" methods
875      // from synthesized "property" methods (that aren't in the source).
876      // This complicicates the rewriter's life.
877      I->addPropertyMethods(Context, *P, insMethods);
878    }
879    I->addMethods(&insMethods[0], insMethods.size(),
880                  &clsMethods[0], clsMethods.size(), AtEndLoc);
881
882  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
883    P->addMethods(&insMethods[0], insMethods.size(),
884                  &clsMethods[0], clsMethods.size(), AtEndLoc);
885  }
886  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
887    C->addMethods(&insMethods[0], insMethods.size(),
888                  &clsMethods[0], clsMethods.size(), AtEndLoc);
889  }
890  else if (ObjCImplementationDecl *IC =
891                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
892    IC->setLocEnd(AtEndLoc);
893    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
894      ImplMethodsVsClassMethods(IC, IDecl);
895  } else {
896    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
897    CatImplClass->setLocEnd(AtEndLoc);
898    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
899    // Find category interface decl and then check that all methods declared
900    // in this interface is implemented in the category @implementation.
901    if (IDecl) {
902      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
903           Categories; Categories = Categories->getNextClassCategory()) {
904        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
905          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
906          break;
907        }
908      }
909    }
910  }
911}
912
913
914/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
915/// objective-c's type qualifier from the parser version of the same info.
916static Decl::ObjCDeclQualifier
917CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
918  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
919  if (PQTVal & ObjCDeclSpec::DQ_In)
920    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
921  if (PQTVal & ObjCDeclSpec::DQ_Inout)
922    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
923  if (PQTVal & ObjCDeclSpec::DQ_Out)
924    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
925  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
926    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
927  if (PQTVal & ObjCDeclSpec::DQ_Byref)
928    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
929  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
930    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
931
932  return ret;
933}
934
935Sema::DeclTy *Sema::ActOnMethodDeclaration(
936    SourceLocation MethodLoc, SourceLocation EndLoc,
937    tok::TokenKind MethodType, DeclTy *classDecl,
938    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
939    Selector Sel,
940    // optional arguments. The number of types/arguments is obtained
941    // from the Sel.getNumArgs().
942    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
943    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
944    bool isVariadic) {
945  Decl *ClassDecl = static_cast<Decl*>(classDecl);
946
947  // Make sure we can establish a context for the method.
948  if (!ClassDecl) {
949    Diag(MethodLoc, diag::error_missing_method_context);
950    return 0;
951  }
952  QualType resultDeclType;
953
954  if (ReturnType)
955    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
956  else // get the type for "id".
957    resultDeclType = Context.getObjCIdType();
958
959  ObjCMethodDecl* ObjCMethod =
960    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
961                           ClassDecl, AttrList,
962                           MethodType == tok::minus, isVariadic,
963                           false,
964                           MethodDeclKind == tok::objc_optional ?
965                           ObjCMethodDecl::Optional :
966                           ObjCMethodDecl::Required);
967
968  llvm::SmallVector<ParmVarDecl*, 16> Params;
969
970  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
971    // FIXME: arg->AttrList must be stored too!
972    QualType argType;
973
974    if (ArgTypes[i])
975      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
976    else
977      argType = Context.getObjCIdType();
978    ParmVarDecl* Param = ParmVarDecl::Create(Context, ObjCMethod,
979                                             SourceLocation(/*FIXME*/),
980                                             ArgNames[i], argType,
981                                             VarDecl::None, 0, 0);
982    Param->setObjCDeclQualifier(
983      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
984    Params.push_back(Param);
985  }
986
987  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
988  ObjCMethod->setObjCDeclQualifier(
989    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
990  const ObjCMethodDecl *PrevMethod = 0;
991
992  // For implementations (which can be very "coarse grain"), we add the
993  // method now. This allows the AST to implement lookup methods that work
994  // incrementally (without waiting until we parse the @end). It also allows
995  // us to flag multiple declaration errors as they occur.
996  if (ObjCImplementationDecl *ImpDecl =
997        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
998    if (MethodType == tok::minus) {
999      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1000      ImpDecl->addInstanceMethod(ObjCMethod);
1001    } else {
1002      PrevMethod = ImpDecl->getClassMethod(Sel);
1003      ImpDecl->addClassMethod(ObjCMethod);
1004    }
1005  }
1006  else if (ObjCCategoryImplDecl *CatImpDecl =
1007            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1008    if (MethodType == tok::minus) {
1009      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1010      CatImpDecl->addInstanceMethod(ObjCMethod);
1011    } else {
1012      PrevMethod = CatImpDecl->getClassMethod(Sel);
1013      CatImpDecl->addClassMethod(ObjCMethod);
1014    }
1015  }
1016  if (PrevMethod) {
1017    // You can never have two method definitions with the same name.
1018    Diag(ObjCMethod->getLocation(), diag::error_duplicate_method_decl,
1019        ObjCMethod->getSelector().getName());
1020    Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1021  }
1022  return ObjCMethod;
1023}
1024
1025Sema::DeclTy *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1026                                  FieldDeclarator &FD,
1027                                  ObjCDeclSpec &ODS,
1028                                  Selector GetterSel,
1029                                  Selector SetterSel,
1030                                  tok::ObjCKeywordKind MethodImplKind) {
1031  QualType T = GetTypeForDeclarator(FD.D, S);
1032  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, AtLoc,
1033                                                     FD.D.getIdentifier(), T);
1034  // Regardless of setter/getter attribute, we save the default getter/setter
1035  // selector names in anticipation of declaration of setter/getter methods.
1036  PDecl->setGetterName(GetterSel);
1037  PDecl->setSetterName(SetterSel);
1038
1039  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readonly)
1040    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1041
1042  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_getter)
1043    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1044
1045  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_setter)
1046    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1047
1048  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_assign)
1049    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1050
1051  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readwrite)
1052    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1053
1054  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_retain)
1055    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1056
1057  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_copy)
1058    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1059
1060  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nonatomic)
1061    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1062
1063  if (MethodImplKind == tok::objc_required)
1064    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1065  else if (MethodImplKind == tok::objc_optional)
1066    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1067
1068  return PDecl;
1069}
1070
1071/// ActOnPropertyImplDecl - This routine performs semantic checks and
1072/// builds the AST node for a property implementation declaration; declared
1073/// as @synthesize or @dynamic.
1074///
1075Sema::DeclTy *Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1076                                          SourceLocation PropertyLoc,
1077                                          bool Synthesize,
1078                                          DeclTy *ClassCatImpDecl,
1079                                          IdentifierInfo *PropertyId,
1080                                          IdentifierInfo *PropertyIvar) {
1081  Decl *ClassImpDecl = static_cast<Decl*>(ClassCatImpDecl);
1082  // Make sure we have a context for the property implementation declaration.
1083  if (!ClassImpDecl) {
1084    Diag(AtLoc, diag::error_missing_property_context);
1085    return 0;
1086  }
1087  ObjCPropertyDecl *property = 0;
1088  ObjCInterfaceDecl* IDecl = 0;
1089  // Find the class or category class where this property must have
1090  // a declaration.
1091  ObjCImplementationDecl *IC = 0;
1092  ObjCCategoryImplDecl* CatImplClass = 0;
1093  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1094    IDecl = getObjCInterfaceDecl(IC->getIdentifier());
1095    // We always synthesize an interface for an implementation
1096    // without an interface decl. So, IDecl is always non-zero.
1097    assert(IDecl &&
1098           "ActOnPropertyImplDecl - @implementation without @interface");
1099
1100    // Look for this property declaration in the @implementation's @interface
1101    property = IDecl->FindPropertyDeclaration(PropertyId);
1102    if (!property) {
1103       Diag(PropertyLoc, diag::error_bad_property_decl, IDecl->getName());
1104      return 0;
1105    }
1106  }
1107  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1108    if (Synthesize) {
1109      Diag(AtLoc, diag::error_synthesize_category_decl);
1110      return 0;
1111    }
1112    IDecl = CatImplClass->getClassInterface();
1113    if (!IDecl) {
1114      Diag(AtLoc, diag::error_missing_property_interface);
1115      return 0;
1116    }
1117    ObjCCategoryDecl *Category =
1118      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1119
1120    // If category for this implementation not found, it is an error which
1121    // has already been reported eralier.
1122    if (!Category)
1123      return 0;
1124    // Look for this property declaration in @implementation's category
1125    property = Category->FindPropertyDeclaration(PropertyId);
1126    if (!property) {
1127      Diag(PropertyLoc, diag::error_bad_category_property_decl,
1128           Category->getName());
1129      return 0;
1130    }
1131  }
1132  else {
1133    Diag(AtLoc, diag::error_bad_property_context);
1134    return 0;
1135  }
1136  ObjCIvarDecl *Ivar = 0;
1137  // Check that we have a valid, previously declared ivar for @synthesize
1138  if (Synthesize) {
1139    // @synthesize
1140    if (!PropertyIvar)
1141      PropertyIvar = PropertyId;
1142    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1143    Ivar = IDecl->FindIvarDeclaration(PropertyIvar);
1144    if (!Ivar) {
1145      Diag(PropertyLoc, diag::error_missing_property_ivar_decl,
1146           PropertyId->getName());
1147      return 0;
1148    }
1149    // Check that type of property and its ivar match.
1150    if (Context.getCanonicalType(Ivar->getType()) !=
1151        Context.getCanonicalType(property->getType())) {
1152      Diag(PropertyLoc, diag::error_property_ivar_type, property->getName(),
1153           Ivar->getName());
1154      return 0;
1155    }
1156
1157  } else if (PropertyIvar) {
1158    // @dynamic
1159    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1160    return 0;
1161  }
1162  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1163  ObjCPropertyImplDecl *PIDecl =
1164    ObjCPropertyImplDecl::Create(Context, AtLoc, PropertyLoc, property,
1165                                 (Synthesize ?
1166                                  ObjCPropertyImplDecl::OBJC_PR_IMPL_SYNTHSIZE
1167                                  : ObjCPropertyImplDecl::OBJC_PR_IMPL_DYNAMIC),
1168                                  Ivar);
1169  if (IC)
1170    IC->addPropertyImplementation(PIDecl);
1171  else
1172    CatImplClass->addPropertyImplementation(PIDecl);
1173
1174  return PIDecl;
1175}
1176