SemaDeclObjC.cpp revision 61f9d41036e30ff80130f99b31c0626e3ef057cc
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
37  // Create Decl objects for each parameter, entrring them in the scope for
38  // binding to their use.
39  struct DeclaratorChunk::ParamInfo PI;
40
41  // Insert the invisible arguments, self and _cmd!
42  PI.Ident = &Context.Idents.get("self");
43  PI.IdentLoc = SourceLocation(); // synthesized vars have a null location.
44  PI.InvalidType = false;
45  PI.AttrList = 0;
46  PI.TypeInfo = Context.getObjCIdType().getAsOpaquePtr();
47
48  if (MDecl->isInstance()) {
49    if (ObjCInterfaceDecl *OID = MDecl->getClassInterface()) {
50      // There may be no interface context due to error in declaration of the
51      // interface (which has been reported). Recover gracefully
52      QualType selfTy = Context.getObjCInterfaceType(OID);
53      selfTy = Context.getPointerType(selfTy);
54      PI.TypeInfo = selfTy.getAsOpaquePtr();
55    }
56  }
57
58  CurMethodDecl->setSelfDecl(ActOnParamDeclarator(PI, FnBodyScope));
59
60  PI.Ident = &Context.Idents.get("_cmd");
61  PI.TypeInfo = Context.getObjCSelType().getAsOpaquePtr();
62  ActOnParamDeclarator(PI, FnBodyScope);
63
64  for (unsigned i = 0, e = MDecl->getNumParams(); i != e; ++i) {
65    ParmVarDecl *PDecl = MDecl->getParamDecl(i);
66    PI.Ident = PDecl->getIdentifier();
67    PI.IdentLoc = PDecl->getLocation(); // user vars have a real location.
68    PI.TypeInfo = PDecl->getType().getAsOpaquePtr();
69    MDecl->setParamDecl(i, ActOnParamDeclarator(PI, FnBodyScope));
70  }
71}
72
73Sema::DeclTy *Sema::ActOnStartClassInterface(
74                    SourceLocation AtInterfaceLoc,
75                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
76                    IdentifierInfo *SuperName, SourceLocation SuperLoc,
77                    IdentifierInfo **ProtocolNames, unsigned NumProtocols,
78                    SourceLocation EndProtoLoc, AttributeList *AttrList) {
79  assert(ClassName && "Missing class identifier");
80
81  // Check for another declaration kind with the same name.
82  ScopedDecl *PrevDecl = LookupInterfaceDecl(ClassName);
83  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
84    Diag(ClassLoc, diag::err_redefinition_different_kind,
85         ClassName->getName());
86    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
87  }
88
89  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
90  if (IDecl) {
91    // Class already seen. Is it a forward declaration?
92    if (!IDecl->isForwardDecl())
93      Diag(AtInterfaceLoc, diag::err_duplicate_class_def, IDecl->getName());
94    else {
95      IDecl->setLocation(AtInterfaceLoc);
96      IDecl->setForwardDecl(false);
97      IDecl->AllocIntfRefProtocols(NumProtocols);
98    }
99  }
100  else {
101    IDecl = ObjCInterfaceDecl::Create(Context, AtInterfaceLoc, NumProtocols,
102                                      ClassName);
103
104    // Chain & install the interface decl into the identifier.
105    IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
106    ClassName->setFETokenInfo(IDecl);
107
108    // Remember that this needs to be removed when the scope is popped.
109    TUScope->AddDecl(IDecl);
110  }
111
112  if (SuperName) {
113    ObjCInterfaceDecl* SuperClassEntry = 0;
114    // Check if a different kind of symbol declared in this scope.
115    PrevDecl = LookupInterfaceDecl(SuperName);
116    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
117      Diag(SuperLoc, diag::err_redefinition_different_kind,
118           SuperName->getName());
119      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
120    }
121    else {
122      // Check that super class is previously defined
123      SuperClassEntry = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
124
125      if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
126        Diag(AtInterfaceLoc, diag::err_undef_superclass,
127             SuperClassEntry ? SuperClassEntry->getName()
128                             : SuperName->getName(),
129             ClassName->getName());
130      }
131    }
132    IDecl->setSuperClass(SuperClassEntry);
133    IDecl->setLocEnd(SuperLoc);
134  } else { // we have a root class.
135    IDecl->setLocEnd(ClassLoc);
136  }
137
138  /// Check then save referenced protocols
139  if (NumProtocols) {
140    for (unsigned int i = 0; i != NumProtocols; i++) {
141      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtocolNames[i]];
142      if (!RefPDecl || RefPDecl->isForwardDecl())
143        Diag(ClassLoc, diag::warn_undef_protocolref,
144             ProtocolNames[i]->getName(),
145             ClassName->getName());
146      IDecl->setIntfRefProtocols(i, RefPDecl);
147    }
148    IDecl->setLocEnd(EndProtoLoc);
149  }
150  return IDecl;
151}
152
153/// ActOnCompatiblityAlias - this action is called after complete parsing of
154/// @compaatibility_alias declaration. It sets up the alias relationships.
155Sema::DeclTy *Sema::ActOnCompatiblityAlias(
156                      SourceLocation AtCompatibilityAliasLoc,
157                      IdentifierInfo *AliasName,  SourceLocation AliasLocation,
158                      IdentifierInfo *ClassName, SourceLocation ClassLocation) {
159  // Look for previous declaration of alias name
160  ScopedDecl *ADecl = LookupScopedDecl(AliasName, Decl::IDNS_Ordinary,
161                                       AliasLocation, TUScope);
162  if (ADecl) {
163    if (isa<ObjCCompatibleAliasDecl>(ADecl)) {
164      Diag(AliasLocation, diag::warn_previous_alias_decl);
165      Diag(ADecl->getLocation(), diag::warn_previous_declaration);
166    }
167    else {
168      Diag(AliasLocation, diag::err_conflicting_aliasing_type,
169           AliasName->getName());
170      Diag(ADecl->getLocation(), diag::err_previous_declaration);
171    }
172    return 0;
173  }
174  // Check for class declaration
175  ScopedDecl *CDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
176                                       ClassLocation, TUScope);
177  if (!CDecl || !isa<ObjCInterfaceDecl>(CDecl)) {
178    Diag(ClassLocation, diag::warn_undef_interface,
179         ClassName->getName());
180    if (CDecl)
181      Diag(CDecl->getLocation(), diag::warn_previous_declaration);
182    return 0;
183  }
184  // Everything checked out, instantiate a new alias declaration ast
185  ObjCCompatibleAliasDecl *AliasDecl =
186    new ObjCCompatibleAliasDecl(AtCompatibilityAliasLoc,
187                                AliasName,
188                                dyn_cast<ObjCInterfaceDecl>(CDecl));
189
190  // Chain & install the interface decl into the identifier.
191  AliasDecl->setNext(AliasName->getFETokenInfo<ScopedDecl>());
192  AliasName->setFETokenInfo(AliasDecl);
193  return AliasDecl;
194}
195
196Sema::DeclTy *Sema::ActOnStartProtocolInterface(
197                SourceLocation AtProtoInterfaceLoc,
198                IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
199                IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
200                SourceLocation EndProtoLoc) {
201  assert(ProtocolName && "Missing protocol identifier");
202  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
203  if (PDecl) {
204    // Protocol already seen. Better be a forward protocol declaration
205    if (!PDecl->isForwardDecl()) {
206      Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
207           ProtocolName->getName());
208      // Just return the protocol we already had.
209      // FIXME: don't leak the objects passed in!
210      return PDecl;
211    }
212
213    PDecl->setForwardDecl(false);
214    PDecl->AllocReferencedProtocols(NumProtoRefs);
215  } else {
216    PDecl = ObjCProtocolDecl::Create(Context, AtProtoInterfaceLoc, NumProtoRefs,
217                                     ProtocolName);
218    PDecl->setForwardDecl(false);
219    ObjCProtocols[ProtocolName] = PDecl;
220  }
221
222  if (NumProtoRefs) {
223    /// Check then save referenced protocols.
224    for (unsigned int i = 0; i != NumProtoRefs; i++) {
225      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtoRefNames[i]];
226      if (!RefPDecl || RefPDecl->isForwardDecl())
227        Diag(ProtocolLoc, diag::warn_undef_protocolref,
228             ProtoRefNames[i]->getName(),
229             ProtocolName->getName());
230      PDecl->setReferencedProtocols(i, RefPDecl);
231    }
232    PDecl->setLocEnd(EndProtoLoc);
233  }
234  return PDecl;
235}
236
237/// FindProtocolDeclaration - This routine looks up protocols and
238/// issuer error if they are not declared. It returns list of protocol
239/// declarations in its 'Protocols' argument.
240void
241Sema::FindProtocolDeclaration(SourceLocation TypeLoc,
242                              IdentifierInfo **ProtocolId,
243                              unsigned NumProtocols,
244                              llvm::SmallVector<DeclTy *,8> &Protocols) {
245  for (unsigned i = 0; i != NumProtocols; ++i) {
246    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i]];
247    if (!PDecl)
248      Diag(TypeLoc, diag::err_undeclared_protocol,
249           ProtocolId[i]->getName());
250    else
251      Protocols.push_back(PDecl);
252  }
253}
254
255/// ActOnForwardProtocolDeclaration -
256Action::DeclTy *
257Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
258        IdentifierInfo **IdentList, unsigned NumElts) {
259  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
260
261  for (unsigned i = 0; i != NumElts; ++i) {
262    IdentifierInfo *Ident = IdentList[i];
263    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
264    if (PDecl == 0)  { // Not already seen?
265      // FIXME: Pass in the location of the identifier!
266      PDecl = ObjCProtocolDecl::Create(Context, AtProtocolLoc, 0, Ident);
267    }
268
269    Protocols.push_back(PDecl);
270  }
271  return ObjCForwardProtocolDecl::Create(Context, AtProtocolLoc,
272                                         &Protocols[0], Protocols.size());
273}
274
275Sema::DeclTy *Sema::ActOnStartCategoryInterface(
276                      SourceLocation AtInterfaceLoc,
277                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
278                      IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
279                      IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
280                      SourceLocation EndProtoLoc) {
281  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
282
283  ObjCCategoryDecl *CDecl =
284    ObjCCategoryDecl::Create(Context, AtInterfaceLoc, NumProtoRefs,
285                             CategoryName);
286  CDecl->setClassInterface(IDecl);
287
288  /// Check that class of this category is already completely declared.
289  if (!IDecl || IDecl->isForwardDecl())
290    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
291  else {
292    /// Check for duplicate interface declaration for this category
293    ObjCCategoryDecl *CDeclChain;
294    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
295         CDeclChain = CDeclChain->getNextClassCategory()) {
296      if (CDeclChain->getIdentifier() == CategoryName) {
297        Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
298             CategoryName->getName());
299        break;
300      }
301    }
302  if (!CDeclChain)
303    CDecl->insertNextClassCategory();
304  }
305
306  if (NumProtoRefs) {
307    /// Check then save referenced protocols
308    for (unsigned int i = 0; i != NumProtoRefs; i++) {
309      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtoRefNames[i]];
310      if (!RefPDecl || RefPDecl->isForwardDecl()) {
311        Diag(CategoryLoc, diag::warn_undef_protocolref,
312             ProtoRefNames[i]->getName(),
313             CategoryName->getName());
314      }
315      CDecl->setCatReferencedProtocols(i, RefPDecl);
316    }
317    CDecl->setLocEnd(EndProtoLoc);
318  }
319  return CDecl;
320}
321
322/// ActOnStartCategoryImplementation - Perform semantic checks on the
323/// category implementation declaration and build an ObjCCategoryImplDecl
324/// object.
325Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
326                      SourceLocation AtCatImplLoc,
327                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
328                      IdentifierInfo *CatName, SourceLocation CatLoc) {
329  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
330  ObjCCategoryImplDecl *CDecl = new ObjCCategoryImplDecl(AtCatImplLoc,
331                                                         CatName, IDecl);
332  /// Check that class of this category is already completely declared.
333  if (!IDecl || IDecl->isForwardDecl())
334    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
335
336  /// TODO: Check that CatName, category name, is not used in another
337  // implementation.
338  return CDecl;
339}
340
341Sema::DeclTy *Sema::ActOnStartClassImplementation(
342                      SourceLocation AtClassImplLoc,
343                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
344                      IdentifierInfo *SuperClassname,
345                      SourceLocation SuperClassLoc) {
346  ObjCInterfaceDecl* IDecl = 0;
347  // Check for another declaration kind with the same name.
348  ScopedDecl *PrevDecl = LookupInterfaceDecl(ClassName);
349  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
350    Diag(ClassLoc, diag::err_redefinition_different_kind,
351         ClassName->getName());
352    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
353  }
354  else {
355    // Is there an interface declaration of this class; if not, warn!
356    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
357    if (!IDecl)
358      Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
359  }
360
361  // Check that super class name is valid class name
362  ObjCInterfaceDecl* SDecl = 0;
363  if (SuperClassname) {
364    // Check if a different kind of symbol declared in this scope.
365    PrevDecl = LookupInterfaceDecl(SuperClassname);
366    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
367      Diag(SuperClassLoc, diag::err_redefinition_different_kind,
368           SuperClassname->getName());
369      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
370    }
371    else {
372      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
373      if (!SDecl)
374        Diag(SuperClassLoc, diag::err_undef_superclass,
375             SuperClassname->getName(), ClassName->getName());
376      else if (IDecl && IDecl->getSuperClass() != SDecl) {
377        // This implementation and its interface do not have the same
378        // super class.
379        Diag(SuperClassLoc, diag::err_conflicting_super_class,
380             SDecl->getName());
381        Diag(SDecl->getLocation(), diag::err_previous_definition);
382      }
383    }
384  }
385
386  if (!IDecl) {
387    // Legacy case of @implementation with no corresponding @interface.
388    // Build, chain & install the interface decl into the identifier.
389    IDecl = ObjCInterfaceDecl::Create(Context, AtClassImplLoc, 0, ClassName,
390                                      false, true);
391    IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
392    ClassName->setFETokenInfo(IDecl);
393    IDecl->setSuperClass(SDecl);
394    IDecl->setLocEnd(ClassLoc);
395
396    // Remember that this needs to be removed when the scope is popped.
397    TUScope->AddDecl(IDecl);
398  }
399
400  ObjCImplementationDecl* IMPDecl =
401  new ObjCImplementationDecl(AtClassImplLoc, ClassName, IDecl, SDecl);
402
403  // Check that there is no duplicate implementation of this class.
404  if (ObjCImplementations[ClassName])
405    Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
406  else // add it to the list.
407    ObjCImplementations[ClassName] = IMPDecl;
408  return IMPDecl;
409}
410
411void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
412                                    ObjCIvarDecl **ivars, unsigned numIvars,
413                                    SourceLocation RBrace) {
414  assert(ImpDecl && "missing implementation decl");
415  ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
416  if (!IDecl)
417    return;
418  /// Check case of non-existing @interface decl.
419  /// (legacy objective-c @implementation decl without an @interface decl).
420  /// Add implementations's ivar to the synthesize class's ivar list.
421  if (IDecl->ImplicitInterfaceDecl()) {
422    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
423    return;
424  }
425  // If implementation has empty ivar list, just return.
426  if (numIvars == 0)
427    return;
428
429  assert(ivars && "missing @implementation ivars");
430
431  // Check interface's Ivar list against those in the implementation.
432  // names and types must match.
433  //
434  unsigned j = 0;
435  ObjCInterfaceDecl::ivar_iterator
436    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
437  for (; numIvars > 0 && IVI != IVE; ++IVI) {
438    ObjCIvarDecl* ImplIvar = ivars[j++];
439    ObjCIvarDecl* ClsIvar = *IVI;
440    assert (ImplIvar && "missing implementation ivar");
441    assert (ClsIvar && "missing class ivar");
442    if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
443      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
444           ImplIvar->getIdentifier()->getName());
445      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
446           ClsIvar->getIdentifier()->getName());
447    }
448    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
449    // as error.
450    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
451      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
452           ImplIvar->getIdentifier()->getName());
453      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
454           ClsIvar->getIdentifier()->getName());
455      return;
456    }
457    --numIvars;
458  }
459
460  if (numIvars > 0)
461    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
462  else if (IVI != IVE)
463    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
464}
465
466void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
467                               bool &IncompleteImpl) {
468  if (!IncompleteImpl) {
469    Diag(ImpLoc, diag::warn_incomplete_impl);
470    IncompleteImpl = true;
471  }
472  Diag(ImpLoc, diag::warn_undef_method_impl, method->getSelector().getName());
473}
474
475/// CheckProtocolMethodDefs - This routine checks unimplemented methods
476/// Declared in protocol, and those referenced by it.
477void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
478                                   ObjCProtocolDecl *PDecl,
479                                   bool& IncompleteImpl,
480                                   const llvm::DenseSet<Selector> &InsMap,
481                                   const llvm::DenseSet<Selector> &ClsMap) {
482  // check unimplemented instance methods.
483  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
484       E = PDecl->instmeth_end(); I != E; ++I) {
485    ObjCMethodDecl *method = *I;
486    if (!InsMap.count(method->getSelector()) &&
487        method->getImplementationControl() != ObjCMethodDecl::Optional)
488      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
489  }
490  // check unimplemented class methods
491  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
492       E = PDecl->classmeth_end(); I != E; ++I) {
493    ObjCMethodDecl *method = *I;
494    if (!ClsMap.count(method->getSelector()) &&
495        method->getImplementationControl() != ObjCMethodDecl::Optional)
496      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
497  }
498  // Check on this protocols's referenced protocols, recursively
499  ObjCProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
500  for (unsigned i = 0; i < PDecl->getNumReferencedProtocols(); i++)
501    CheckProtocolMethodDefs(ImpLoc, RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
502}
503
504void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
505                                     ObjCInterfaceDecl* IDecl) {
506  llvm::DenseSet<Selector> InsMap;
507  // Check and see if instance methods in class interface have been
508  // implemented in the implementation class.
509  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
510       E = IMPDecl->instmeth_end(); I != E; ++I)
511    InsMap.insert((*I)->getSelector());
512
513  bool IncompleteImpl = false;
514  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
515       E = IDecl->instmeth_end(); I != E; ++I)
516    if (!InsMap.count((*I)->getSelector()))
517      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
518
519  llvm::DenseSet<Selector> ClsMap;
520  // Check and see if class methods in class interface have been
521  // implemented in the implementation class.
522  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
523       E = IMPDecl->classmeth_end(); I != E; ++I)
524    ClsMap.insert((*I)->getSelector());
525
526  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
527       E = IDecl->classmeth_end(); I != E; ++I)
528    if (!ClsMap.count((*I)->getSelector()))
529      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
530
531  // Check the protocol list for unimplemented methods in the @implementation
532  // class.
533  ObjCProtocolDecl** protocols = IDecl->getReferencedProtocols();
534  for (unsigned i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
535    CheckProtocolMethodDefs(IMPDecl->getLocation(), protocols[i],
536                            IncompleteImpl, InsMap, ClsMap);
537}
538
539/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
540/// category interface is implemented in the category @implementation.
541void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
542                                            ObjCCategoryDecl *CatClassDecl) {
543  llvm::DenseSet<Selector> InsMap;
544  // Check and see if instance methods in category interface have been
545  // implemented in its implementation class.
546  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
547       E = CatImplDecl->instmeth_end(); I != E; ++I)
548    InsMap.insert((*I)->getSelector());
549
550  bool IncompleteImpl = false;
551  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
552       E = CatClassDecl->instmeth_end(); I != E; ++I)
553    if (!InsMap.count((*I)->getSelector()))
554      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
555
556  llvm::DenseSet<Selector> ClsMap;
557  // Check and see if class methods in category interface have been
558  // implemented in its implementation class.
559  for (ObjCCategoryImplDecl::classmeth_iterator
560       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
561       I != E; ++I)
562    ClsMap.insert((*I)->getSelector());
563
564  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
565       E = CatClassDecl->classmeth_end(); I != E; ++I)
566    if (!ClsMap.count((*I)->getSelector()))
567      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
568
569  // Check the protocol list for unimplemented methods in the @implementation
570  // class.
571  ObjCProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
572  for (unsigned i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
573    ObjCProtocolDecl* PDecl = protocols[i];
574    CheckProtocolMethodDefs(CatImplDecl->getLocation(), PDecl, IncompleteImpl,
575                            InsMap, ClsMap);
576  }
577}
578
579/// ActOnForwardClassDeclaration -
580Action::DeclTy *
581Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
582                                   IdentifierInfo **IdentList, unsigned NumElts)
583{
584  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
585
586  for (unsigned i = 0; i != NumElts; ++i) {
587    // Check for another declaration kind with the same name.
588    ScopedDecl *PrevDecl = LookupInterfaceDecl(IdentList[i]);
589    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
590      Diag(AtClassLoc, diag::err_redefinition_different_kind,
591           IdentList[i]->getName());
592      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
593    }
594    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
595    if (!IDecl) {  // Not already seen?  Make a forward decl.
596      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, 0, IdentList[i],
597                                        true);
598      // Chain & install the interface decl into the identifier.
599      IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
600      IdentList[i]->setFETokenInfo(IDecl);
601
602      // Remember that this needs to be removed when the scope is popped.
603      TUScope->AddDecl(IDecl);
604    }
605
606    Interfaces.push_back(IDecl);
607  }
608
609  return ObjCClassDecl::Create(Context, AtClassLoc,
610                               &Interfaces[0], Interfaces.size());
611}
612
613
614/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
615/// returns true, or false, accordingly.
616/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
617bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
618                                      const ObjCMethodDecl *PrevMethod) {
619  if (Method->getResultType().getCanonicalType() !=
620      PrevMethod->getResultType().getCanonicalType())
621    return false;
622  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
623    ParmVarDecl *ParamDecl = Method->getParamDecl(i);
624    ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
625    if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
626      return false;
627  }
628  return true;
629}
630
631void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
632  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
633  if (!FirstMethod.Method) {
634    // Haven't seen a method with this selector name yet - add it.
635    FirstMethod.Method = Method;
636    FirstMethod.Next = 0;
637  } else {
638    // We've seen a method with this name, now check the type signature(s).
639    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
640
641    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
642         Next = Next->Next)
643      match = MatchTwoMethodDeclarations(Method, Next->Method);
644
645    if (!match) {
646      // We have a new signature for an existing method - add it.
647      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
648      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
649      FirstMethod.Next = OMI;
650    }
651  }
652}
653
654void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
655  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
656  if (!FirstMethod.Method) {
657    // Haven't seen a method with this selector name yet - add it.
658    FirstMethod.Method = Method;
659    FirstMethod.Next = 0;
660  } else {
661    // We've seen a method with this name, now check the type signature(s).
662    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
663
664    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
665         Next = Next->Next)
666      match = MatchTwoMethodDeclarations(Method, Next->Method);
667
668    if (!match) {
669      // We have a new signature for an existing method - add it.
670      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
671      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
672      FirstMethod.Next = OMI;
673    }
674  }
675}
676
677// Note: For class/category implemenations, allMethods/allProperties is
678// always null.
679void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
680                      DeclTy **allMethods, unsigned allNum,
681                      DeclTy **allProperties, unsigned pNum) {
682  Decl *ClassDecl = static_cast<Decl *>(classDecl);
683
684  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
685  // always passing in a decl. If the decl has an error, isInvalidDecl()
686  // should be true.
687  if (!ClassDecl)
688    return;
689
690  llvm::SmallVector<ObjCMethodDecl*, 32> insMethods;
691  llvm::SmallVector<ObjCMethodDecl*, 16> clsMethods;
692
693  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
694  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
695
696  bool isInterfaceDeclKind =
697        (isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
698         || isa<ObjCProtocolDecl>(ClassDecl));
699  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
700
701  // TODO: property declaration in category and protocols.
702  if (pNum != 0 && isa<ObjCInterfaceDecl>(ClassDecl)) {
703    ObjCPropertyDecl **properties = new ObjCPropertyDecl*[pNum];
704    memcpy(properties, allProperties, pNum*sizeof(ObjCPropertyDecl*));
705    dyn_cast<ObjCInterfaceDecl>(ClassDecl)->setPropertyDecls(properties);
706    dyn_cast<ObjCInterfaceDecl>(ClassDecl)->setNumPropertyDecl(pNum);
707  }
708
709  for (unsigned i = 0; i < allNum; i++ ) {
710    ObjCMethodDecl *Method =
711      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
712
713    if (!Method) continue;  // Already issued a diagnostic.
714    if (Method->isInstance()) {
715      /// Check for instance method of the same name with incompatible types
716      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
717      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
718                              : false;
719      if (isInterfaceDeclKind && PrevMethod && !match
720          || checkIdenticalMethods && match) {
721          Diag(Method->getLocation(), diag::error_duplicate_method_decl,
722               Method->getSelector().getName());
723          Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
724      } else {
725        insMethods.push_back(Method);
726        InsMap[Method->getSelector()] = Method;
727        /// The following allows us to typecheck messages to "id".
728        AddInstanceMethodToGlobalPool(Method);
729      }
730    }
731    else {
732      /// Check for class method of the same name with incompatible types
733      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
734      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
735                              : false;
736      if (isInterfaceDeclKind && PrevMethod && !match
737          || checkIdenticalMethods && match) {
738        Diag(Method->getLocation(), diag::error_duplicate_method_decl,
739             Method->getSelector().getName());
740        Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
741      } else {
742        clsMethods.push_back(Method);
743        ClsMap[Method->getSelector()] = Method;
744        /// The following allows us to typecheck messages to "Class".
745        AddFactoryMethodToGlobalPool(Method);
746      }
747    }
748  }
749
750  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
751    I->addMethods(&insMethods[0], insMethods.size(),
752                  &clsMethods[0], clsMethods.size(), AtEndLoc);
753  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
754    P->addMethods(&insMethods[0], insMethods.size(),
755                  &clsMethods[0], clsMethods.size(), AtEndLoc);
756  }
757  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
758    C->addMethods(&insMethods[0], insMethods.size(),
759                  &clsMethods[0], clsMethods.size(), AtEndLoc);
760  }
761  else if (ObjCImplementationDecl *IC =
762                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
763    IC->setLocEnd(AtEndLoc);
764    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
765      ImplMethodsVsClassMethods(IC, IDecl);
766  } else {
767    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
768    CatImplClass->setLocEnd(AtEndLoc);
769    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
770    // Find category interface decl and then check that all methods declared
771    // in this interface is implemented in the category @implementation.
772    if (IDecl) {
773      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
774           Categories; Categories = Categories->getNextClassCategory()) {
775        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
776          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
777          break;
778        }
779      }
780    }
781  }
782}
783
784
785/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
786/// objective-c's type qualifier from the parser version of the same info.
787static Decl::ObjCDeclQualifier
788CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
789  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
790  if (PQTVal & ObjCDeclSpec::DQ_In)
791    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
792  if (PQTVal & ObjCDeclSpec::DQ_Inout)
793    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
794  if (PQTVal & ObjCDeclSpec::DQ_Out)
795    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
796  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
797    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
798  if (PQTVal & ObjCDeclSpec::DQ_Byref)
799    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
800  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
801    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
802
803  return ret;
804}
805
806Sema::DeclTy *Sema::ActOnMethodDeclaration(
807    SourceLocation MethodLoc, SourceLocation EndLoc,
808    tok::TokenKind MethodType, DeclTy *classDecl,
809    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
810    Selector Sel,
811    // optional arguments. The number of types/arguments is obtained
812    // from the Sel.getNumArgs().
813    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
814    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
815    bool isVariadic) {
816  Decl *ClassDecl = static_cast<Decl*>(classDecl);
817
818  // Make sure we can establish a context for the method.
819  if (!ClassDecl) {
820    Diag(MethodLoc, diag::error_missing_method_context);
821    return 0;
822  }
823  llvm::SmallVector<ParmVarDecl*, 16> Params;
824
825  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
826    // FIXME: arg->AttrList must be stored too!
827    QualType argType;
828
829    if (ArgTypes[i])
830      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
831    else
832      argType = Context.getObjCIdType();
833    ParmVarDecl* Param = ParmVarDecl::Create(Context, SourceLocation(/*FIXME*/),
834                                             ArgNames[i], argType,
835                                             VarDecl::None, 0);
836    Param->setObjCDeclQualifier(
837      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
838    Params.push_back(Param);
839  }
840  QualType resultDeclType;
841
842  if (ReturnType)
843    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
844  else // get the type for "id".
845    resultDeclType = Context.getObjCIdType();
846
847  ObjCMethodDecl* ObjCMethod =
848    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
849                           ClassDecl, AttrList,
850                           MethodType == tok::minus, isVariadic,
851                           MethodDeclKind == tok::objc_optional ?
852                           ObjCMethodDecl::Optional :
853                           ObjCMethodDecl::Required);
854
855  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
856  ObjCMethod->setObjCDeclQualifier(
857    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
858  const ObjCMethodDecl *PrevMethod = 0;
859
860  // For implementations (which can be very "coarse grain"), we add the
861  // method now. This allows the AST to implement lookup methods that work
862  // incrementally (without waiting until we parse the @end). It also allows
863  // us to flag multiple declaration errors as they occur.
864  if (ObjCImplementationDecl *ImpDecl =
865        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
866    if (MethodType == tok::minus) {
867      PrevMethod = ImpDecl->getInstanceMethod(Sel);
868      ImpDecl->addInstanceMethod(ObjCMethod);
869    } else {
870      PrevMethod = ImpDecl->getClassMethod(Sel);
871      ImpDecl->addClassMethod(ObjCMethod);
872    }
873  }
874  else if (ObjCCategoryImplDecl *CatImpDecl =
875            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
876    if (MethodType == tok::minus) {
877      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
878      CatImpDecl->addInstanceMethod(ObjCMethod);
879    } else {
880      PrevMethod = CatImpDecl->getClassMethod(Sel);
881      CatImpDecl->addClassMethod(ObjCMethod);
882    }
883  }
884  if (PrevMethod) {
885    // You can never have two method definitions with the same name.
886    Diag(ObjCMethod->getLocation(), diag::error_duplicate_method_decl,
887        ObjCMethod->getSelector().getName());
888    Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
889  }
890  return ObjCMethod;
891}
892
893Sema::DeclTy *Sema::ActOnAddObjCProperties(SourceLocation AtLoc,
894  DeclTy **allProperties, unsigned NumProperties, ObjCDeclSpec &DS) {
895  ObjCPropertyDecl *PDecl = new ObjCPropertyDecl(AtLoc);
896
897  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readonly)
898    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
899
900  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_getter) {
901    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
902    PDecl->setGetterName(DS.getGetterName());
903  }
904
905  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_setter) {
906    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
907    PDecl->setSetterName(DS.getSetterName());
908  }
909
910  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_assign)
911    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
912
913  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readwrite)
914    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
915
916  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_retain)
917    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
918
919  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_copy)
920    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
921
922  if(DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nonatomic)
923    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
924
925  PDecl->setNumPropertyDecls(NumProperties);
926  if (NumProperties != 0) {
927    ObjCIvarDecl **properties = new ObjCIvarDecl*[NumProperties];
928    memcpy(properties, allProperties, NumProperties*sizeof(ObjCIvarDecl*));
929    PDecl->setPropertyDecls(properties);
930  }
931  return PDecl;
932}
933
934