SemaDeclObjC.cpp revision 44859618fbb881db1728da0bb6e82553f579d2ec
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 *CDeclU = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
176                                        ClassLocation, TUScope);
177  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
178  if (CDecl == 0) {
179    Diag(ClassLocation, diag::warn_undef_interface, ClassName->getName());
180    if (CDeclU)
181      Diag(CDeclU->getLocation(), diag::warn_previous_declaration);
182    return 0;
183  }
184
185  // Everything checked out, instantiate a new alias declaration AST.
186  ObjCCompatibleAliasDecl *AliasDecl =
187    ObjCCompatibleAliasDecl::Create(Context, AtCompatibilityAliasLoc,
188                                    AliasName, 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, CategoryName);
285  CDecl->setClassInterface(IDecl);
286
287  /// Check that class of this category is already completely declared.
288  if (!IDecl || IDecl->isForwardDecl())
289    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
290  else {
291    /// Check for duplicate interface declaration for this category
292    ObjCCategoryDecl *CDeclChain;
293    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
294         CDeclChain = CDeclChain->getNextClassCategory()) {
295      if (CDeclChain->getIdentifier() == CategoryName) {
296        Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
297             CategoryName->getName());
298        break;
299      }
300    }
301  if (!CDeclChain)
302    CDecl->insertNextClassCategory();
303  }
304
305  if (NumProtoRefs) {
306    llvm::SmallVector<ObjCProtocolDecl*, 32> RefProtocols;
307    /// Check and then save the 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      if (RefPDecl)
316        RefProtocols.push_back(RefPDecl);
317    }
318    if (!RefProtocols.empty())
319      CDecl->setReferencedProtocolList(&RefProtocols[0], RefProtocols.size());
320  }
321  CDecl->setLocEnd(EndProtoLoc);
322  return CDecl;
323}
324
325/// ActOnStartCategoryImplementation - Perform semantic checks on the
326/// category implementation declaration and build an ObjCCategoryImplDecl
327/// object.
328Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
329                      SourceLocation AtCatImplLoc,
330                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
331                      IdentifierInfo *CatName, SourceLocation CatLoc) {
332  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
333  ObjCCategoryImplDecl *CDecl =
334    ObjCCategoryImplDecl::Create(Context, AtCatImplLoc, CatName, IDecl);
335  /// Check that class of this category is already completely declared.
336  if (!IDecl || IDecl->isForwardDecl())
337    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
338
339  /// TODO: Check that CatName, category name, is not used in another
340  // implementation.
341  return CDecl;
342}
343
344Sema::DeclTy *Sema::ActOnStartClassImplementation(
345                      SourceLocation AtClassImplLoc,
346                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
347                      IdentifierInfo *SuperClassname,
348                      SourceLocation SuperClassLoc) {
349  ObjCInterfaceDecl* IDecl = 0;
350  // Check for another declaration kind with the same name.
351  ScopedDecl *PrevDecl = LookupInterfaceDecl(ClassName);
352  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
353    Diag(ClassLoc, diag::err_redefinition_different_kind,
354         ClassName->getName());
355    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
356  }
357  else {
358    // Is there an interface declaration of this class; if not, warn!
359    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
360    if (!IDecl)
361      Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
362  }
363
364  // Check that super class name is valid class name
365  ObjCInterfaceDecl* SDecl = 0;
366  if (SuperClassname) {
367    // Check if a different kind of symbol declared in this scope.
368    PrevDecl = LookupInterfaceDecl(SuperClassname);
369    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
370      Diag(SuperClassLoc, diag::err_redefinition_different_kind,
371           SuperClassname->getName());
372      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
373    }
374    else {
375      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
376      if (!SDecl)
377        Diag(SuperClassLoc, diag::err_undef_superclass,
378             SuperClassname->getName(), ClassName->getName());
379      else if (IDecl && IDecl->getSuperClass() != SDecl) {
380        // This implementation and its interface do not have the same
381        // super class.
382        Diag(SuperClassLoc, diag::err_conflicting_super_class,
383             SDecl->getName());
384        Diag(SDecl->getLocation(), diag::err_previous_definition);
385      }
386    }
387  }
388
389  if (!IDecl) {
390    // Legacy case of @implementation with no corresponding @interface.
391    // Build, chain & install the interface decl into the identifier.
392    IDecl = ObjCInterfaceDecl::Create(Context, AtClassImplLoc, 0, ClassName,
393                                      false, true);
394    IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
395    ClassName->setFETokenInfo(IDecl);
396    IDecl->setSuperClass(SDecl);
397    IDecl->setLocEnd(ClassLoc);
398
399    // Remember that this needs to be removed when the scope is popped.
400    TUScope->AddDecl(IDecl);
401  }
402
403  ObjCImplementationDecl* IMPDecl =
404    ObjCImplementationDecl::Create(Context, AtClassImplLoc, ClassName,
405                                   IDecl, SDecl);
406
407  // Check that there is no duplicate implementation of this class.
408  if (ObjCImplementations[ClassName])
409    // FIXME: Don't leak everything!
410    Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
411  else // add it to the list.
412    ObjCImplementations[ClassName] = IMPDecl;
413  return IMPDecl;
414}
415
416void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
417                                    ObjCIvarDecl **ivars, unsigned numIvars,
418                                    SourceLocation RBrace) {
419  assert(ImpDecl && "missing implementation decl");
420  ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
421  if (!IDecl)
422    return;
423  /// Check case of non-existing @interface decl.
424  /// (legacy objective-c @implementation decl without an @interface decl).
425  /// Add implementations's ivar to the synthesize class's ivar list.
426  if (IDecl->ImplicitInterfaceDecl()) {
427    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
428    return;
429  }
430  // If implementation has empty ivar list, just return.
431  if (numIvars == 0)
432    return;
433
434  assert(ivars && "missing @implementation ivars");
435
436  // Check interface's Ivar list against those in the implementation.
437  // names and types must match.
438  //
439  unsigned j = 0;
440  ObjCInterfaceDecl::ivar_iterator
441    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
442  for (; numIvars > 0 && IVI != IVE; ++IVI) {
443    ObjCIvarDecl* ImplIvar = ivars[j++];
444    ObjCIvarDecl* ClsIvar = *IVI;
445    assert (ImplIvar && "missing implementation ivar");
446    assert (ClsIvar && "missing class ivar");
447    if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
448      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
449           ImplIvar->getIdentifier()->getName());
450      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
451           ClsIvar->getIdentifier()->getName());
452    }
453    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
454    // as error.
455    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
456      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
457           ImplIvar->getIdentifier()->getName());
458      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
459           ClsIvar->getIdentifier()->getName());
460      return;
461    }
462    --numIvars;
463  }
464
465  if (numIvars > 0)
466    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
467  else if (IVI != IVE)
468    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
469}
470
471void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
472                               bool &IncompleteImpl) {
473  if (!IncompleteImpl) {
474    Diag(ImpLoc, diag::warn_incomplete_impl);
475    IncompleteImpl = true;
476  }
477  Diag(ImpLoc, diag::warn_undef_method_impl, method->getSelector().getName());
478}
479
480/// CheckProtocolMethodDefs - This routine checks unimplemented methods
481/// Declared in protocol, and those referenced by it.
482void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
483                                   ObjCProtocolDecl *PDecl,
484                                   bool& IncompleteImpl,
485                                   const llvm::DenseSet<Selector> &InsMap,
486                                   const llvm::DenseSet<Selector> &ClsMap) {
487  // check unimplemented instance methods.
488  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
489       E = PDecl->instmeth_end(); I != E; ++I) {
490    ObjCMethodDecl *method = *I;
491    if (!InsMap.count(method->getSelector()) &&
492        method->getImplementationControl() != ObjCMethodDecl::Optional)
493      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
494  }
495  // check unimplemented class methods
496  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
497       E = PDecl->classmeth_end(); I != E; ++I) {
498    ObjCMethodDecl *method = *I;
499    if (!ClsMap.count(method->getSelector()) &&
500        method->getImplementationControl() != ObjCMethodDecl::Optional)
501      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
502  }
503  // Check on this protocols's referenced protocols, recursively
504  ObjCProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
505  for (unsigned i = 0; i < PDecl->getNumReferencedProtocols(); i++)
506    CheckProtocolMethodDefs(ImpLoc, RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
507}
508
509void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
510                                     ObjCInterfaceDecl* IDecl) {
511  llvm::DenseSet<Selector> InsMap;
512  // Check and see if instance methods in class interface have been
513  // implemented in the implementation class.
514  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
515       E = IMPDecl->instmeth_end(); I != E; ++I)
516    InsMap.insert((*I)->getSelector());
517
518  bool IncompleteImpl = false;
519  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
520       E = IDecl->instmeth_end(); I != E; ++I)
521    if (!InsMap.count((*I)->getSelector()))
522      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
523
524  llvm::DenseSet<Selector> ClsMap;
525  // Check and see if class methods in class interface have been
526  // implemented in the implementation class.
527  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
528       E = IMPDecl->classmeth_end(); I != E; ++I)
529    ClsMap.insert((*I)->getSelector());
530
531  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
532       E = IDecl->classmeth_end(); I != E; ++I)
533    if (!ClsMap.count((*I)->getSelector()))
534      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
535
536  // Check the protocol list for unimplemented methods in the @implementation
537  // class.
538  ObjCProtocolDecl** protocols = IDecl->getReferencedProtocols();
539  for (unsigned i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
540    CheckProtocolMethodDefs(IMPDecl->getLocation(), protocols[i],
541                            IncompleteImpl, InsMap, ClsMap);
542}
543
544/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
545/// category interface is implemented in the category @implementation.
546void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
547                                            ObjCCategoryDecl *CatClassDecl) {
548  llvm::DenseSet<Selector> InsMap;
549  // Check and see if instance methods in category interface have been
550  // implemented in its implementation class.
551  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
552       E = CatImplDecl->instmeth_end(); I != E; ++I)
553    InsMap.insert((*I)->getSelector());
554
555  bool IncompleteImpl = false;
556  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
557       E = CatClassDecl->instmeth_end(); I != E; ++I)
558    if (!InsMap.count((*I)->getSelector()))
559      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
560
561  llvm::DenseSet<Selector> ClsMap;
562  // Check and see if class methods in category interface have been
563  // implemented in its implementation class.
564  for (ObjCCategoryImplDecl::classmeth_iterator
565       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
566       I != E; ++I)
567    ClsMap.insert((*I)->getSelector());
568
569  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
570       E = CatClassDecl->classmeth_end(); I != E; ++I)
571    if (!ClsMap.count((*I)->getSelector()))
572      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
573
574  // Check the protocol list for unimplemented methods in the @implementation
575  // class.
576  ObjCProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
577  for (unsigned i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
578    ObjCProtocolDecl* PDecl = protocols[i];
579    CheckProtocolMethodDefs(CatImplDecl->getLocation(), PDecl, IncompleteImpl,
580                            InsMap, ClsMap);
581  }
582}
583
584/// ActOnForwardClassDeclaration -
585Action::DeclTy *
586Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
587                                   IdentifierInfo **IdentList, unsigned NumElts)
588{
589  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
590
591  for (unsigned i = 0; i != NumElts; ++i) {
592    // Check for another declaration kind with the same name.
593    ScopedDecl *PrevDecl = LookupInterfaceDecl(IdentList[i]);
594    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
595      Diag(AtClassLoc, diag::err_redefinition_different_kind,
596           IdentList[i]->getName());
597      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
598    }
599    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
600    if (!IDecl) {  // Not already seen?  Make a forward decl.
601      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, 0, IdentList[i],
602                                        true);
603      // Chain & install the interface decl into the identifier.
604      IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
605      IdentList[i]->setFETokenInfo(IDecl);
606
607      // Remember that this needs to be removed when the scope is popped.
608      TUScope->AddDecl(IDecl);
609    }
610
611    Interfaces.push_back(IDecl);
612  }
613
614  return ObjCClassDecl::Create(Context, AtClassLoc,
615                               &Interfaces[0], Interfaces.size());
616}
617
618
619/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
620/// returns true, or false, accordingly.
621/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
622bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
623                                      const ObjCMethodDecl *PrevMethod) {
624  if (Method->getResultType().getCanonicalType() !=
625      PrevMethod->getResultType().getCanonicalType())
626    return false;
627  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
628    ParmVarDecl *ParamDecl = Method->getParamDecl(i);
629    ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
630    if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
631      return false;
632  }
633  return true;
634}
635
636void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
637  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
638  if (!FirstMethod.Method) {
639    // Haven't seen a method with this selector name yet - add it.
640    FirstMethod.Method = Method;
641    FirstMethod.Next = 0;
642  } else {
643    // We've seen a method with this name, now check the type signature(s).
644    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
645
646    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
647         Next = Next->Next)
648      match = MatchTwoMethodDeclarations(Method, Next->Method);
649
650    if (!match) {
651      // We have a new signature for an existing method - add it.
652      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
653      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
654      FirstMethod.Next = OMI;
655    }
656  }
657}
658
659void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
660  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
661  if (!FirstMethod.Method) {
662    // Haven't seen a method with this selector name yet - add it.
663    FirstMethod.Method = Method;
664    FirstMethod.Next = 0;
665  } else {
666    // We've seen a method with this name, now check the type signature(s).
667    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
668
669    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
670         Next = Next->Next)
671      match = MatchTwoMethodDeclarations(Method, Next->Method);
672
673    if (!match) {
674      // We have a new signature for an existing method - add it.
675      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
676      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
677      FirstMethod.Next = OMI;
678    }
679  }
680}
681
682// Note: For class/category implemenations, allMethods/allProperties is
683// always null.
684void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
685                      DeclTy **allMethods, unsigned allNum,
686                      DeclTy **allProperties, unsigned pNum) {
687  Decl *ClassDecl = static_cast<Decl *>(classDecl);
688
689  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
690  // always passing in a decl. If the decl has an error, isInvalidDecl()
691  // should be true.
692  if (!ClassDecl)
693    return;
694
695  llvm::SmallVector<ObjCMethodDecl*, 32> insMethods;
696  llvm::SmallVector<ObjCMethodDecl*, 16> clsMethods;
697
698  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
699  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
700
701  bool isInterfaceDeclKind =
702        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
703         || isa<ObjCProtocolDecl>(ClassDecl);
704  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
705
706  // TODO: property declaration in category and protocols.
707  if (pNum != 0)
708    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl))
709      IDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
710
711  for (unsigned i = 0; i < allNum; i++ ) {
712    ObjCMethodDecl *Method =
713      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
714
715    if (!Method) continue;  // Already issued a diagnostic.
716    if (Method->isInstance()) {
717      /// Check for instance method of the same name with incompatible types
718      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
719      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
720                              : false;
721      if (isInterfaceDeclKind && PrevMethod && !match
722          || checkIdenticalMethods && match) {
723          Diag(Method->getLocation(), diag::error_duplicate_method_decl,
724               Method->getSelector().getName());
725          Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
726      } else {
727        insMethods.push_back(Method);
728        InsMap[Method->getSelector()] = Method;
729        /// The following allows us to typecheck messages to "id".
730        AddInstanceMethodToGlobalPool(Method);
731      }
732    }
733    else {
734      /// Check for class method of the same name with incompatible types
735      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
736      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
737                              : false;
738      if (isInterfaceDeclKind && PrevMethod && !match
739          || checkIdenticalMethods && match) {
740        Diag(Method->getLocation(), diag::error_duplicate_method_decl,
741             Method->getSelector().getName());
742        Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
743      } else {
744        clsMethods.push_back(Method);
745        ClsMap[Method->getSelector()] = Method;
746        /// The following allows us to typecheck messages to "Class".
747        AddFactoryMethodToGlobalPool(Method);
748      }
749    }
750  }
751
752  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
753    I->addMethods(&insMethods[0], insMethods.size(),
754                  &clsMethods[0], clsMethods.size(), AtEndLoc);
755  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
756    P->addMethods(&insMethods[0], insMethods.size(),
757                  &clsMethods[0], clsMethods.size(), AtEndLoc);
758  }
759  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
760    C->addMethods(&insMethods[0], insMethods.size(),
761                  &clsMethods[0], clsMethods.size(), AtEndLoc);
762  }
763  else if (ObjCImplementationDecl *IC =
764                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
765    IC->setLocEnd(AtEndLoc);
766    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
767      ImplMethodsVsClassMethods(IC, IDecl);
768  } else {
769    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
770    CatImplClass->setLocEnd(AtEndLoc);
771    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
772    // Find category interface decl and then check that all methods declared
773    // in this interface is implemented in the category @implementation.
774    if (IDecl) {
775      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
776           Categories; Categories = Categories->getNextClassCategory()) {
777        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
778          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
779          break;
780        }
781      }
782    }
783  }
784}
785
786
787/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
788/// objective-c's type qualifier from the parser version of the same info.
789static Decl::ObjCDeclQualifier
790CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
791  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
792  if (PQTVal & ObjCDeclSpec::DQ_In)
793    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
794  if (PQTVal & ObjCDeclSpec::DQ_Inout)
795    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
796  if (PQTVal & ObjCDeclSpec::DQ_Out)
797    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
798  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
799    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
800  if (PQTVal & ObjCDeclSpec::DQ_Byref)
801    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
802  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
803    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
804
805  return ret;
806}
807
808Sema::DeclTy *Sema::ActOnMethodDeclaration(
809    SourceLocation MethodLoc, SourceLocation EndLoc,
810    tok::TokenKind MethodType, DeclTy *classDecl,
811    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
812    Selector Sel,
813    // optional arguments. The number of types/arguments is obtained
814    // from the Sel.getNumArgs().
815    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
816    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
817    bool isVariadic) {
818  Decl *ClassDecl = static_cast<Decl*>(classDecl);
819
820  // Make sure we can establish a context for the method.
821  if (!ClassDecl) {
822    Diag(MethodLoc, diag::error_missing_method_context);
823    return 0;
824  }
825  llvm::SmallVector<ParmVarDecl*, 16> Params;
826
827  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
828    // FIXME: arg->AttrList must be stored too!
829    QualType argType;
830
831    if (ArgTypes[i])
832      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
833    else
834      argType = Context.getObjCIdType();
835    ParmVarDecl* Param = ParmVarDecl::Create(Context, SourceLocation(/*FIXME*/),
836                                             ArgNames[i], argType,
837                                             VarDecl::None, 0);
838    Param->setObjCDeclQualifier(
839      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
840    Params.push_back(Param);
841  }
842  QualType resultDeclType;
843
844  if (ReturnType)
845    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
846  else // get the type for "id".
847    resultDeclType = Context.getObjCIdType();
848
849  ObjCMethodDecl* ObjCMethod =
850    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
851                           ClassDecl, AttrList,
852                           MethodType == tok::minus, isVariadic,
853                           MethodDeclKind == tok::objc_optional ?
854                           ObjCMethodDecl::Optional :
855                           ObjCMethodDecl::Required);
856
857  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
858  ObjCMethod->setObjCDeclQualifier(
859    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
860  const ObjCMethodDecl *PrevMethod = 0;
861
862  // For implementations (which can be very "coarse grain"), we add the
863  // method now. This allows the AST to implement lookup methods that work
864  // incrementally (without waiting until we parse the @end). It also allows
865  // us to flag multiple declaration errors as they occur.
866  if (ObjCImplementationDecl *ImpDecl =
867        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
868    if (MethodType == tok::minus) {
869      PrevMethod = ImpDecl->getInstanceMethod(Sel);
870      ImpDecl->addInstanceMethod(ObjCMethod);
871    } else {
872      PrevMethod = ImpDecl->getClassMethod(Sel);
873      ImpDecl->addClassMethod(ObjCMethod);
874    }
875  }
876  else if (ObjCCategoryImplDecl *CatImpDecl =
877            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
878    if (MethodType == tok::minus) {
879      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
880      CatImpDecl->addInstanceMethod(ObjCMethod);
881    } else {
882      PrevMethod = CatImpDecl->getClassMethod(Sel);
883      CatImpDecl->addClassMethod(ObjCMethod);
884    }
885  }
886  if (PrevMethod) {
887    // You can never have two method definitions with the same name.
888    Diag(ObjCMethod->getLocation(), diag::error_duplicate_method_decl,
889        ObjCMethod->getSelector().getName());
890    Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
891  }
892  return ObjCMethod;
893}
894
895Sema::DeclTy *Sema::ActOnAddObjCProperties(SourceLocation AtLoc,
896                                           DeclTy **allProperties,
897                                           unsigned NumProperties,
898                                           ObjCDeclSpec &DS) {
899  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, AtLoc);
900
901  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readonly)
902    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
903
904  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_getter) {
905    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
906    PDecl->setGetterName(DS.getGetterName());
907  }
908
909  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_setter) {
910    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
911    PDecl->setSetterName(DS.getSetterName());
912  }
913
914  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_assign)
915    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
916
917  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readwrite)
918    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
919
920  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_retain)
921    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
922
923  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_copy)
924    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
925
926  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nonatomic)
927    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
928
929  if (NumProperties != 0)
930    PDecl->setPropertyDeclLists((ObjCIvarDecl**)allProperties, NumProperties);
931
932  return PDecl;
933}
934
935