SemaDeclObjC.cpp revision e57c21a9247ac0755b4464c522c8d9f1db39bb1f
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  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, ClassLoc,TUScope);
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 = LookupDecl(SuperName, Decl::IDNS_Ordinary, SuperLoc, TUScope);
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(SourceLocation AtLoc,
156                                           IdentifierInfo *AliasName,
157                                           SourceLocation AliasLocation,
158                                           IdentifierInfo *ClassName,
159                                           SourceLocation ClassLocation) {
160  // Look for previous declaration of alias name
161  Decl *ADecl = LookupDecl(AliasName, Decl::IDNS_Ordinary,
162                           AliasLocation, TUScope);
163  if (ADecl) {
164    if (isa<ObjCCompatibleAliasDecl>(ADecl)) {
165      Diag(AliasLocation, diag::warn_previous_alias_decl);
166      Diag(ADecl->getLocation(), diag::warn_previous_declaration);
167    }
168    else {
169      Diag(AliasLocation, diag::err_conflicting_aliasing_type,
170           AliasName->getName());
171      Diag(ADecl->getLocation(), diag::err_previous_declaration);
172    }
173    return 0;
174  }
175  // Check for class declaration
176  Decl *CDeclU = LookupDecl(ClassName, Decl::IDNS_Ordinary,
177                            ClassLocation, TUScope);
178  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
179  if (CDecl == 0) {
180    Diag(ClassLocation, diag::warn_undef_interface, ClassName->getName());
181    if (CDeclU)
182      Diag(CDeclU->getLocation(), diag::warn_previous_declaration);
183    return 0;
184  }
185
186  // Everything checked out, instantiate a new alias declaration AST.
187  ObjCCompatibleAliasDecl *AliasDecl =
188    ObjCCompatibleAliasDecl::Create(Context, AtLoc, AliasName, CDecl);
189
190  ObjCAliasDecls[AliasName] = AliasDecl;
191  TUScope->AddDecl(AliasDecl);
192  return AliasDecl;
193}
194
195Sema::DeclTy *Sema::ActOnStartProtocolInterface(
196                SourceLocation AtProtoInterfaceLoc,
197                IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
198                IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
199                SourceLocation EndProtoLoc) {
200  assert(ProtocolName && "Missing protocol identifier");
201  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
202  if (PDecl) {
203    // Protocol already seen. Better be a forward protocol declaration
204    if (!PDecl->isForwardDecl()) {
205      Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
206           ProtocolName->getName());
207      // Just return the protocol we already had.
208      // FIXME: don't leak the objects passed in!
209      return PDecl;
210    }
211
212    PDecl->setForwardDecl(false);
213    PDecl->AllocReferencedProtocols(NumProtoRefs);
214  } else {
215    PDecl = ObjCProtocolDecl::Create(Context, AtProtoInterfaceLoc, NumProtoRefs,
216                                     ProtocolName);
217    PDecl->setForwardDecl(false);
218    ObjCProtocols[ProtocolName] = PDecl;
219  }
220
221  if (NumProtoRefs) {
222    /// Check then save referenced protocols.
223    for (unsigned int i = 0; i != NumProtoRefs; i++) {
224      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtoRefNames[i]];
225      if (!RefPDecl || RefPDecl->isForwardDecl())
226        Diag(ProtocolLoc, diag::warn_undef_protocolref,
227             ProtoRefNames[i]->getName(),
228             ProtocolName->getName());
229      PDecl->setReferencedProtocols(i, RefPDecl);
230    }
231    PDecl->setLocEnd(EndProtoLoc);
232  }
233  return PDecl;
234}
235
236/// FindProtocolDeclaration - This routine looks up protocols and
237/// issuer error if they are not declared. It returns list of protocol
238/// declarations in its 'Protocols' argument.
239void
240Sema::FindProtocolDeclaration(SourceLocation TypeLoc,
241                              IdentifierInfo **ProtocolId,
242                              unsigned NumProtocols,
243                              llvm::SmallVector<DeclTy *,8> &Protocols) {
244  for (unsigned i = 0; i != NumProtocols; ++i) {
245    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i]];
246    if (!PDecl)
247      Diag(TypeLoc, diag::err_undeclared_protocol,
248           ProtocolId[i]->getName());
249    else
250      Protocols.push_back(PDecl);
251  }
252}
253
254/// ActOnForwardProtocolDeclaration -
255Action::DeclTy *
256Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
257        IdentifierInfo **IdentList, unsigned NumElts) {
258  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
259
260  for (unsigned i = 0; i != NumElts; ++i) {
261    IdentifierInfo *Ident = IdentList[i];
262    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
263    if (PDecl == 0)  { // Not already seen?
264      // FIXME: Pass in the location of the identifier!
265      PDecl = ObjCProtocolDecl::Create(Context, AtProtocolLoc, 0, Ident);
266    }
267
268    Protocols.push_back(PDecl);
269  }
270  return ObjCForwardProtocolDecl::Create(Context, AtProtocolLoc,
271                                         &Protocols[0], Protocols.size());
272}
273
274Sema::DeclTy *Sema::ActOnStartCategoryInterface(
275                      SourceLocation AtInterfaceLoc,
276                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
277                      IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
278                      IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs,
279                      SourceLocation EndProtoLoc) {
280  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
281
282  ObjCCategoryDecl *CDecl =
283    ObjCCategoryDecl::Create(Context, AtInterfaceLoc, CategoryName);
284  CDecl->setClassInterface(IDecl);
285
286  /// Check that class of this category is already completely declared.
287  if (!IDecl || IDecl->isForwardDecl())
288    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
289  else {
290    /// Check for duplicate interface declaration for this category
291    ObjCCategoryDecl *CDeclChain;
292    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
293         CDeclChain = CDeclChain->getNextClassCategory()) {
294      if (CDeclChain->getIdentifier() == CategoryName) {
295        Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
296             CategoryName->getName());
297        break;
298      }
299    }
300  if (!CDeclChain)
301    CDecl->insertNextClassCategory();
302  }
303
304  if (NumProtoRefs) {
305    llvm::SmallVector<ObjCProtocolDecl*, 32> RefProtocols;
306    /// Check and then save the referenced protocols.
307    for (unsigned int i = 0; i != NumProtoRefs; i++) {
308      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtoRefNames[i]];
309      if (!RefPDecl || RefPDecl->isForwardDecl()) {
310        Diag(CategoryLoc, diag::warn_undef_protocolref,
311             ProtoRefNames[i]->getName(),
312             CategoryName->getName());
313      }
314      if (RefPDecl)
315        RefProtocols.push_back(RefPDecl);
316    }
317    if (!RefProtocols.empty())
318      CDecl->setReferencedProtocolList(&RefProtocols[0], RefProtocols.size());
319  }
320  CDecl->setLocEnd(EndProtoLoc);
321  return CDecl;
322}
323
324/// ActOnStartCategoryImplementation - Perform semantic checks on the
325/// category implementation declaration and build an ObjCCategoryImplDecl
326/// object.
327Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
328                      SourceLocation AtCatImplLoc,
329                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
330                      IdentifierInfo *CatName, SourceLocation CatLoc) {
331  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
332  ObjCCategoryImplDecl *CDecl =
333    ObjCCategoryImplDecl::Create(Context, AtCatImplLoc, CatName, IDecl);
334  /// Check that class of this category is already completely declared.
335  if (!IDecl || IDecl->isForwardDecl())
336    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
337
338  /// TODO: Check that CatName, category name, is not used in another
339  // implementation.
340  return CDecl;
341}
342
343Sema::DeclTy *Sema::ActOnStartClassImplementation(
344                      SourceLocation AtClassImplLoc,
345                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
346                      IdentifierInfo *SuperClassname,
347                      SourceLocation SuperClassLoc) {
348  ObjCInterfaceDecl* IDecl = 0;
349  // Check for another declaration kind with the same name.
350  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, ClassLoc,TUScope);
351  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
352    Diag(ClassLoc, diag::err_redefinition_different_kind,
353         ClassName->getName());
354    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
355  }
356  else {
357    // Is there an interface declaration of this class; if not, warn!
358    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
359    if (!IDecl)
360      Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
361  }
362
363  // Check that super class name is valid class name
364  ObjCInterfaceDecl* SDecl = 0;
365  if (SuperClassname) {
366    // Check if a different kind of symbol declared in this scope.
367    PrevDecl = LookupDecl(SuperClassname, Decl::IDNS_Ordinary,
368                          SuperClassLoc, TUScope);
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    Decl *PrevDecl = LookupDecl(IdentList[i], Decl::IDNS_Ordinary,
594                                AtClassLoc, TUScope);
595    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
596      Diag(AtClassLoc, diag::err_redefinition_different_kind,
597           IdentList[i]->getName());
598      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
599    }
600    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
601    if (!IDecl) {  // Not already seen?  Make a forward decl.
602      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, 0, IdentList[i],
603                                        true);
604      // Chain & install the interface decl into the identifier.
605      IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
606      IdentList[i]->setFETokenInfo(IDecl);
607
608      // Remember that this needs to be removed when the scope is popped.
609      TUScope->AddDecl(IDecl);
610    }
611
612    Interfaces.push_back(IDecl);
613  }
614
615  return ObjCClassDecl::Create(Context, AtClassLoc,
616                               &Interfaces[0], Interfaces.size());
617}
618
619
620/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
621/// returns true, or false, accordingly.
622/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
623bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
624                                      const ObjCMethodDecl *PrevMethod) {
625  if (Method->getResultType().getCanonicalType() !=
626      PrevMethod->getResultType().getCanonicalType())
627    return false;
628  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
629    ParmVarDecl *ParamDecl = Method->getParamDecl(i);
630    ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
631    if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
632      return false;
633  }
634  return true;
635}
636
637void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
638  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
639  if (!FirstMethod.Method) {
640    // Haven't seen a method with this selector name yet - add it.
641    FirstMethod.Method = Method;
642    FirstMethod.Next = 0;
643  } else {
644    // We've seen a method with this name, now check the type signature(s).
645    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
646
647    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
648         Next = Next->Next)
649      match = MatchTwoMethodDeclarations(Method, Next->Method);
650
651    if (!match) {
652      // We have a new signature for an existing method - add it.
653      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
654      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
655      FirstMethod.Next = OMI;
656    }
657  }
658}
659
660void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
661  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
662  if (!FirstMethod.Method) {
663    // Haven't seen a method with this selector name yet - add it.
664    FirstMethod.Method = Method;
665    FirstMethod.Next = 0;
666  } else {
667    // We've seen a method with this name, now check the type signature(s).
668    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
669
670    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
671         Next = Next->Next)
672      match = MatchTwoMethodDeclarations(Method, Next->Method);
673
674    if (!match) {
675      // We have a new signature for an existing method - add it.
676      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
677      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
678      FirstMethod.Next = OMI;
679    }
680  }
681}
682
683// Note: For class/category implemenations, allMethods/allProperties is
684// always null.
685void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
686                      DeclTy **allMethods, unsigned allNum,
687                      DeclTy **allProperties, unsigned pNum) {
688  Decl *ClassDecl = static_cast<Decl *>(classDecl);
689
690  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
691  // always passing in a decl. If the decl has an error, isInvalidDecl()
692  // should be true.
693  if (!ClassDecl)
694    return;
695
696  llvm::SmallVector<ObjCMethodDecl*, 32> insMethods;
697  llvm::SmallVector<ObjCMethodDecl*, 16> clsMethods;
698
699  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
700  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
701
702  bool isInterfaceDeclKind =
703        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
704         || isa<ObjCProtocolDecl>(ClassDecl);
705  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
706
707  // TODO: property declaration in category and protocols.
708  if (pNum != 0)
709    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl))
710      IDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
711
712  for (unsigned i = 0; i < allNum; i++ ) {
713    ObjCMethodDecl *Method =
714      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
715
716    if (!Method) continue;  // Already issued a diagnostic.
717    if (Method->isInstance()) {
718      /// Check for instance method of the same name with incompatible types
719      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
720      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
721                              : false;
722      if (isInterfaceDeclKind && PrevMethod && !match
723          || checkIdenticalMethods && match) {
724          Diag(Method->getLocation(), diag::error_duplicate_method_decl,
725               Method->getSelector().getName());
726          Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
727      } else {
728        insMethods.push_back(Method);
729        InsMap[Method->getSelector()] = Method;
730        /// The following allows us to typecheck messages to "id".
731        AddInstanceMethodToGlobalPool(Method);
732      }
733    }
734    else {
735      /// Check for class method of the same name with incompatible types
736      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
737      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
738                              : false;
739      if (isInterfaceDeclKind && PrevMethod && !match
740          || checkIdenticalMethods && match) {
741        Diag(Method->getLocation(), diag::error_duplicate_method_decl,
742             Method->getSelector().getName());
743        Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
744      } else {
745        clsMethods.push_back(Method);
746        ClsMap[Method->getSelector()] = Method;
747        /// The following allows us to typecheck messages to "Class".
748        AddFactoryMethodToGlobalPool(Method);
749      }
750    }
751  }
752
753  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
754    I->addMethods(&insMethods[0], insMethods.size(),
755                  &clsMethods[0], clsMethods.size(), AtEndLoc);
756  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
757    P->addMethods(&insMethods[0], insMethods.size(),
758                  &clsMethods[0], clsMethods.size(), AtEndLoc);
759  }
760  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
761    C->addMethods(&insMethods[0], insMethods.size(),
762                  &clsMethods[0], clsMethods.size(), AtEndLoc);
763  }
764  else if (ObjCImplementationDecl *IC =
765                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
766    IC->setLocEnd(AtEndLoc);
767    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
768      ImplMethodsVsClassMethods(IC, IDecl);
769  } else {
770    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
771    CatImplClass->setLocEnd(AtEndLoc);
772    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
773    // Find category interface decl and then check that all methods declared
774    // in this interface is implemented in the category @implementation.
775    if (IDecl) {
776      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
777           Categories; Categories = Categories->getNextClassCategory()) {
778        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
779          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
780          break;
781        }
782      }
783    }
784  }
785}
786
787
788/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
789/// objective-c's type qualifier from the parser version of the same info.
790static Decl::ObjCDeclQualifier
791CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
792  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
793  if (PQTVal & ObjCDeclSpec::DQ_In)
794    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
795  if (PQTVal & ObjCDeclSpec::DQ_Inout)
796    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
797  if (PQTVal & ObjCDeclSpec::DQ_Out)
798    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
799  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
800    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
801  if (PQTVal & ObjCDeclSpec::DQ_Byref)
802    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
803  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
804    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
805
806  return ret;
807}
808
809Sema::DeclTy *Sema::ActOnMethodDeclaration(
810    SourceLocation MethodLoc, SourceLocation EndLoc,
811    tok::TokenKind MethodType, DeclTy *classDecl,
812    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
813    Selector Sel,
814    // optional arguments. The number of types/arguments is obtained
815    // from the Sel.getNumArgs().
816    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
817    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
818    bool isVariadic) {
819  Decl *ClassDecl = static_cast<Decl*>(classDecl);
820
821  // Make sure we can establish a context for the method.
822  if (!ClassDecl) {
823    Diag(MethodLoc, diag::error_missing_method_context);
824    return 0;
825  }
826  llvm::SmallVector<ParmVarDecl*, 16> Params;
827
828  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
829    // FIXME: arg->AttrList must be stored too!
830    QualType argType;
831
832    if (ArgTypes[i])
833      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
834    else
835      argType = Context.getObjCIdType();
836    ParmVarDecl* Param = ParmVarDecl::Create(Context, SourceLocation(/*FIXME*/),
837                                             ArgNames[i], argType,
838                                             VarDecl::None, 0);
839    Param->setObjCDeclQualifier(
840      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
841    Params.push_back(Param);
842  }
843  QualType resultDeclType;
844
845  if (ReturnType)
846    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
847  else // get the type for "id".
848    resultDeclType = Context.getObjCIdType();
849
850  ObjCMethodDecl* ObjCMethod =
851    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
852                           ClassDecl, AttrList,
853                           MethodType == tok::minus, isVariadic,
854                           MethodDeclKind == tok::objc_optional ?
855                           ObjCMethodDecl::Optional :
856                           ObjCMethodDecl::Required);
857
858  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
859  ObjCMethod->setObjCDeclQualifier(
860    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
861  const ObjCMethodDecl *PrevMethod = 0;
862
863  // For implementations (which can be very "coarse grain"), we add the
864  // method now. This allows the AST to implement lookup methods that work
865  // incrementally (without waiting until we parse the @end). It also allows
866  // us to flag multiple declaration errors as they occur.
867  if (ObjCImplementationDecl *ImpDecl =
868        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
869    if (MethodType == tok::minus) {
870      PrevMethod = ImpDecl->getInstanceMethod(Sel);
871      ImpDecl->addInstanceMethod(ObjCMethod);
872    } else {
873      PrevMethod = ImpDecl->getClassMethod(Sel);
874      ImpDecl->addClassMethod(ObjCMethod);
875    }
876  }
877  else if (ObjCCategoryImplDecl *CatImpDecl =
878            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
879    if (MethodType == tok::minus) {
880      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
881      CatImpDecl->addInstanceMethod(ObjCMethod);
882    } else {
883      PrevMethod = CatImpDecl->getClassMethod(Sel);
884      CatImpDecl->addClassMethod(ObjCMethod);
885    }
886  }
887  if (PrevMethod) {
888    // You can never have two method definitions with the same name.
889    Diag(ObjCMethod->getLocation(), diag::error_duplicate_method_decl,
890        ObjCMethod->getSelector().getName());
891    Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
892  }
893  return ObjCMethod;
894}
895
896Sema::DeclTy *Sema::ActOnAddObjCProperties(SourceLocation AtLoc,
897                                           DeclTy **allProperties,
898                                           unsigned NumProperties,
899                                           ObjCDeclSpec &DS) {
900  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, AtLoc);
901
902  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readonly)
903    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
904
905  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_getter) {
906    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
907    PDecl->setGetterName(DS.getGetterName());
908  }
909
910  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_setter) {
911    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
912    PDecl->setSetterName(DS.getSetterName());
913  }
914
915  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_assign)
916    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
917
918  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readwrite)
919    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
920
921  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_retain)
922    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
923
924  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_copy)
925    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
926
927  if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nonatomic)
928    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
929
930  if (NumProperties != 0)
931    PDecl->setPropertyDeclLists((ObjCIvarDecl**)allProperties, NumProperties);
932
933  return PDecl;
934}
935
936