SemaDeclObjC.cpp revision e26cb43f48421366ffc0d3c28b8e703a010f1089
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(FnBodyScope, 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, MDecl->getClassInterface());
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 && PrevDecl->isTemplateParameter()) {
70    // Maybe we will complain about the shadowed template parameter.
71    DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
72    // Just pretend that we didn't see the previous declaration.
73    PrevDecl = 0;
74  }
75
76  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
77    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
78    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
79  }
80
81  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
82  if (IDecl) {
83    // Class already seen. Is it a forward declaration?
84    if (!IDecl->isForwardDecl()) {
85      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
86      Diag(IDecl->getLocation(), diag::note_previous_definition);
87
88      // Return the previous class interface.
89      // FIXME: don't leak the objects passed in!
90      return IDecl;
91    } else {
92      IDecl->setLocation(AtInterfaceLoc);
93      IDecl->setForwardDecl(false);
94    }
95  } else {
96    IDecl = ObjCInterfaceDecl::Create(Context, AtInterfaceLoc,
97                                      ClassName, ClassLoc);
98    if (AttrList)
99      ProcessDeclAttributeList(IDecl, AttrList);
100
101    ObjCInterfaceDecls[ClassName] = IDecl;
102    // Remember that this needs to be removed when the scope is popped.
103    TUScope->AddDecl(IDecl);
104  }
105
106  if (SuperName) {
107    ObjCInterfaceDecl* SuperClassEntry = 0;
108    // Check if a different kind of symbol declared in this scope.
109    PrevDecl = LookupDecl(SuperName, Decl::IDNS_Ordinary, TUScope);
110    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
111      Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
112      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
113    }
114    else {
115      // Check that super class is previously defined
116      SuperClassEntry = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
117
118      if (!SuperClassEntry)
119        Diag(SuperLoc, diag::err_undef_superclass)
120          << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
121      else if (SuperClassEntry->isForwardDecl())
122        Diag(SuperLoc, diag::err_undef_superclass)
123          << SuperClassEntry->getDeclName() << ClassName
124          << SourceRange(AtInterfaceLoc, ClassLoc);
125    }
126    IDecl->setSuperClass(SuperClassEntry);
127    IDecl->setSuperClassLoc(SuperLoc);
128    IDecl->setLocEnd(SuperLoc);
129  } else { // we have a root class.
130    IDecl->setLocEnd(ClassLoc);
131  }
132
133  /// Check then save referenced protocols.
134  if (NumProtoRefs) {
135    IDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
136    IDecl->setLocEnd(EndProtoLoc);
137  }
138
139  CheckObjCDeclScope(IDecl);
140  return IDecl;
141}
142
143/// ActOnCompatiblityAlias - this action is called after complete parsing of
144/// @compatibility_alias declaration. It sets up the alias relationships.
145Sema::DeclTy *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
146                                           IdentifierInfo *AliasName,
147                                           SourceLocation AliasLocation,
148                                           IdentifierInfo *ClassName,
149                                           SourceLocation ClassLocation) {
150  // Look for previous declaration of alias name
151  Decl *ADecl = LookupDecl(AliasName, Decl::IDNS_Ordinary, TUScope);
152  if (ADecl) {
153    if (isa<ObjCCompatibleAliasDecl>(ADecl))
154      Diag(AliasLocation, diag::warn_previous_alias_decl);
155    else
156      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
157    Diag(ADecl->getLocation(), diag::note_previous_declaration);
158    return 0;
159  }
160  // Check for class declaration
161  Decl *CDeclU = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
162  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
163  if (CDecl == 0) {
164    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
165    if (CDeclU)
166      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
167    return 0;
168  }
169
170  // Everything checked out, instantiate a new alias declaration AST.
171  ObjCCompatibleAliasDecl *AliasDecl =
172    ObjCCompatibleAliasDecl::Create(Context, AtLoc, AliasName, CDecl);
173
174  ObjCAliasDecls[AliasName] = AliasDecl;
175
176  if (!CheckObjCDeclScope(AliasDecl))
177    TUScope->AddDecl(AliasDecl);
178
179  return AliasDecl;
180}
181
182Sema::DeclTy *
183Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
184                                  IdentifierInfo *ProtocolName,
185                                  SourceLocation ProtocolLoc,
186                                  DeclTy * const *ProtoRefs,
187                                  unsigned NumProtoRefs,
188                                  SourceLocation EndProtoLoc,
189                                  AttributeList *AttrList) {
190  // FIXME: Deal with AttrList.
191  assert(ProtocolName && "Missing protocol identifier");
192  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
193  if (PDecl) {
194    // Protocol already seen. Better be a forward protocol declaration
195    if (!PDecl->isForwardDecl()) {
196      Diag(ProtocolLoc, diag::err_duplicate_protocol_def) << ProtocolName;
197      Diag(PDecl->getLocation(), diag::note_previous_definition);
198      // Just return the protocol we already had.
199      // FIXME: don't leak the objects passed in!
200      return PDecl;
201    }
202    // Make sure the cached decl gets a valid start location.
203    PDecl->setLocation(AtProtoInterfaceLoc);
204    PDecl->setForwardDecl(false);
205  } else {
206    PDecl = ObjCProtocolDecl::Create(Context, AtProtoInterfaceLoc,ProtocolName);
207    PDecl->setForwardDecl(false);
208    ObjCProtocols[ProtocolName] = PDecl;
209  }
210  if (AttrList)
211    ProcessDeclAttributeList(PDecl, AttrList);
212  if (NumProtoRefs) {
213    /// Check then save referenced protocols.
214    PDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
215    PDecl->setLocEnd(EndProtoLoc);
216  }
217
218  CheckObjCDeclScope(PDecl);
219  return PDecl;
220}
221
222/// FindProtocolDeclaration - This routine looks up protocols and
223/// issues an error if they are not declared. It returns list of
224/// protocol declarations in its 'Protocols' argument.
225void
226Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
227                              const IdentifierLocPair *ProtocolId,
228                              unsigned NumProtocols,
229                              llvm::SmallVectorImpl<DeclTy*> &Protocols) {
230  for (unsigned i = 0; i != NumProtocols; ++i) {
231    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
232    if (!PDecl) {
233      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
234        << ProtocolId[i].first;
235      continue;
236    }
237    for (const Attr *attr = PDecl->getAttrs(); attr; attr = attr->getNext()) {
238      if (attr->hasKind(Attr::Unavailable))
239        Diag(ProtocolId[i].second, diag::warn_unavailable) <<
240          PDecl->getDeclName();
241      if (attr->hasKind(Attr::Deprecated))
242        Diag(ProtocolId[i].second, diag::warn_deprecated) <<
243          PDecl->getDeclName();
244    }
245
246    // If this is a forward declaration and we are supposed to warn in this
247    // case, do it.
248    if (WarnOnDeclarations && PDecl->isForwardDecl())
249      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
250        << ProtocolId[i].first;
251    Protocols.push_back(PDecl);
252  }
253}
254
255/// DiagnosePropertyMismatch - Compares two properties for their
256/// attributes and types and warns on a variety of inconsistencies.
257///
258void
259Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
260                               ObjCPropertyDecl *SuperProperty,
261                               const IdentifierInfo *inheritedName) {
262  ObjCPropertyDecl::PropertyAttributeKind CAttr =
263  Property->getPropertyAttributes();
264  ObjCPropertyDecl::PropertyAttributeKind SAttr =
265  SuperProperty->getPropertyAttributes();
266  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
267      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
268    Diag(Property->getLocation(), diag::warn_readonly_property)
269      << Property->getDeclName() << inheritedName;
270  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
271      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
272    Diag(Property->getLocation(), diag::warn_property_attribute)
273      << Property->getDeclName() << "copy" << inheritedName;
274  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
275           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
276    Diag(Property->getLocation(), diag::warn_property_attribute)
277      << Property->getDeclName() << "retain" << inheritedName;
278
279  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
280      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
281    Diag(Property->getLocation(), diag::warn_property_attribute)
282      << Property->getDeclName() << "atomic" << inheritedName;
283  if (Property->getSetterName() != SuperProperty->getSetterName())
284    Diag(Property->getLocation(), diag::warn_property_attribute)
285      << Property->getDeclName() << "setter" << inheritedName;
286  if (Property->getGetterName() != SuperProperty->getGetterName())
287    Diag(Property->getLocation(), diag::warn_property_attribute)
288      << Property->getDeclName() << "getter" << inheritedName;
289
290  if (Context.getCanonicalType(Property->getType()) !=
291          Context.getCanonicalType(SuperProperty->getType()))
292    Diag(Property->getLocation(), diag::warn_property_type)
293      << Property->getType() << inheritedName;
294
295}
296
297/// ComparePropertiesInBaseAndSuper - This routine compares property
298/// declarations in base and its super class, if any, and issues
299/// diagnostics in a variety of inconsistant situations.
300///
301void
302Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
303  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
304  if (!SDecl)
305    return;
306  // FIXME: O(N^2)
307  for (ObjCInterfaceDecl::classprop_iterator S = SDecl->classprop_begin(),
308       E = SDecl->classprop_end(); S != E; ++S) {
309    ObjCPropertyDecl *SuperPDecl = (*S);
310    // Does property in super class has declaration in current class?
311    for (ObjCInterfaceDecl::classprop_iterator I = IDecl->classprop_begin(),
312         E = IDecl->classprop_end(); I != E; ++I) {
313      ObjCPropertyDecl *PDecl = (*I);
314      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
315          DiagnosePropertyMismatch(PDecl, SuperPDecl,
316                                   SDecl->getIdentifier());
317    }
318  }
319}
320
321/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
322/// of properties declared in a protocol and adds them to the list
323/// of properties for current class/category if it is not there already.
324void
325Sema::MergeOneProtocolPropertiesIntoClass(Decl *CDecl,
326                                          ObjCProtocolDecl *PDecl) {
327  llvm::SmallVector<ObjCPropertyDecl*, 16> mergeProperties;
328  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
329  if (!IDecl) {
330    // Category
331    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
332    assert (CatDecl && "MergeOneProtocolPropertiesIntoClass");
333    for (ObjCProtocolDecl::classprop_iterator P = PDecl->classprop_begin(),
334         E = PDecl->classprop_end(); P != E; ++P) {
335      ObjCPropertyDecl *Pr = (*P);
336      ObjCCategoryDecl::classprop_iterator CP, CE;
337      // Is this property already in  category's list of properties?
338      for (CP = CatDecl->classprop_begin(), CE = CatDecl->classprop_end();
339           CP != CE; ++CP)
340        if ((*CP)->getIdentifier() == Pr->getIdentifier())
341          break;
342      if (CP == CE)
343        // Add this property to list of properties for thie class.
344        mergeProperties.push_back(Pr);
345      else
346        // Property protocol already exist in class. Diagnose any mismatch.
347        DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
348    }
349    CatDecl->mergeProperties(&mergeProperties[0], mergeProperties.size());
350    return;
351  }
352  for (ObjCProtocolDecl::classprop_iterator P = PDecl->classprop_begin(),
353       E = PDecl->classprop_end(); P != E; ++P) {
354    ObjCPropertyDecl *Pr = (*P);
355    ObjCInterfaceDecl::classprop_iterator CP, CE;
356    // Is this property already in  class's list of properties?
357    for (CP = IDecl->classprop_begin(), CE = IDecl->classprop_end();
358         CP != CE; ++CP)
359      if ((*CP)->getIdentifier() == Pr->getIdentifier())
360        break;
361    if (CP == CE)
362      // Add this property to list of properties for thie class.
363      mergeProperties.push_back(Pr);
364    else
365      // Property protocol already exist in class. Diagnose any mismatch.
366      DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
367    }
368  IDecl->mergeProperties(&mergeProperties[0], mergeProperties.size());
369}
370
371/// MergeProtocolPropertiesIntoClass - This routine merges properties
372/// declared in 'MergeItsProtocols' objects (which can be a class or an
373/// inherited protocol into the list of properties for class/category 'CDecl'
374///
375
376void
377Sema::MergeProtocolPropertiesIntoClass(Decl *CDecl,
378                                       DeclTy *MergeItsProtocols) {
379  Decl *ClassDecl = static_cast<Decl *>(MergeItsProtocols);
380  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
381
382  if (!IDecl) {
383    // Category
384    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
385    assert (CatDecl && "MergeProtocolPropertiesIntoClass");
386    if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
387      for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
388           E = MDecl->protocol_end(); P != E; ++P)
389      // Merge properties of category (*P) into IDECL's
390      MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
391
392      // Go thru the list of protocols for this category and recursively merge
393      // their properties into this class as well.
394      for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
395           E = CatDecl->protocol_end(); P != E; ++P)
396        MergeProtocolPropertiesIntoClass(CatDecl, *P);
397    } else {
398      ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
399      for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
400           E = MD->protocol_end(); P != E; ++P)
401        MergeOneProtocolPropertiesIntoClass(CatDecl, (*P));
402    }
403    return;
404  }
405
406  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
407    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
408         E = MDecl->protocol_end(); P != E; ++P)
409      // Merge properties of class (*P) into IDECL's
410      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
411
412    // Go thru the list of protocols for this class and recursively merge
413    // their properties into this class as well.
414    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
415         E = IDecl->protocol_end(); P != E; ++P)
416      MergeProtocolPropertiesIntoClass(IDecl, *P);
417  } else {
418    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
419    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
420         E = MD->protocol_end(); P != E; ++P)
421      MergeOneProtocolPropertiesIntoClass(IDecl, (*P));
422  }
423}
424
425/// ActOnForwardProtocolDeclaration -
426Action::DeclTy *
427Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
428                                      const IdentifierLocPair *IdentList,
429                                      unsigned NumElts,
430                                      AttributeList *attrList) {
431  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
432
433  for (unsigned i = 0; i != NumElts; ++i) {
434    IdentifierInfo *Ident = IdentList[i].first;
435    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
436    if (PDecl == 0) // Not already seen?
437      PDecl = ObjCProtocolDecl::Create(Context, IdentList[i].second, Ident);
438    if (attrList)
439      ProcessDeclAttributeList(PDecl, attrList);
440    Protocols.push_back(PDecl);
441  }
442
443  ObjCForwardProtocolDecl *PDecl =
444    ObjCForwardProtocolDecl::Create(Context, AtProtocolLoc,
445                                    &Protocols[0], Protocols.size());
446
447  CheckObjCDeclScope(PDecl);
448  return PDecl;
449}
450
451Sema::DeclTy *Sema::
452ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
453                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
454                            IdentifierInfo *CategoryName,
455                            SourceLocation CategoryLoc,
456                            DeclTy * const *ProtoRefs,
457                            unsigned NumProtoRefs,
458                            SourceLocation EndProtoLoc) {
459  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
460
461  ObjCCategoryDecl *CDecl =
462    ObjCCategoryDecl::Create(Context, AtInterfaceLoc, CategoryName);
463  CDecl->setClassInterface(IDecl);
464
465  /// Check that class of this category is already completely declared.
466  if (!IDecl || IDecl->isForwardDecl())
467    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
468  else {
469    /// Check for duplicate interface declaration for this category
470    ObjCCategoryDecl *CDeclChain;
471    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
472         CDeclChain = CDeclChain->getNextClassCategory()) {
473      if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
474        Diag(CategoryLoc, diag::warn_dup_category_def)
475          << ClassName << CategoryName;
476        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
477        break;
478      }
479    }
480    if (!CDeclChain)
481      CDecl->insertNextClassCategory();
482  }
483
484  if (NumProtoRefs) {
485    CDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
486    CDecl->setLocEnd(EndProtoLoc);
487  }
488
489  CheckObjCDeclScope(CDecl);
490  return CDecl;
491}
492
493/// ActOnStartCategoryImplementation - Perform semantic checks on the
494/// category implementation declaration and build an ObjCCategoryImplDecl
495/// object.
496Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
497                      SourceLocation AtCatImplLoc,
498                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
499                      IdentifierInfo *CatName, SourceLocation CatLoc) {
500  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
501  ObjCCategoryImplDecl *CDecl =
502    ObjCCategoryImplDecl::Create(Context, AtCatImplLoc, CatName, IDecl);
503  /// Check that class of this category is already completely declared.
504  if (!IDecl || IDecl->isForwardDecl())
505    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
506
507  /// TODO: Check that CatName, category name, is not used in another
508  // implementation.
509  ObjCCategoryImpls.push_back(CDecl);
510
511  CheckObjCDeclScope(CDecl);
512  return CDecl;
513}
514
515Sema::DeclTy *Sema::ActOnStartClassImplementation(
516                      SourceLocation AtClassImplLoc,
517                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
518                      IdentifierInfo *SuperClassname,
519                      SourceLocation SuperClassLoc) {
520  ObjCInterfaceDecl* IDecl = 0;
521  // Check for another declaration kind with the same name.
522  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
523  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
524    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
525    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
526  }
527  else {
528    // Is there an interface declaration of this class; if not, warn!
529    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
530    if (!IDecl)
531      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
532  }
533
534  // Check that super class name is valid class name
535  ObjCInterfaceDecl* SDecl = 0;
536  if (SuperClassname) {
537    // Check if a different kind of symbol declared in this scope.
538    PrevDecl = LookupDecl(SuperClassname, Decl::IDNS_Ordinary, TUScope);
539    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
540      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
541        << SuperClassname;
542      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
543    } else {
544      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
545      if (!SDecl)
546        Diag(SuperClassLoc, diag::err_undef_superclass)
547          << SuperClassname << ClassName;
548      else if (IDecl && IDecl->getSuperClass() != SDecl) {
549        // This implementation and its interface do not have the same
550        // super class.
551        Diag(SuperClassLoc, diag::err_conflicting_super_class)
552          << SDecl->getDeclName();
553        Diag(SDecl->getLocation(), diag::note_previous_definition);
554      }
555    }
556  }
557
558  if (!IDecl) {
559    // Legacy case of @implementation with no corresponding @interface.
560    // Build, chain & install the interface decl into the identifier.
561
562    // FIXME: Do we support attributes on the @implementation? If so
563    // we should copy them over.
564    IDecl = ObjCInterfaceDecl::Create(Context, AtClassImplLoc, ClassName,
565                                      ClassLoc, false, true);
566    ObjCInterfaceDecls[ClassName] = IDecl;
567    IDecl->setSuperClass(SDecl);
568    IDecl->setLocEnd(ClassLoc);
569
570    // Remember that this needs to be removed when the scope is popped.
571    TUScope->AddDecl(IDecl);
572  }
573
574  ObjCImplementationDecl* IMPDecl =
575    ObjCImplementationDecl::Create(Context, AtClassImplLoc, ClassName,
576                                   IDecl, SDecl);
577
578  if (CheckObjCDeclScope(IMPDecl))
579    return IMPDecl;
580
581  // Check that there is no duplicate implementation of this class.
582  if (ObjCImplementations[ClassName])
583    // FIXME: Don't leak everything!
584    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
585  else // add it to the list.
586    ObjCImplementations[ClassName] = IMPDecl;
587  return IMPDecl;
588}
589
590void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
591                                    ObjCIvarDecl **ivars, unsigned numIvars,
592                                    SourceLocation RBrace) {
593  assert(ImpDecl && "missing implementation decl");
594  ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
595  if (!IDecl)
596    return;
597  /// Check case of non-existing @interface decl.
598  /// (legacy objective-c @implementation decl without an @interface decl).
599  /// Add implementations's ivar to the synthesize class's ivar list.
600  if (IDecl->ImplicitInterfaceDecl()) {
601    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
602    return;
603  }
604  // If implementation has empty ivar list, just return.
605  if (numIvars == 0)
606    return;
607
608  assert(ivars && "missing @implementation ivars");
609
610  // Check interface's Ivar list against those in the implementation.
611  // names and types must match.
612  //
613  unsigned j = 0;
614  ObjCInterfaceDecl::ivar_iterator
615    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
616  for (; numIvars > 0 && IVI != IVE; ++IVI) {
617    ObjCIvarDecl* ImplIvar = ivars[j++];
618    ObjCIvarDecl* ClsIvar = *IVI;
619    assert (ImplIvar && "missing implementation ivar");
620    assert (ClsIvar && "missing class ivar");
621    if (Context.getCanonicalType(ImplIvar->getType()) !=
622        Context.getCanonicalType(ClsIvar->getType())) {
623      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
624        << ImplIvar->getIdentifier()
625        << ImplIvar->getType() << ClsIvar->getType();
626      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
627    }
628    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
629    // as error.
630    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
631      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
632        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
633      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
634      return;
635    }
636    --numIvars;
637  }
638
639  if (numIvars > 0)
640    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
641  else if (IVI != IVE)
642    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
643}
644
645void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
646                               bool &IncompleteImpl) {
647  if (!IncompleteImpl) {
648    Diag(ImpLoc, diag::warn_incomplete_impl);
649    IncompleteImpl = true;
650  }
651  Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName();
652}
653
654void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
655                                       ObjCMethodDecl *IntfMethodDecl) {
656  bool err = false;
657  QualType ImpMethodQType =
658    Context.getCanonicalType(ImpMethodDecl->getResultType());
659  QualType IntfMethodQType =
660    Context.getCanonicalType(IntfMethodDecl->getResultType());
661  if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType))
662    err = true;
663  else for (ObjCMethodDecl::param_iterator IM=ImpMethodDecl->param_begin(),
664            IF=IntfMethodDecl->param_begin(),
665            EM=ImpMethodDecl->param_end(); IM!=EM; ++IM, IF++) {
666    ImpMethodQType = Context.getCanonicalType((*IM)->getType());
667    IntfMethodQType = Context.getCanonicalType((*IF)->getType());
668    if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType)) {
669      err = true;
670      break;
671    }
672  }
673  if (err) {
674    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_types)
675    << ImpMethodDecl->getDeclName();
676    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
677  }
678}
679
680/// FIXME: Type hierarchies in Objective-C can be deep. We could most
681/// likely improve the efficiency of selector lookups and type
682/// checking by associating with each protocol / interface / category
683/// the flattened instance tables. If we used an immutable set to keep
684/// the table then it wouldn't add significant memory cost and it
685/// would be handy for lookups.
686
687/// CheckProtocolMethodDefs - This routine checks unimplemented methods
688/// Declared in protocol, and those referenced by it.
689void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
690                                   ObjCProtocolDecl *PDecl,
691                                   bool& IncompleteImpl,
692                                   const llvm::DenseSet<Selector> &InsMap,
693                                   const llvm::DenseSet<Selector> &ClsMap,
694                                   ObjCInterfaceDecl *IDecl) {
695  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
696
697  // If a method lookup fails locally we still need to look and see if
698  // the method was implemented by a base class or an inherited
699  // protocol. This lookup is slow, but occurs rarely in correct code
700  // and otherwise would terminate in a warning.
701
702  // check unimplemented instance methods.
703  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
704       E = PDecl->instmeth_end(); I != E; ++I) {
705    ObjCMethodDecl *method = *I;
706    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
707        !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
708        (!Super || !Super->lookupInstanceMethod(method->getSelector())))
709      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
710  }
711  // check unimplemented class methods
712  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
713       E = PDecl->classmeth_end(); I != E; ++I) {
714    ObjCMethodDecl *method = *I;
715    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
716        !ClsMap.count(method->getSelector()) &&
717        (!Super || !Super->lookupClassMethod(method->getSelector())))
718      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
719  }
720  // Check on this protocols's referenced protocols, recursively.
721  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
722       E = PDecl->protocol_end(); PI != E; ++PI)
723    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
724}
725
726void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
727                                     ObjCInterfaceDecl* IDecl) {
728  llvm::DenseSet<Selector> InsMap;
729  // Check and see if instance methods in class interface have been
730  // implemented in the implementation class.
731  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
732       E = IMPDecl->instmeth_end(); I != E; ++I)
733    InsMap.insert((*I)->getSelector());
734
735  bool IncompleteImpl = false;
736  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
737       E = IDecl->instmeth_end(); I != E; ++I)
738    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector()))
739      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
740    else if (!(*I)->isSynthesized()){
741      ObjCMethodDecl *ImpMethodDecl =
742        IMPDecl->getInstanceMethod((*I)->getSelector());
743      ObjCMethodDecl *IntfMethodDecl =
744        IDecl->getInstanceMethod((*I)->getSelector());
745      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
746
747    }
748
749  llvm::DenseSet<Selector> ClsMap;
750  // Check and see if class methods in class interface have been
751  // implemented in the implementation class.
752  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
753       E = IMPDecl->classmeth_end(); I != E; ++I)
754    ClsMap.insert((*I)->getSelector());
755
756  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
757       E = IDecl->classmeth_end(); I != E; ++I)
758    if (!ClsMap.count((*I)->getSelector()))
759      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
760    else {
761      ObjCMethodDecl *ImpMethodDecl =
762        IMPDecl->getClassMethod((*I)->getSelector());
763      ObjCMethodDecl *IntfMethodDecl =
764        IDecl->getClassMethod((*I)->getSelector());
765      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
766    }
767
768
769  // Check the protocol list for unimplemented methods in the @implementation
770  // class.
771  const ObjCList<ObjCProtocolDecl> &Protocols =
772    IDecl->getReferencedProtocols();
773  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
774       E = Protocols.end(); I != E; ++I)
775    CheckProtocolMethodDefs(IMPDecl->getLocation(), *I,
776                            IncompleteImpl, InsMap, ClsMap, IDecl);
777}
778
779/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
780/// category interface are implemented in the category @implementation.
781void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
782                                            ObjCCategoryDecl *CatClassDecl) {
783  llvm::DenseSet<Selector> InsMap;
784  // Check and see if instance methods in category interface have been
785  // implemented in its implementation class.
786  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
787       E = CatImplDecl->instmeth_end(); I != E; ++I)
788    InsMap.insert((*I)->getSelector());
789
790  bool IncompleteImpl = false;
791  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
792       E = CatClassDecl->instmeth_end(); I != E; ++I)
793    if (!InsMap.count((*I)->getSelector()))
794      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
795    else {
796      ObjCMethodDecl *ImpMethodDecl =
797        CatImplDecl->getInstanceMethod((*I)->getSelector());
798      ObjCMethodDecl *IntfMethodDecl =
799        CatClassDecl->getInstanceMethod((*I)->getSelector());
800      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
801    }
802
803  llvm::DenseSet<Selector> ClsMap;
804  // Check and see if class methods in category interface have been
805  // implemented in its implementation class.
806  for (ObjCCategoryImplDecl::classmeth_iterator
807       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
808       I != E; ++I)
809    ClsMap.insert((*I)->getSelector());
810
811  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
812       E = CatClassDecl->classmeth_end(); I != E; ++I)
813    if (!ClsMap.count((*I)->getSelector()))
814      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
815    else {
816      ObjCMethodDecl *ImpMethodDecl =
817        CatImplDecl->getClassMethod((*I)->getSelector());
818      ObjCMethodDecl *IntfMethodDecl =
819        CatClassDecl->getClassMethod((*I)->getSelector());
820      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
821    }
822  // Check the protocol list for unimplemented methods in the @implementation
823  // class.
824  for (ObjCCategoryDecl::protocol_iterator PI = CatClassDecl->protocol_begin(),
825       E = CatClassDecl->protocol_end(); PI != E; ++PI)
826    CheckProtocolMethodDefs(CatImplDecl->getLocation(), *PI, IncompleteImpl,
827                            InsMap, ClsMap, CatClassDecl->getClassInterface());
828}
829
830/// ActOnForwardClassDeclaration -
831Action::DeclTy *
832Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
833                                   IdentifierInfo **IdentList, unsigned NumElts)
834{
835  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
836
837  for (unsigned i = 0; i != NumElts; ++i) {
838    // Check for another declaration kind with the same name.
839    Decl *PrevDecl = LookupDecl(IdentList[i], Decl::IDNS_Ordinary, TUScope);
840    if (PrevDecl && PrevDecl->isTemplateParameter()) {
841      // Maybe we will complain about the shadowed template parameter.
842      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
843      // Just pretend that we didn't see the previous declaration.
844      PrevDecl = 0;
845    }
846
847    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
848      // GCC apparently allows the following idiom:
849      //
850      // typedef NSObject < XCElementTogglerP > XCElementToggler;
851      // @class XCElementToggler;
852      //
853      // FIXME: Make an extension?
854      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
855      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
856        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
857        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
858      }
859    }
860    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
861    if (!IDecl) {  // Not already seen?  Make a forward decl.
862      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, IdentList[i],
863                                        SourceLocation(), true);
864      ObjCInterfaceDecls[IdentList[i]] = IDecl;
865
866      // Remember that this needs to be removed when the scope is popped.
867      TUScope->AddDecl(IDecl);
868    }
869
870    Interfaces.push_back(IDecl);
871  }
872
873  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, AtClassLoc,
874                                               &Interfaces[0],
875                                               Interfaces.size());
876
877  CheckObjCDeclScope(CDecl);
878  return CDecl;
879}
880
881
882/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
883/// returns true, or false, accordingly.
884/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
885bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
886                                      const ObjCMethodDecl *PrevMethod,
887                                      bool matchBasedOnSizeAndAlignment) {
888  QualType T1 = Context.getCanonicalType(Method->getResultType());
889  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
890
891  if (T1 != T2) {
892    // The result types are different.
893    if (!matchBasedOnSizeAndAlignment)
894      return false;
895    // Incomplete types don't have a size and alignment.
896    if (T1->isIncompleteType() || T2->isIncompleteType())
897      return false;
898    // Check is based on size and alignment.
899    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
900      return false;
901  }
902  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
903    T1 = Context.getCanonicalType(Method->getParamDecl(i)->getType());
904    T2 = Context.getCanonicalType(PrevMethod->getParamDecl(i)->getType());
905    if (T1 != T2) {
906      // The result types are different.
907      if (!matchBasedOnSizeAndAlignment)
908        return false;
909      // Incomplete types don't have a size and alignment.
910      if (T1->isIncompleteType() || T2->isIncompleteType())
911        return false;
912      // Check is based on size and alignment.
913      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
914        return false;
915    }
916  }
917  return true;
918}
919
920void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
921  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
922  if (!FirstMethod.Method) {
923    // Haven't seen a method with this selector name yet - add it.
924    FirstMethod.Method = Method;
925    FirstMethod.Next = 0;
926  } else {
927    // We've seen a method with this name, now check the type signature(s).
928    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
929
930    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
931         Next = Next->Next)
932      match = MatchTwoMethodDeclarations(Method, Next->Method);
933
934    if (!match) {
935      // We have a new signature for an existing method - add it.
936      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
937      FirstMethod.Next = new ObjCMethodList(Method, FirstMethod.Next);;
938    }
939  }
940}
941
942// FIXME: Finish implementing -Wno-strict-selector-match.
943ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
944                                                       SourceRange R) {
945  ObjCMethodList &MethList = InstanceMethodPool[Sel];
946  bool issueWarning = false;
947
948  if (MethList.Method && MethList.Next) {
949    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
950      // This checks if the methods differ by size & alignment.
951      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
952        issueWarning = true;
953  }
954  if (issueWarning && (MethList.Method && MethList.Next)) {
955    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
956    Diag(MethList.Method->getLocStart(), diag::note_using_decl)
957      << MethList.Method->getSourceRange();
958    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
959      Diag(Next->Method->getLocStart(), diag::note_also_found_decl)
960        << Next->Method->getSourceRange();
961  }
962  return MethList.Method;
963}
964
965void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
966  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
967  if (!FirstMethod.Method) {
968    // Haven't seen a method with this selector name yet - add it.
969    FirstMethod.Method = Method;
970    FirstMethod.Next = 0;
971  } else {
972    // We've seen a method with this name, now check the type signature(s).
973    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
974
975    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
976         Next = Next->Next)
977      match = MatchTwoMethodDeclarations(Method, Next->Method);
978
979    if (!match) {
980      // We have a new signature for an existing method - add it.
981      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
982      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
983      FirstMethod.Next = OMI;
984    }
985  }
986}
987
988/// diagnosePropertySetterGetterMismatch - Make sure that use-defined
989/// setter/getter methods have the property type and issue diagnostics
990/// if they don't.
991///
992void
993Sema::diagnosePropertySetterGetterMismatch(ObjCPropertyDecl *property,
994                                           const ObjCMethodDecl *GetterMethod,
995                                           const ObjCMethodDecl *SetterMethod) {
996  if (GetterMethod &&
997      GetterMethod->getResultType() != property->getType()) {
998    Diag(property->getLocation(),
999         diag::err_accessor_property_type_mismatch)
1000      << property->getDeclName()
1001      << GetterMethod->getSelector().getAsIdentifierInfo();
1002    Diag(GetterMethod->getLocation(), diag::note_declared_at);
1003  }
1004
1005  if (SetterMethod) {
1006    if (Context.getCanonicalType(SetterMethod->getResultType())
1007        != Context.VoidTy)
1008      Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1009    if (SetterMethod->getNumParams() != 1 ||
1010        (SetterMethod->getParamDecl(0)->getType() != property->getType())) {
1011      Diag(property->getLocation(),
1012           diag::err_accessor_property_type_mismatch)
1013        << property->getDeclName()
1014        << SetterMethod->getSelector().getAsIdentifierInfo();
1015      Diag(SetterMethod->getLocation(), diag::note_declared_at);
1016    }
1017  }
1018}
1019
1020// Note: For class/category implemenations, allMethods/allProperties is
1021// always null.
1022void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
1023                      DeclTy **allMethods, unsigned allNum,
1024                      DeclTy **allProperties, unsigned pNum) {
1025  Decl *ClassDecl = static_cast<Decl *>(classDecl);
1026
1027  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1028  // always passing in a decl. If the decl has an error, isInvalidDecl()
1029  // should be true.
1030  if (!ClassDecl)
1031    return;
1032
1033  llvm::SmallVector<ObjCMethodDecl*, 32> insMethods;
1034  llvm::SmallVector<ObjCMethodDecl*, 16> clsMethods;
1035
1036  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1037  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1038
1039  bool isInterfaceDeclKind =
1040        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1041         || isa<ObjCProtocolDecl>(ClassDecl);
1042  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1043
1044  if (pNum != 0) {
1045    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl))
1046      IDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
1047    else if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1048      CDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
1049    else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(ClassDecl))
1050      PDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
1051    else
1052      assert(false && "ActOnAtEnd - property declaration misplaced");
1053  }
1054
1055  for (unsigned i = 0; i < allNum; i++ ) {
1056    ObjCMethodDecl *Method =
1057      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
1058
1059    if (!Method) continue;  // Already issued a diagnostic.
1060    if (Method->isInstance()) {
1061      /// Check for instance method of the same name with incompatible types
1062      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1063      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1064                              : false;
1065      if ((isInterfaceDeclKind && PrevMethod && !match)
1066          || (checkIdenticalMethods && match)) {
1067          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1068            << Method->getDeclName();
1069          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1070      } else {
1071        insMethods.push_back(Method);
1072        InsMap[Method->getSelector()] = Method;
1073        /// The following allows us to typecheck messages to "id".
1074        AddInstanceMethodToGlobalPool(Method);
1075      }
1076    }
1077    else {
1078      /// Check for class method of the same name with incompatible types
1079      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1080      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1081                              : false;
1082      if ((isInterfaceDeclKind && PrevMethod && !match)
1083          || (checkIdenticalMethods && match)) {
1084        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1085          << Method->getDeclName();
1086        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1087      } else {
1088        clsMethods.push_back(Method);
1089        ClsMap[Method->getSelector()] = Method;
1090        /// The following allows us to typecheck messages to "Class".
1091        AddFactoryMethodToGlobalPool(Method);
1092      }
1093    }
1094  }
1095  // Save the size so we can detect if we've added any property methods.
1096  unsigned int insMethodsSizePriorToPropAdds = insMethods.size();
1097  unsigned int clsMethodsSizePriorToPropAdds = clsMethods.size();
1098
1099  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1100    // Compares properties declared in this class to those of its
1101    // super class.
1102    ComparePropertiesInBaseAndSuper(I);
1103    MergeProtocolPropertiesIntoClass(I, I);
1104    for (ObjCInterfaceDecl::classprop_iterator i = I->classprop_begin(),
1105         e = I->classprop_end(); i != e; ++i) {
1106      diagnosePropertySetterGetterMismatch((*i), InsMap[(*i)->getGetterName()],
1107                                           InsMap[(*i)->getSetterName()]);
1108      I->addPropertyMethods(Context, *i, insMethods, InsMap);
1109    }
1110    I->addMethods(&insMethods[0], insMethods.size(),
1111                  &clsMethods[0], clsMethods.size(), AtEndLoc);
1112
1113  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
1114    for (ObjCProtocolDecl::classprop_iterator i = P->classprop_begin(),
1115         e = P->classprop_end(); i != e; ++i) {
1116      diagnosePropertySetterGetterMismatch((*i), InsMap[(*i)->getGetterName()],
1117                                           InsMap[(*i)->getSetterName()]);
1118      P->addPropertyMethods(Context, *i, insMethods, InsMap);
1119    }
1120    P->addMethods(&insMethods[0], insMethods.size(),
1121                  &clsMethods[0], clsMethods.size(), AtEndLoc);
1122  }
1123  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1124    // Categories are used to extend the class by declaring new methods.
1125    // By the same token, they are also used to add new properties. No
1126    // need to compare the added property to those in the class.
1127
1128    // Merge protocol properties into category
1129    MergeProtocolPropertiesIntoClass(C, C);
1130    for (ObjCCategoryDecl::classprop_iterator i = C->classprop_begin(),
1131         e = C->classprop_end(); i != e; ++i) {
1132      diagnosePropertySetterGetterMismatch((*i), InsMap[(*i)->getGetterName()],
1133                                           InsMap[(*i)->getSetterName()]);
1134      C->addPropertyMethods(Context, *i, insMethods, InsMap);
1135    }
1136    C->addMethods(&insMethods[0], insMethods.size(),
1137                  &clsMethods[0], clsMethods.size(), AtEndLoc);
1138  }
1139  else if (ObjCImplementationDecl *IC =
1140                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1141    IC->setLocEnd(AtEndLoc);
1142    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
1143      ImplMethodsVsClassMethods(IC, IDecl);
1144  } else {
1145    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
1146    CatImplClass->setLocEnd(AtEndLoc);
1147    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1148    // Find category interface decl and then check that all methods declared
1149    // in this interface are implemented in the category @implementation.
1150    if (IDecl) {
1151      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1152           Categories; Categories = Categories->getNextClassCategory()) {
1153        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1154          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1155          break;
1156        }
1157      }
1158    }
1159  }
1160  // Add any synthesized methods to the global pool. This allows us to
1161  // handle the following, which is supported by GCC (and part of the design).
1162  //
1163  // @interface Foo
1164  // @property double bar;
1165  // @end
1166  //
1167  // void thisIsUnfortunate() {
1168  //   id foo;
1169  //   double bar = [foo bar];
1170  // }
1171  //
1172  if (insMethodsSizePriorToPropAdds < insMethods.size())
1173    for (unsigned i = insMethodsSizePriorToPropAdds; i < insMethods.size(); i++)
1174      AddInstanceMethodToGlobalPool(insMethods[i]);
1175  if (clsMethodsSizePriorToPropAdds < clsMethods.size())
1176    for (unsigned i = clsMethodsSizePriorToPropAdds; i < clsMethods.size(); i++)
1177      AddFactoryMethodToGlobalPool(clsMethods[i]);
1178}
1179
1180
1181/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1182/// objective-c's type qualifier from the parser version of the same info.
1183static Decl::ObjCDeclQualifier
1184CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1185  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1186  if (PQTVal & ObjCDeclSpec::DQ_In)
1187    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1188  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1189    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1190  if (PQTVal & ObjCDeclSpec::DQ_Out)
1191    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1192  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1193    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1194  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1195    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1196  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1197    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1198
1199  return ret;
1200}
1201
1202Sema::DeclTy *Sema::ActOnMethodDeclaration(
1203    SourceLocation MethodLoc, SourceLocation EndLoc,
1204    tok::TokenKind MethodType, DeclTy *classDecl,
1205    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1206    Selector Sel,
1207    // optional arguments. The number of types/arguments is obtained
1208    // from the Sel.getNumArgs().
1209    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1210    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1211    bool isVariadic) {
1212  Decl *ClassDecl = static_cast<Decl*>(classDecl);
1213
1214  // Make sure we can establish a context for the method.
1215  if (!ClassDecl) {
1216    Diag(MethodLoc, diag::error_missing_method_context);
1217    return 0;
1218  }
1219  QualType resultDeclType;
1220
1221  if (ReturnType)
1222    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1223  else // get the type for "id".
1224    resultDeclType = Context.getObjCIdType();
1225
1226  ObjCMethodDecl* ObjCMethod =
1227    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1228                           ClassDecl,
1229                           MethodType == tok::minus, isVariadic,
1230                           false,
1231                           MethodDeclKind == tok::objc_optional ?
1232                           ObjCMethodDecl::Optional :
1233                           ObjCMethodDecl::Required);
1234
1235  llvm::SmallVector<ParmVarDecl*, 16> Params;
1236
1237  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
1238    // FIXME: arg->AttrList must be stored too!
1239    QualType argType, originalArgType;
1240
1241    if (ArgTypes[i]) {
1242      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
1243      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1244      if (argType->isArrayType())  { // (char *[]) -> (char **)
1245        originalArgType = argType;
1246        argType = Context.getArrayDecayedType(argType);
1247      }
1248      else if (argType->isFunctionType())
1249        argType = Context.getPointerType(argType);
1250    } else
1251      argType = Context.getObjCIdType();
1252    ParmVarDecl* Param;
1253    if (originalArgType.isNull())
1254      Param = ParmVarDecl::Create(Context, ObjCMethod,
1255                                  SourceLocation(/*FIXME*/),
1256                                  ArgNames[i], argType,
1257                                  VarDecl::None, 0, 0);
1258    else
1259      Param = ParmVarWithOriginalTypeDecl::Create(Context, ObjCMethod,
1260                                  SourceLocation(/*FIXME*/),
1261                                  ArgNames[i], argType, originalArgType,
1262                                  VarDecl::None, 0, 0);
1263
1264    Param->setObjCDeclQualifier(
1265      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
1266    Params.push_back(Param);
1267  }
1268
1269  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
1270  ObjCMethod->setObjCDeclQualifier(
1271    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1272  const ObjCMethodDecl *PrevMethod = 0;
1273
1274  if (AttrList)
1275    ProcessDeclAttributeList(ObjCMethod, AttrList);
1276
1277  // For implementations (which can be very "coarse grain"), we add the
1278  // method now. This allows the AST to implement lookup methods that work
1279  // incrementally (without waiting until we parse the @end). It also allows
1280  // us to flag multiple declaration errors as they occur.
1281  if (ObjCImplementationDecl *ImpDecl =
1282        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1283    if (MethodType == tok::minus) {
1284      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1285      ImpDecl->addInstanceMethod(ObjCMethod);
1286    } else {
1287      PrevMethod = ImpDecl->getClassMethod(Sel);
1288      ImpDecl->addClassMethod(ObjCMethod);
1289    }
1290  }
1291  else if (ObjCCategoryImplDecl *CatImpDecl =
1292            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1293    if (MethodType == tok::minus) {
1294      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1295      CatImpDecl->addInstanceMethod(ObjCMethod);
1296    } else {
1297      PrevMethod = CatImpDecl->getClassMethod(Sel);
1298      CatImpDecl->addClassMethod(ObjCMethod);
1299    }
1300  }
1301  if (PrevMethod) {
1302    // You can never have two method definitions with the same name.
1303    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1304      << ObjCMethod->getDeclName();
1305    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1306  }
1307  return ObjCMethod;
1308}
1309
1310void Sema::CheckObjCPropertyAttributes(QualType PropertyTy,
1311                                       SourceLocation Loc,
1312                                       unsigned &Attributes) {
1313  // FIXME: Improve the reported location.
1314
1315  // readonly and readwrite/assign/retain/copy conflict.
1316  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1317      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1318                     ObjCDeclSpec::DQ_PR_assign |
1319                     ObjCDeclSpec::DQ_PR_copy |
1320                     ObjCDeclSpec::DQ_PR_retain))) {
1321    const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1322                          "readwrite" :
1323                         (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1324                          "assign" :
1325                         (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1326                          "copy" : "retain";
1327
1328    Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1329                 diag::err_objc_property_attr_mutually_exclusive :
1330                 diag::warn_objc_property_attr_mutually_exclusive)
1331      << "readonly" << which;
1332  }
1333
1334  // Check for copy or retain on non-object types.
1335  if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) &&
1336      !Context.isObjCObjectPointerType(PropertyTy)) {
1337    Diag(Loc, diag::err_objc_property_requires_object)
1338      << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain");
1339    Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain);
1340  }
1341
1342  // Check for more than one of { assign, copy, retain }.
1343  if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1344    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1345      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1346        << "assign" << "copy";
1347      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1348    }
1349    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1350      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1351        << "assign" << "retain";
1352      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1353    }
1354  } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1355    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1356      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1357        << "copy" << "retain";
1358      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1359    }
1360  }
1361
1362  // Warn if user supplied no assignment attribute, property is
1363  // readwrite, and this is an object type.
1364  if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
1365                      ObjCDeclSpec::DQ_PR_retain)) &&
1366      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1367      Context.isObjCObjectPointerType(PropertyTy)) {
1368    // Skip this warning in gc-only mode.
1369    if (getLangOptions().getGCMode() != LangOptions::GCOnly)
1370      Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
1371
1372    // If non-gc code warn that this is likely inappropriate.
1373    if (getLangOptions().getGCMode() == LangOptions::NonGC)
1374      Diag(Loc, diag::warn_objc_property_default_assign_on_object);
1375
1376    // FIXME: Implement warning dependent on NSCopying being
1377    // implemented. See also:
1378    // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
1379    // (please trim this list while you are at it).
1380  }
1381}
1382
1383Sema::DeclTy *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1384                                  FieldDeclarator &FD,
1385                                  ObjCDeclSpec &ODS,
1386                                  Selector GetterSel,
1387                                  Selector SetterSel,
1388                                  DeclTy *ClassCategory,
1389                                  bool *isOverridingProperty,
1390                                  tok::ObjCKeywordKind MethodImplKind) {
1391  unsigned Attributes = ODS.getPropertyAttributes();
1392  bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
1393                      // default is readwrite!
1394                      !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
1395  // property is defaulted to 'assign' if it is readwrite and is
1396  // not retain or copy
1397  bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
1398                   (isReadWrite &&
1399                    !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1400                    !(Attributes & ObjCDeclSpec::DQ_PR_copy)));
1401  QualType T = GetTypeForDeclarator(FD.D, S);
1402  Decl *ClassDecl = static_cast<Decl *>(ClassCategory);
1403
1404  // May modify Attributes.
1405  CheckObjCPropertyAttributes(T, AtLoc, Attributes);
1406
1407  if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1408    if (!CDecl->getIdentifier()) {
1409      // This is an anonymous category. property requires special
1410      // handling.
1411      if (ObjCInterfaceDecl *ICDecl = CDecl->getClassInterface()) {
1412        if (ObjCPropertyDecl *PIDecl =
1413            ICDecl->FindPropertyDeclaration(FD.D.getIdentifier())) {
1414          // property 'PIDecl's readonly attribute will be over-ridden
1415          // with anonymous category's readwrite property attribute!
1416          unsigned PIkind = PIDecl->getPropertyAttributes();
1417          if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
1418            if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) !=
1419                (PIkind & ObjCPropertyDecl::OBJC_PR_nonatomic))
1420              Diag(AtLoc, diag::warn_property_attr_mismatch);
1421            PIDecl->makeitReadWriteAttribute();
1422            if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1423              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1424            if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1425              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1426            PIDecl->setSetterName(SetterSel);
1427            // FIXME: use a common routine with addPropertyMethods.
1428            ObjCMethodDecl *SetterDecl =
1429              ObjCMethodDecl::Create(Context, AtLoc, AtLoc, SetterSel,
1430                                     Context.VoidTy,
1431                                     ICDecl,
1432                                     true, false, true,
1433                                     ObjCMethodDecl::Required);
1434            ParmVarDecl *Argument = ParmVarDecl::Create(Context,
1435                                                        SetterDecl,
1436                                                        SourceLocation(),
1437                                                        FD.D.getIdentifier(),
1438                                                        T,
1439                                                        VarDecl::None,
1440                                                        0, 0);
1441            SetterDecl->setMethodParams(&Argument, 1);
1442            PIDecl->setSetterMethodDecl(SetterDecl);
1443          }
1444          else
1445            Diag(AtLoc, diag::err_use_continuation_class) << ICDecl->getDeclName();
1446          *isOverridingProperty = true;
1447          return 0;
1448        }
1449        // No matching property found in the main class. Just fall thru
1450        // and add property to the anonymous category. It looks like
1451	// it works as is. This category becomes just like a category
1452	// for its primary class.
1453      } else {
1454          Diag(CDecl->getLocation(), diag::err_continuation_class);
1455          *isOverridingProperty = true;
1456          return 0;
1457      }
1458    }
1459
1460  Type *t = T.getTypePtr();
1461  if (t->isArrayType() || t->isFunctionType())
1462    Diag(AtLoc, diag::err_property_type) << T;
1463
1464  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, AtLoc,
1465                                                     FD.D.getIdentifier(), T);
1466  // Regardless of setter/getter attribute, we save the default getter/setter
1467  // selector names in anticipation of declaration of setter/getter methods.
1468  PDecl->setGetterName(GetterSel);
1469  PDecl->setSetterName(SetterSel);
1470
1471  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
1472    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1473
1474  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
1475    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1476
1477  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
1478    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1479
1480  if (isReadWrite)
1481    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1482
1483  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1484    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1485
1486  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1487    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1488
1489  if (isAssign)
1490    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1491
1492  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
1493    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1494
1495  if (MethodImplKind == tok::objc_required)
1496    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1497  else if (MethodImplKind == tok::objc_optional)
1498    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1499
1500  return PDecl;
1501}
1502
1503/// ActOnPropertyImplDecl - This routine performs semantic checks and
1504/// builds the AST node for a property implementation declaration; declared
1505/// as @synthesize or @dynamic.
1506///
1507Sema::DeclTy *Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1508                                          SourceLocation PropertyLoc,
1509                                          bool Synthesize,
1510                                          DeclTy *ClassCatImpDecl,
1511                                          IdentifierInfo *PropertyId,
1512                                          IdentifierInfo *PropertyIvar) {
1513  Decl *ClassImpDecl = static_cast<Decl*>(ClassCatImpDecl);
1514  // Make sure we have a context for the property implementation declaration.
1515  if (!ClassImpDecl) {
1516    Diag(AtLoc, diag::error_missing_property_context);
1517    return 0;
1518  }
1519  ObjCPropertyDecl *property = 0;
1520  ObjCInterfaceDecl* IDecl = 0;
1521  // Find the class or category class where this property must have
1522  // a declaration.
1523  ObjCImplementationDecl *IC = 0;
1524  ObjCCategoryImplDecl* CatImplClass = 0;
1525  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1526    IDecl = getObjCInterfaceDecl(IC->getIdentifier());
1527    // We always synthesize an interface for an implementation
1528    // without an interface decl. So, IDecl is always non-zero.
1529    assert(IDecl &&
1530           "ActOnPropertyImplDecl - @implementation without @interface");
1531
1532    // Look for this property declaration in the @implementation's @interface
1533    property = IDecl->FindPropertyDeclaration(PropertyId);
1534    if (!property) {
1535      Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
1536      return 0;
1537    }
1538  }
1539  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1540    if (Synthesize) {
1541      Diag(AtLoc, diag::error_synthesize_category_decl);
1542      return 0;
1543    }
1544    IDecl = CatImplClass->getClassInterface();
1545    if (!IDecl) {
1546      Diag(AtLoc, diag::error_missing_property_interface);
1547      return 0;
1548    }
1549    ObjCCategoryDecl *Category =
1550      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1551
1552    // If category for this implementation not found, it is an error which
1553    // has already been reported eralier.
1554    if (!Category)
1555      return 0;
1556    // Look for this property declaration in @implementation's category
1557    property = Category->FindPropertyDeclaration(PropertyId);
1558    if (!property) {
1559      Diag(PropertyLoc, diag::error_bad_category_property_decl)
1560        << Category->getDeclName();
1561      return 0;
1562    }
1563  }
1564  else {
1565    Diag(AtLoc, diag::error_bad_property_context);
1566    return 0;
1567  }
1568  ObjCIvarDecl *Ivar = 0;
1569  // Check that we have a valid, previously declared ivar for @synthesize
1570  if (Synthesize) {
1571    // @synthesize
1572    if (!PropertyIvar)
1573      PropertyIvar = PropertyId;
1574    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1575    Ivar = IDecl->FindIvarDeclaration(PropertyIvar);
1576    if (!Ivar) {
1577      Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
1578      return 0;
1579    }
1580    QualType PropType = Context.getCanonicalType(property->getType());
1581    QualType IvarType = Context.getCanonicalType(Ivar->getType());
1582
1583    // Check that type of property and its ivar are type compatible.
1584    if (PropType != IvarType) {
1585      if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) {
1586        Diag(PropertyLoc, diag::error_property_ivar_type)
1587          << property->getDeclName() << Ivar->getDeclName();
1588        return 0;
1589      }
1590    }
1591  } else if (PropertyIvar) {
1592    // @dynamic
1593    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1594    return 0;
1595  }
1596  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1597  ObjCPropertyImplDecl *PIDecl =
1598    ObjCPropertyImplDecl::Create(Context, AtLoc, PropertyLoc, property,
1599                                 (Synthesize ?
1600                                  ObjCPropertyImplDecl::Synthesize
1601                                  : ObjCPropertyImplDecl::Dynamic),
1602                                 Ivar);
1603  if (IC) {
1604    if (Synthesize)
1605      if (ObjCPropertyImplDecl *PPIDecl =
1606          IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1607        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1608          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1609          << PropertyIvar;
1610        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1611      }
1612
1613    if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplDecl(PropertyId)) {
1614      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1615      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1616      return 0;
1617    }
1618    IC->addPropertyImplementation(PIDecl);
1619  }
1620  else {
1621    if (Synthesize)
1622      if (ObjCPropertyImplDecl *PPIDecl =
1623          CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1624        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1625          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1626          << PropertyIvar;
1627        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1628      }
1629
1630    if (ObjCPropertyImplDecl *PPIDecl =
1631          CatImplClass->FindPropertyImplDecl(PropertyId)) {
1632      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1633      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1634      return 0;
1635    }
1636    CatImplClass->addPropertyImplementation(PIDecl);
1637  }
1638
1639  return PIDecl;
1640}
1641
1642bool Sema::CheckObjCDeclScope(Decl *D) {
1643  if (isa<TranslationUnitDecl>(CurContext))
1644    return false;
1645
1646  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1647  D->setInvalidDecl();
1648
1649  return true;
1650}
1651
1652/// Collect the instance variables declared in an Objective-C object.  Used in
1653/// the creation of structures from objects using the @defs directive.
1654/// FIXME: This should be consolidated with CollectObjCIvars as it is also
1655/// part of the AST generation logic of @defs.
1656static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
1657                         ASTContext& Ctx,
1658                         llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
1659  if (Class->getSuperClass())
1660    CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
1661
1662  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1663  for (ObjCInterfaceDecl::ivar_iterator
1664       I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1665
1666    ObjCIvarDecl* ID = *I;
1667    ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
1668                                                ID->getLocation(),
1669                                                ID->getIdentifier(),
1670                                                ID->getType(),
1671                                                ID->getBitWidth()));
1672  }
1673}
1674
1675/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1676/// instance variables of ClassName into Decls.
1677void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
1678                     IdentifierInfo *ClassName,
1679                     llvm::SmallVectorImpl<DeclTy*> &Decls) {
1680  // Check that ClassName is a valid class
1681  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1682  if (!Class) {
1683    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1684    return;
1685  }
1686  // Collect the instance variables
1687  CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
1688
1689  // Introduce all of these fields into the appropriate scope.
1690  for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
1691       D != Decls.end(); ++D) {
1692    FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
1693    if (getLangOptions().CPlusPlus)
1694      PushOnScopeChains(cast<FieldDecl>(FD), S);
1695    else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
1696      Record->addDecl(Context, FD);
1697  }
1698}
1699
1700