1 //===--- DeclObjC.cpp - ObjC Declaration AST Node Implementation ----------===//
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 the Objective-C related Decl classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Stmt.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "llvm/ADT/STLExtras.h"
19 using namespace clang;
20 
21 //===----------------------------------------------------------------------===//
22 // ObjCListBase
23 //===----------------------------------------------------------------------===//
24 
25 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
26   List = 0;
27   if (Elts == 0) return;  // Setting to an empty list is a noop.
28 
29 
30   List = new (Ctx) void*[Elts];
31   NumElts = Elts;
32   memcpy(List, InList, sizeof(void*)*Elts);
33 }
34 
35 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts,
36                            const SourceLocation *Locs, ASTContext &Ctx) {
37   if (Elts == 0)
38     return;
39 
40   Locations = new (Ctx) SourceLocation[Elts];
41   memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
42   set(InList, Elts, Ctx);
43 }
44 
45 //===----------------------------------------------------------------------===//
46 // ObjCInterfaceDecl
47 //===----------------------------------------------------------------------===//
48 
49 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
50 ///
51 ObjCIvarDecl *
52 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
53   lookup_const_iterator Ivar, IvarEnd;
54   for (llvm::tie(Ivar, IvarEnd) = lookup(Id); Ivar != IvarEnd; ++Ivar) {
55     if (ObjCIvarDecl *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
56       return ivar;
57   }
58   return 0;
59 }
60 
61 // Get the local instance/class method declared in this interface.
62 ObjCMethodDecl *
63 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance) const {
64   // Since instance & class methods can have the same name, the loop below
65   // ensures we get the correct method.
66   //
67   // @interface Whatever
68   // - (int) class_method;
69   // + (float) class_method;
70   // @end
71   //
72   lookup_const_iterator Meth, MethEnd;
73   for (llvm::tie(Meth, MethEnd) = lookup(Sel); Meth != MethEnd; ++Meth) {
74     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
75     if (MD && MD->isInstanceMethod() == isInstance)
76       return MD;
77   }
78   return 0;
79 }
80 
81 ObjCPropertyDecl *
82 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
83                                    IdentifierInfo *propertyID) {
84 
85   DeclContext::lookup_const_iterator I, E;
86   llvm::tie(I, E) = DC->lookup(propertyID);
87   for ( ; I != E; ++I)
88     if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I))
89       return PD;
90 
91   return 0;
92 }
93 
94 /// FindPropertyDeclaration - Finds declaration of the property given its name
95 /// in 'PropertyId' and returns it. It returns 0, if not found.
96 ObjCPropertyDecl *
97 ObjCContainerDecl::FindPropertyDeclaration(IdentifierInfo *PropertyId) const {
98 
99   if (ObjCPropertyDecl *PD =
100         ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
101     return PD;
102 
103   switch (getKind()) {
104     default:
105       break;
106     case Decl::ObjCProtocol: {
107       const ObjCProtocolDecl *PID = cast<ObjCProtocolDecl>(this);
108       for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
109            E = PID->protocol_end(); I != E; ++I)
110         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
111           return P;
112       break;
113     }
114     case Decl::ObjCInterface: {
115       const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(this);
116       // Look through categories.
117       for (ObjCCategoryDecl *Cat = OID->getCategoryList();
118            Cat; Cat = Cat->getNextClassCategory())
119         if (!Cat->IsClassExtension())
120           if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(PropertyId))
121             return P;
122 
123       // Look through protocols.
124       for (ObjCInterfaceDecl::all_protocol_iterator
125             I = OID->all_referenced_protocol_begin(),
126             E = OID->all_referenced_protocol_end(); I != E; ++I)
127         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
128           return P;
129 
130       // Finally, check the super class.
131       if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
132         return superClass->FindPropertyDeclaration(PropertyId);
133       break;
134     }
135     case Decl::ObjCCategory: {
136       const ObjCCategoryDecl *OCD = cast<ObjCCategoryDecl>(this);
137       // Look through protocols.
138       if (!OCD->IsClassExtension())
139         for (ObjCCategoryDecl::protocol_iterator
140               I = OCD->protocol_begin(), E = OCD->protocol_end(); I != E; ++I)
141         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
142           return P;
143 
144       break;
145     }
146   }
147   return 0;
148 }
149 
150 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
151 /// with name 'PropertyId' in the primary class; including those in protocols
152 /// (direct or indirect) used by the primary class.
153 ///
154 ObjCPropertyDecl *
155 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
156                                             IdentifierInfo *PropertyId) const {
157   if (ExternallyCompleted)
158     LoadExternalDefinition();
159 
160   if (ObjCPropertyDecl *PD =
161       ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
162     return PD;
163 
164   // Look through protocols.
165   for (ObjCInterfaceDecl::all_protocol_iterator
166         I = all_referenced_protocol_begin(),
167         E = all_referenced_protocol_end(); I != E; ++I)
168     if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
169       return P;
170 
171   return 0;
172 }
173 
174 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
175                               ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
176                               ASTContext &C)
177 {
178   if (ExternallyCompleted)
179     LoadExternalDefinition();
180 
181   if (AllReferencedProtocols.empty() && ReferencedProtocols.empty()) {
182     AllReferencedProtocols.set(ExtList, ExtNum, C);
183     return;
184   }
185 
186   // Check for duplicate protocol in class's protocol list.
187   // This is O(n*m). But it is extremely rare and number of protocols in
188   // class or its extension are very few.
189   SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
190   for (unsigned i = 0; i < ExtNum; i++) {
191     bool protocolExists = false;
192     ObjCProtocolDecl *ProtoInExtension = ExtList[i];
193     for (all_protocol_iterator
194           p = all_referenced_protocol_begin(),
195           e = all_referenced_protocol_end(); p != e; ++p) {
196       ObjCProtocolDecl *Proto = (*p);
197       if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
198         protocolExists = true;
199         break;
200       }
201     }
202     // Do we want to warn on a protocol in extension class which
203     // already exist in the class? Probably not.
204     if (!protocolExists)
205       ProtocolRefs.push_back(ProtoInExtension);
206   }
207 
208   if (ProtocolRefs.empty())
209     return;
210 
211   // Merge ProtocolRefs into class's protocol list;
212   for (all_protocol_iterator p = all_referenced_protocol_begin(),
213         e = all_referenced_protocol_end(); p != e; ++p) {
214     ProtocolRefs.push_back(*p);
215   }
216 
217   AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(), C);
218 }
219 
220 /// getFirstClassExtension - Find first class extension of the given class.
221 ObjCCategoryDecl* ObjCInterfaceDecl::getFirstClassExtension() const {
222   for (ObjCCategoryDecl *CDecl = getCategoryList(); CDecl;
223        CDecl = CDecl->getNextClassCategory())
224     if (CDecl->IsClassExtension())
225       return CDecl;
226   return 0;
227 }
228 
229 /// getNextClassCategory - Find next class extension in list of categories.
230 const ObjCCategoryDecl* ObjCCategoryDecl::getNextClassExtension() const {
231   for (const ObjCCategoryDecl *CDecl = getNextClassCategory(); CDecl;
232         CDecl = CDecl->getNextClassCategory())
233     if (CDecl->IsClassExtension())
234       return CDecl;
235   return 0;
236 }
237 
238 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
239                                               ObjCInterfaceDecl *&clsDeclared) {
240   ObjCInterfaceDecl* ClassDecl = this;
241   while (ClassDecl != NULL) {
242     if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
243       clsDeclared = ClassDecl;
244       return I;
245     }
246     for (const ObjCCategoryDecl *CDecl = ClassDecl->getFirstClassExtension();
247          CDecl; CDecl = CDecl->getNextClassExtension()) {
248       if (ObjCIvarDecl *I = CDecl->getIvarDecl(ID)) {
249         clsDeclared = ClassDecl;
250         return I;
251       }
252     }
253 
254     ClassDecl = ClassDecl->getSuperClass();
255   }
256   return NULL;
257 }
258 
259 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
260 /// class whose name is passed as argument. If it is not one of the super classes
261 /// the it returns NULL.
262 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
263                                         const IdentifierInfo*ICName) {
264   ObjCInterfaceDecl* ClassDecl = this;
265   while (ClassDecl != NULL) {
266     if (ClassDecl->getIdentifier() == ICName)
267       return ClassDecl;
268     ClassDecl = ClassDecl->getSuperClass();
269   }
270   return NULL;
271 }
272 
273 /// lookupMethod - This method returns an instance/class method by looking in
274 /// the class, its categories, and its super classes (using a linear search).
275 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
276                                                 bool isInstance) const {
277   const ObjCInterfaceDecl* ClassDecl = this;
278   ObjCMethodDecl *MethodDecl = 0;
279 
280   if (ExternallyCompleted)
281     LoadExternalDefinition();
282 
283   while (ClassDecl != NULL) {
284     if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
285       return MethodDecl;
286 
287     // Didn't find one yet - look through protocols.
288     const ObjCList<ObjCProtocolDecl> &Protocols =
289       ClassDecl->getReferencedProtocols();
290     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
291          E = Protocols.end(); I != E; ++I)
292       if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
293         return MethodDecl;
294 
295     // Didn't find one yet - now look through categories.
296     ObjCCategoryDecl *CatDecl = ClassDecl->getCategoryList();
297     while (CatDecl) {
298       if ((MethodDecl = CatDecl->getMethod(Sel, isInstance)))
299         return MethodDecl;
300 
301       // Didn't find one yet - look through protocols.
302       const ObjCList<ObjCProtocolDecl> &Protocols =
303         CatDecl->getReferencedProtocols();
304       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
305            E = Protocols.end(); I != E; ++I)
306         if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
307           return MethodDecl;
308       CatDecl = CatDecl->getNextClassCategory();
309     }
310     ClassDecl = ClassDecl->getSuperClass();
311   }
312   return NULL;
313 }
314 
315 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
316                                    const Selector &Sel,
317                                    bool Instance) {
318   ObjCMethodDecl *Method = 0;
319   if (ObjCImplementationDecl *ImpDecl = getImplementation())
320     Method = Instance ? ImpDecl->getInstanceMethod(Sel)
321                       : ImpDecl->getClassMethod(Sel);
322 
323   if (!Method && getSuperClass())
324     return getSuperClass()->lookupPrivateMethod(Sel, Instance);
325   return Method;
326 }
327 
328 //===----------------------------------------------------------------------===//
329 // ObjCMethodDecl
330 //===----------------------------------------------------------------------===//
331 
332 ObjCMethodDecl *ObjCMethodDecl::Create(ASTContext &C,
333                                        SourceLocation beginLoc,
334                                        SourceLocation endLoc,
335                                        Selector SelInfo, QualType T,
336                                        TypeSourceInfo *ResultTInfo,
337                                        DeclContext *contextDecl,
338                                        bool isInstance,
339                                        bool isVariadic,
340                                        bool isSynthesized,
341                                        bool isImplicitlyDeclared,
342                                        bool isDefined,
343                                        ImplementationControl impControl,
344                                        bool HasRelatedResultType) {
345   return new (C) ObjCMethodDecl(beginLoc, endLoc,
346                                 SelInfo, T, ResultTInfo, contextDecl,
347                                 isInstance,
348                                 isVariadic, isSynthesized, isImplicitlyDeclared,
349                                 isDefined,
350                                 impControl,
351                                 HasRelatedResultType);
352 }
353 
354 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
355                                          ArrayRef<ParmVarDecl*> Params,
356                                          ArrayRef<SourceLocation> SelLocs) {
357   ParamsAndSelLocs = 0;
358   NumParams = Params.size();
359   if (Params.empty() && SelLocs.empty())
360     return;
361 
362   unsigned Size = sizeof(ParmVarDecl *) * NumParams +
363                   sizeof(SourceLocation) * SelLocs.size();
364   ParamsAndSelLocs = C.Allocate(Size);
365   std::copy(Params.begin(), Params.end(), getParams());
366   std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
367 }
368 
369 void ObjCMethodDecl::getSelectorLocs(
370                                SmallVectorImpl<SourceLocation> &SelLocs) const {
371   for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
372     SelLocs.push_back(getSelectorLoc(i));
373 }
374 
375 void ObjCMethodDecl::setMethodParams(ASTContext &C,
376                                      ArrayRef<ParmVarDecl*> Params,
377                                      ArrayRef<SourceLocation> SelLocs) {
378   assert((!SelLocs.empty() || isImplicit()) &&
379          "No selector locs for non-implicit method");
380   if (isImplicit())
381     return setParamsAndSelLocs(C, Params, ArrayRef<SourceLocation>());
382 
383   SelLocsKind = hasStandardSelectorLocs(getSelector(), SelLocs, Params, EndLoc);
384   if (SelLocsKind != SelLoc_NonStandard)
385     return setParamsAndSelLocs(C, Params, ArrayRef<SourceLocation>());
386 
387   setParamsAndSelLocs(C, Params, SelLocs);
388 }
389 
390 /// \brief A definition will return its interface declaration.
391 /// An interface declaration will return its definition.
392 /// Otherwise it will return itself.
393 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclaration() {
394   ASTContext &Ctx = getASTContext();
395   ObjCMethodDecl *Redecl = 0;
396   Decl *CtxD = cast<Decl>(getDeclContext());
397 
398   if (ObjCInterfaceDecl *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
399     if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
400       Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
401 
402   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
403     if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
404       Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
405 
406   } else if (ObjCImplementationDecl *ImplD =
407                dyn_cast<ObjCImplementationDecl>(CtxD)) {
408     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
409       Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
410 
411   } else if (ObjCCategoryImplDecl *CImplD =
412                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
413     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
414       Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
415   }
416 
417   return Redecl ? Redecl : this;
418 }
419 
420 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
421   Decl *CtxD = cast<Decl>(getDeclContext());
422 
423   if (ObjCImplementationDecl *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
424     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
425       if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
426                                               isInstanceMethod()))
427         return MD;
428 
429   } else if (ObjCCategoryImplDecl *CImplD =
430                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
431     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
432       if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
433                                                isInstanceMethod()))
434         return MD;
435   }
436 
437   return this;
438 }
439 
440 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
441   ObjCMethodFamily family = static_cast<ObjCMethodFamily>(Family);
442   if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
443     return family;
444 
445   // Check for an explicit attribute.
446   if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
447     // The unfortunate necessity of mapping between enums here is due
448     // to the attributes framework.
449     switch (attr->getFamily()) {
450     case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
451     case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
452     case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
453     case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
454     case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
455     case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
456     }
457     Family = static_cast<unsigned>(family);
458     return family;
459   }
460 
461   family = getSelector().getMethodFamily();
462   switch (family) {
463   case OMF_None: break;
464 
465   // init only has a conventional meaning for an instance method, and
466   // it has to return an object.
467   case OMF_init:
468     if (!isInstanceMethod() || !getResultType()->isObjCObjectPointerType())
469       family = OMF_None;
470     break;
471 
472   // alloc/copy/new have a conventional meaning for both class and
473   // instance methods, but they require an object return.
474   case OMF_alloc:
475   case OMF_copy:
476   case OMF_mutableCopy:
477   case OMF_new:
478     if (!getResultType()->isObjCObjectPointerType())
479       family = OMF_None;
480     break;
481 
482   // These selectors have a conventional meaning only for instance methods.
483   case OMF_dealloc:
484   case OMF_finalize:
485   case OMF_retain:
486   case OMF_release:
487   case OMF_autorelease:
488   case OMF_retainCount:
489   case OMF_self:
490     if (!isInstanceMethod())
491       family = OMF_None;
492     break;
493 
494   case OMF_performSelector:
495     if (!isInstanceMethod() ||
496         !getResultType()->isObjCIdType())
497       family = OMF_None;
498     else {
499       unsigned noParams = param_size();
500       if (noParams < 1 || noParams > 3)
501         family = OMF_None;
502       else {
503         ObjCMethodDecl::arg_type_iterator it = arg_type_begin();
504         QualType ArgT = (*it);
505         if (!ArgT->isObjCSelType()) {
506           family = OMF_None;
507           break;
508         }
509         while (--noParams) {
510           it++;
511           ArgT = (*it);
512           if (!ArgT->isObjCIdType()) {
513             family = OMF_None;
514             break;
515           }
516         }
517       }
518     }
519     break;
520 
521   }
522 
523   // Cache the result.
524   Family = static_cast<unsigned>(family);
525   return family;
526 }
527 
528 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
529                                           const ObjCInterfaceDecl *OID) {
530   QualType selfTy;
531   if (isInstanceMethod()) {
532     // There may be no interface context due to error in declaration
533     // of the interface (which has been reported). Recover gracefully.
534     if (OID) {
535       selfTy = Context.getObjCInterfaceType(OID);
536       selfTy = Context.getObjCObjectPointerType(selfTy);
537     } else {
538       selfTy = Context.getObjCIdType();
539     }
540   } else // we have a factory method.
541     selfTy = Context.getObjCClassType();
542 
543   bool selfIsPseudoStrong = false;
544   bool selfIsConsumed = false;
545   if (isInstanceMethod() && Context.getLangOptions().ObjCAutoRefCount) {
546     selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
547 
548     // 'self' is always __strong.  It's actually pseudo-strong except
549     // in init methods, though.
550     Qualifiers qs;
551     qs.setObjCLifetime(Qualifiers::OCL_Strong);
552     selfTy = Context.getQualifiedType(selfTy, qs);
553 
554     // In addition, 'self' is const unless this is an init method.
555     if (getMethodFamily() != OMF_init) {
556       selfTy = selfTy.withConst();
557       selfIsPseudoStrong = true;
558     }
559   }
560 
561   ImplicitParamDecl *self
562     = ImplicitParamDecl::Create(Context, this, SourceLocation(),
563                                 &Context.Idents.get("self"), selfTy);
564   setSelfDecl(self);
565 
566   if (selfIsConsumed)
567     self->addAttr(new (Context) NSConsumedAttr(SourceLocation(), Context));
568 
569   if (selfIsPseudoStrong)
570     self->setARCPseudoStrong(true);
571 
572   setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
573                                        &Context.Idents.get("_cmd"),
574                                        Context.getObjCSelType()));
575 }
576 
577 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
578   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
579     return ID;
580   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
581     return CD->getClassInterface();
582   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
583     return IMD->getClassInterface();
584 
585   assert(!isa<ObjCProtocolDecl>(getDeclContext()) && "It's a protocol method");
586   llvm_unreachable("unknown method context");
587 }
588 
589 //===----------------------------------------------------------------------===//
590 // ObjCInterfaceDecl
591 //===----------------------------------------------------------------------===//
592 
593 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(ASTContext &C,
594                                              DeclContext *DC,
595                                              SourceLocation atLoc,
596                                              IdentifierInfo *Id,
597                                              SourceLocation ClassLoc,
598                                              bool ForwardDecl, bool isInternal){
599   return new (C) ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc, ForwardDecl,
600                                      isInternal);
601 }
602 
603 ObjCInterfaceDecl::
604 ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id,
605                   SourceLocation CLoc, bool FD, bool isInternal)
606   : ObjCContainerDecl(ObjCInterface, DC, atLoc, Id),
607     TypeForDecl(0), SuperClass(0),
608     CategoryList(0), IvarList(0),
609     ForwardDecl(FD), InternalInterface(isInternal), ExternallyCompleted(false),
610     ClassLoc(CLoc) {
611 }
612 
613 void ObjCInterfaceDecl::LoadExternalDefinition() const {
614   assert(ExternallyCompleted && "Class is not externally completed");
615   ExternallyCompleted = false;
616   getASTContext().getExternalSource()->CompleteType(
617                                         const_cast<ObjCInterfaceDecl *>(this));
618 }
619 
620 void ObjCInterfaceDecl::setExternallyCompleted() {
621   assert(getASTContext().getExternalSource() &&
622          "Class can't be externally completed without an external source");
623   assert(!ForwardDecl &&
624          "Forward declarations can't be externally completed");
625   ExternallyCompleted = true;
626 }
627 
628 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
629   if (ExternallyCompleted)
630     LoadExternalDefinition();
631 
632   return getASTContext().getObjCImplementation(
633                                           const_cast<ObjCInterfaceDecl*>(this));
634 }
635 
636 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
637   getASTContext().setObjCImplementation(this, ImplD);
638 }
639 
640 /// all_declared_ivar_begin - return first ivar declared in this class,
641 /// its extensions and its implementation. Lazily build the list on first
642 /// access.
643 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
644   if (IvarList)
645     return IvarList;
646 
647   ObjCIvarDecl *curIvar = 0;
648   if (!ivar_empty()) {
649     ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
650     IvarList = (*I); ++I;
651     for (curIvar = IvarList; I != E; curIvar = *I, ++I)
652       curIvar->setNextIvar(*I);
653   }
654 
655   for (const ObjCCategoryDecl *CDecl = getFirstClassExtension(); CDecl;
656        CDecl = CDecl->getNextClassExtension()) {
657     if (!CDecl->ivar_empty()) {
658       ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
659                                           E = CDecl->ivar_end();
660       if (!IvarList) {
661         IvarList = (*I); ++I;
662         curIvar = IvarList;
663       }
664       for ( ;I != E; curIvar = *I, ++I)
665         curIvar->setNextIvar(*I);
666     }
667   }
668 
669   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
670     if (!ImplDecl->ivar_empty()) {
671       ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
672                                             E = ImplDecl->ivar_end();
673       if (!IvarList) {
674         IvarList = (*I); ++I;
675         curIvar = IvarList;
676       }
677       for ( ;I != E; curIvar = *I, ++I)
678         curIvar->setNextIvar(*I);
679     }
680   }
681   return IvarList;
682 }
683 
684 /// FindCategoryDeclaration - Finds category declaration in the list of
685 /// categories for this class and returns it. Name of the category is passed
686 /// in 'CategoryId'. If category not found, return 0;
687 ///
688 ObjCCategoryDecl *
689 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
690   if (ExternallyCompleted)
691     LoadExternalDefinition();
692 
693   for (ObjCCategoryDecl *Category = getCategoryList();
694        Category; Category = Category->getNextClassCategory())
695     if (Category->getIdentifier() == CategoryId)
696       return Category;
697   return 0;
698 }
699 
700 ObjCMethodDecl *
701 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
702   for (ObjCCategoryDecl *Category = getCategoryList();
703        Category; Category = Category->getNextClassCategory())
704     if (ObjCCategoryImplDecl *Impl = Category->getImplementation())
705       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
706         return MD;
707   return 0;
708 }
709 
710 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
711   for (ObjCCategoryDecl *Category = getCategoryList();
712        Category; Category = Category->getNextClassCategory())
713     if (ObjCCategoryImplDecl *Impl = Category->getImplementation())
714       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
715         return MD;
716   return 0;
717 }
718 
719 /// ClassImplementsProtocol - Checks that 'lProto' protocol
720 /// has been implemented in IDecl class, its super class or categories (if
721 /// lookupCategory is true).
722 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
723                                     bool lookupCategory,
724                                     bool RHSIsQualifiedID) {
725   ObjCInterfaceDecl *IDecl = this;
726   // 1st, look up the class.
727   const ObjCList<ObjCProtocolDecl> &Protocols =
728   IDecl->getReferencedProtocols();
729 
730   for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
731        E = Protocols.end(); PI != E; ++PI) {
732     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
733       return true;
734     // This is dubious and is added to be compatible with gcc.  In gcc, it is
735     // also allowed assigning a protocol-qualified 'id' type to a LHS object
736     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
737     // object. This IMO, should be a bug.
738     // FIXME: Treat this as an extension, and flag this as an error when GCC
739     // extensions are not enabled.
740     if (RHSIsQualifiedID &&
741         getASTContext().ProtocolCompatibleWithProtocol(*PI, lProto))
742       return true;
743   }
744 
745   // 2nd, look up the category.
746   if (lookupCategory)
747     for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
748          CDecl = CDecl->getNextClassCategory()) {
749       for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
750            E = CDecl->protocol_end(); PI != E; ++PI)
751         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
752           return true;
753     }
754 
755   // 3rd, look up the super class(s)
756   if (IDecl->getSuperClass())
757     return
758   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
759                                                   RHSIsQualifiedID);
760 
761   return false;
762 }
763 
764 //===----------------------------------------------------------------------===//
765 // ObjCIvarDecl
766 //===----------------------------------------------------------------------===//
767 
768 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
769                                    SourceLocation StartLoc,
770                                    SourceLocation IdLoc, IdentifierInfo *Id,
771                                    QualType T, TypeSourceInfo *TInfo,
772                                    AccessControl ac, Expr *BW,
773                                    bool synthesized) {
774   if (DC) {
775     // Ivar's can only appear in interfaces, implementations (via synthesized
776     // properties), and class extensions (via direct declaration, or synthesized
777     // properties).
778     //
779     // FIXME: This should really be asserting this:
780     //   (isa<ObjCCategoryDecl>(DC) &&
781     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
782     // but unfortunately we sometimes place ivars into non-class extension
783     // categories on error. This breaks an AST invariant, and should not be
784     // fixed.
785     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
786             isa<ObjCCategoryDecl>(DC)) &&
787            "Invalid ivar decl context!");
788     // Once a new ivar is created in any of class/class-extension/implementation
789     // decl contexts, the previously built IvarList must be rebuilt.
790     ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(DC);
791     if (!ID) {
792       if (ObjCImplementationDecl *IM = dyn_cast<ObjCImplementationDecl>(DC)) {
793         ID = IM->getClassInterface();
794         if (BW)
795           IM->setHasSynthBitfield(true);
796       } else {
797         ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
798         ID = CD->getClassInterface();
799         if (BW)
800           CD->setHasSynthBitfield(true);
801       }
802     }
803     ID->setIvarList(0);
804   }
805 
806   return new (C) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo,
807                               ac, BW, synthesized);
808 }
809 
810 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
811   const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
812 
813   switch (DC->getKind()) {
814   default:
815   case ObjCCategoryImpl:
816   case ObjCProtocol:
817     llvm_unreachable("invalid ivar container!");
818 
819     // Ivars can only appear in class extension categories.
820   case ObjCCategory: {
821     const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
822     assert(CD->IsClassExtension() && "invalid container for ivar!");
823     return CD->getClassInterface();
824   }
825 
826   case ObjCImplementation:
827     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
828 
829   case ObjCInterface:
830     return cast<ObjCInterfaceDecl>(DC);
831   }
832 }
833 
834 //===----------------------------------------------------------------------===//
835 // ObjCAtDefsFieldDecl
836 //===----------------------------------------------------------------------===//
837 
838 ObjCAtDefsFieldDecl
839 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
840                              SourceLocation StartLoc,  SourceLocation IdLoc,
841                              IdentifierInfo *Id, QualType T, Expr *BW) {
842   return new (C) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
843 }
844 
845 //===----------------------------------------------------------------------===//
846 // ObjCProtocolDecl
847 //===----------------------------------------------------------------------===//
848 
849 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
850                                            SourceLocation L,
851                                            IdentifierInfo *Id) {
852   return new (C) ObjCProtocolDecl(DC, L, Id);
853 }
854 
855 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
856   ObjCProtocolDecl *PDecl = this;
857 
858   if (Name == getIdentifier())
859     return PDecl;
860 
861   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
862     if ((PDecl = (*I)->lookupProtocolNamed(Name)))
863       return PDecl;
864 
865   return NULL;
866 }
867 
868 // lookupMethod - Lookup a instance/class method in the protocol and protocols
869 // it inherited.
870 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
871                                                bool isInstance) const {
872   ObjCMethodDecl *MethodDecl = NULL;
873 
874   if ((MethodDecl = getMethod(Sel, isInstance)))
875     return MethodDecl;
876 
877   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
878     if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
879       return MethodDecl;
880   return NULL;
881 }
882 
883 //===----------------------------------------------------------------------===//
884 // ObjCClassDecl
885 //===----------------------------------------------------------------------===//
886 
887 ObjCClassDecl::ObjCClassDecl(DeclContext *DC, SourceLocation L,
888                              ObjCInterfaceDecl *const Elt,
889                              const SourceLocation Loc,
890                              ASTContext &C)
891   : Decl(ObjCClass, DC, L) {
892   setClass(C, Elt, Loc);
893 }
894 
895 ObjCClassDecl *ObjCClassDecl::Create(ASTContext &C, DeclContext *DC,
896                                      SourceLocation L,
897                                      ObjCInterfaceDecl *const Elt,
898                                      const SourceLocation Loc) {
899   return new (C) ObjCClassDecl(DC, L, Elt, Loc, C);
900 }
901 
902 void ObjCClassDecl::setClass(ASTContext &C, ObjCInterfaceDecl*const Cls,
903                              const SourceLocation Loc) {
904 
905   ForwardDecl = (ObjCClassRef*) C.Allocate(sizeof(ObjCClassRef),
906                                            llvm::alignOf<ObjCClassRef>());
907   new (ForwardDecl) ObjCClassRef(Cls, Loc);
908 }
909 
910 SourceRange ObjCClassDecl::getSourceRange() const {
911   // FIXME: We should include the semicolon
912   return SourceRange(getLocation(), ForwardDecl->getLocation());
913 }
914 
915 //===----------------------------------------------------------------------===//
916 // ObjCForwardProtocolDecl
917 //===----------------------------------------------------------------------===//
918 
919 ObjCForwardProtocolDecl::
920 ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L,
921                         ObjCProtocolDecl *const *Elts, unsigned nElts,
922                         const SourceLocation *Locs, ASTContext &C)
923 : Decl(ObjCForwardProtocol, DC, L) {
924   ReferencedProtocols.set(Elts, nElts, Locs, C);
925 }
926 
927 
928 ObjCForwardProtocolDecl *
929 ObjCForwardProtocolDecl::Create(ASTContext &C, DeclContext *DC,
930                                 SourceLocation L,
931                                 ObjCProtocolDecl *const *Elts,
932                                 unsigned NumElts,
933                                 const SourceLocation *Locs) {
934   return new (C) ObjCForwardProtocolDecl(DC, L, Elts, NumElts, Locs, C);
935 }
936 
937 //===----------------------------------------------------------------------===//
938 // ObjCCategoryDecl
939 //===----------------------------------------------------------------------===//
940 
941 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
942                                            SourceLocation AtLoc,
943                                            SourceLocation ClassNameLoc,
944                                            SourceLocation CategoryNameLoc,
945                                            IdentifierInfo *Id,
946                                            ObjCInterfaceDecl *IDecl) {
947   ObjCCategoryDecl *CatDecl = new (C) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc,
948                                                        CategoryNameLoc, Id,
949                                                        IDecl);
950   if (IDecl) {
951     // Link this category into its class's category list.
952     CatDecl->NextClassCategory = IDecl->getCategoryList();
953     IDecl->setCategoryList(CatDecl);
954     if (ASTMutationListener *L = C.getASTMutationListener())
955       L->AddedObjCCategoryToInterface(CatDecl, IDecl);
956   }
957 
958   return CatDecl;
959 }
960 
961 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, EmptyShell Empty) {
962   return new (C) ObjCCategoryDecl(0, SourceLocation(), SourceLocation(),
963                                   SourceLocation(), 0, 0);
964 }
965 
966 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
967   return getASTContext().getObjCImplementation(
968                                            const_cast<ObjCCategoryDecl*>(this));
969 }
970 
971 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
972   getASTContext().setObjCImplementation(this, ImplD);
973 }
974 
975 
976 //===----------------------------------------------------------------------===//
977 // ObjCCategoryImplDecl
978 //===----------------------------------------------------------------------===//
979 
980 ObjCCategoryImplDecl *
981 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
982                              SourceLocation L,IdentifierInfo *Id,
983                              ObjCInterfaceDecl *ClassInterface) {
984   return new (C) ObjCCategoryImplDecl(DC, L, Id, ClassInterface);
985 }
986 
987 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
988   // The class interface might be NULL if we are working with invalid code.
989   if (const ObjCInterfaceDecl *ID = getClassInterface())
990     return ID->FindCategoryDeclaration(getIdentifier());
991   return 0;
992 }
993 
994 
995 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
996   // FIXME: The context should be correct before we get here.
997   property->setLexicalDeclContext(this);
998   addDecl(property);
999 }
1000 
1001 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
1002   ASTContext &Ctx = getASTContext();
1003 
1004   if (ObjCImplementationDecl *ImplD
1005         = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
1006     if (IFace)
1007       Ctx.setObjCImplementation(IFace, ImplD);
1008 
1009   } else if (ObjCCategoryImplDecl *ImplD =
1010              dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
1011     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
1012       Ctx.setObjCImplementation(CD, ImplD);
1013   }
1014 
1015   ClassInterface = IFace;
1016 }
1017 
1018 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
1019 /// properties implemented in this category @implementation block and returns
1020 /// the implemented property that uses it.
1021 ///
1022 ObjCPropertyImplDecl *ObjCImplDecl::
1023 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
1024   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
1025     ObjCPropertyImplDecl *PID = *i;
1026     if (PID->getPropertyIvarDecl() &&
1027         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
1028       return PID;
1029   }
1030   return 0;
1031 }
1032 
1033 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
1034 /// added to the list of those properties @synthesized/@dynamic in this
1035 /// category @implementation block.
1036 ///
1037 ObjCPropertyImplDecl *ObjCImplDecl::
1038 FindPropertyImplDecl(IdentifierInfo *Id) const {
1039   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
1040     ObjCPropertyImplDecl *PID = *i;
1041     if (PID->getPropertyDecl()->getIdentifier() == Id)
1042       return PID;
1043   }
1044   return 0;
1045 }
1046 
1047 raw_ostream &clang::operator<<(raw_ostream &OS,
1048                                      const ObjCCategoryImplDecl *CID) {
1049   OS << CID->getName();
1050   return OS;
1051 }
1052 
1053 //===----------------------------------------------------------------------===//
1054 // ObjCImplementationDecl
1055 //===----------------------------------------------------------------------===//
1056 
1057 ObjCImplementationDecl *
1058 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
1059                                SourceLocation L,
1060                                ObjCInterfaceDecl *ClassInterface,
1061                                ObjCInterfaceDecl *SuperDecl) {
1062   return new (C) ObjCImplementationDecl(DC, L, ClassInterface, SuperDecl);
1063 }
1064 
1065 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1066                                              CXXCtorInitializer ** initializers,
1067                                                  unsigned numInitializers) {
1068   if (numInitializers > 0) {
1069     NumIvarInitializers = numInitializers;
1070     CXXCtorInitializer **ivarInitializers =
1071     new (C) CXXCtorInitializer*[NumIvarInitializers];
1072     memcpy(ivarInitializers, initializers,
1073            numInitializers * sizeof(CXXCtorInitializer*));
1074     IvarInitializers = ivarInitializers;
1075   }
1076 }
1077 
1078 raw_ostream &clang::operator<<(raw_ostream &OS,
1079                                      const ObjCImplementationDecl *ID) {
1080   OS << ID->getName();
1081   return OS;
1082 }
1083 
1084 //===----------------------------------------------------------------------===//
1085 // ObjCCompatibleAliasDecl
1086 //===----------------------------------------------------------------------===//
1087 
1088 ObjCCompatibleAliasDecl *
1089 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
1090                                 SourceLocation L,
1091                                 IdentifierInfo *Id,
1092                                 ObjCInterfaceDecl* AliasedClass) {
1093   return new (C) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
1094 }
1095 
1096 //===----------------------------------------------------------------------===//
1097 // ObjCPropertyDecl
1098 //===----------------------------------------------------------------------===//
1099 
1100 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
1101                                            SourceLocation L,
1102                                            IdentifierInfo *Id,
1103                                            SourceLocation AtLoc,
1104                                            TypeSourceInfo *T,
1105                                            PropertyControl propControl) {
1106   return new (C) ObjCPropertyDecl(DC, L, Id, AtLoc, T);
1107 }
1108 
1109 //===----------------------------------------------------------------------===//
1110 // ObjCPropertyImplDecl
1111 //===----------------------------------------------------------------------===//
1112 
1113 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
1114                                                    DeclContext *DC,
1115                                                    SourceLocation atLoc,
1116                                                    SourceLocation L,
1117                                                    ObjCPropertyDecl *property,
1118                                                    Kind PK,
1119                                                    ObjCIvarDecl *ivar,
1120                                                    SourceLocation ivarLoc) {
1121   return new (C) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
1122                                       ivarLoc);
1123 }
1124 
1125 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
1126   SourceLocation EndLoc = getLocation();
1127   if (IvarLoc.isValid())
1128     EndLoc = IvarLoc;
1129 
1130   return SourceRange(AtLoc, EndLoc);
1131 }
1132