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