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