2004-09-24 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / corlib / System / MonoCustomAttrs.cs
1 // System.MonoCustomAttrs.cs
2 // Hooks into the runtime to get custom attributes for reflection handles
3 //
4 // Authors:
5 //      Paolo Molaro (lupus@ximian.com)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
9 //
10
11 //
12 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System;
35 using System.Reflection;
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38
39 namespace System
40 {
41         internal class MonoCustomAttrs
42         {
43                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
44                 internal static extern object[] GetCustomAttributesInternal (ICustomAttributeProvider obj, bool pseudoAttrs);
45
46                 internal static object[] GetCustomAttributesBase (ICustomAttributeProvider obj)
47                 {
48                         object[] attrs = GetCustomAttributesInternal (obj, false);
49
50 #if NET_2_0 || BOOTSTRAP_NET_2_0
51                         object[] pseudoAttrs = null;
52
53                         /* FIXME: Add other types */
54                         if (obj is Type)
55                                 pseudoAttrs = ((Type)obj).GetPseudoCustomAttributes ();
56                         else if (obj is MonoMethod)
57                                 pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes ();
58                         else if (obj is FieldInfo)
59                                 pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes ();
60
61                         if (pseudoAttrs != null) {
62                                 object[] res = new object [attrs.Length + pseudoAttrs.Length];
63                                 System.Array.Copy (attrs, res, attrs.Length);
64                                 System.Array.Copy (pseudoAttrs, 0, res, attrs.Length, pseudoAttrs.Length);
65                                 return res;
66                         }
67                         else
68                                 return attrs;
69 #else
70                         return attrs;
71 #endif
72                 }
73
74                 internal static Attribute GetCustomAttribute (ICustomAttributeProvider obj,
75                                                                 Type attributeType,
76                                                                 bool inherit)
77                 {
78                         object[] res = GetCustomAttributes (obj, attributeType, inherit);
79                         if (res.Length == 0)
80                         {
81                                 return null;
82                         }
83                         else if (res.Length > 1)
84                         {
85                                 string msg = "'{0}' has more than one attribute of type '{1}";
86                                 msg = String.Format (msg, obj, attributeType);
87                                 throw new AmbiguousMatchException (msg);
88                         }
89
90                         return (Attribute) res[0];
91                 }
92
93                 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit)
94                 {
95                         if (obj == null)
96                                 throw new ArgumentNullException ("obj");
97
98                         object[] r;
99                         object[] res = GetCustomAttributesBase (obj);
100                         // shortcut
101                         if (!inherit && res.Length == 1)
102                         {
103                                 if (attributeType != null)
104                                 {
105                                         if (attributeType.IsAssignableFrom (res[0].GetType ()))
106                                         {
107                                                 r = (object[]) Array.CreateInstance (attributeType, 1);
108                                                 r[0] = res[0];
109                                         }
110                                         else
111                                         {
112                                                 r = (object[]) Array.CreateInstance (attributeType, 0);
113                                         }
114                                 }
115                                 else
116                                 {
117                                         r = (object[]) Array.CreateInstance (res[0].GetType (), 1);
118                                         r[0] = res[0];
119                                 }
120                                 return r;
121                         }
122
123                         // if AttributeType is sealed, and Inherited is set to false, then 
124                         // there's no use in scanning base types 
125                         if ((attributeType != null && attributeType.IsSealed) && inherit)
126                         {
127                                 AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage (
128                                         attributeType);
129                                 if (!usageAttribute.Inherited)
130                                 {
131                                         inherit = false;
132                                 }
133                         }
134
135                         int initialSize = res.Length < 16 ? res.Length : 16;
136
137                         Hashtable attributeInfos = new Hashtable (initialSize);
138                         ArrayList a = new ArrayList (initialSize);
139                         ICustomAttributeProvider btype = obj;
140
141                         int inheritanceLevel = 0;
142
143                         do
144                         {
145                                 foreach (object attr in res)
146                                 {
147                                         AttributeUsageAttribute usage;
148
149                                         Type attrType = attr.GetType ();
150                                         if (attributeType != null)
151                                         {
152                                                 if (!attributeType.IsAssignableFrom (attrType))
153                                                 {
154                                                         continue;
155                                                 }
156                                         }
157
158                                         AttributeInfo firstAttribute = (AttributeInfo) attributeInfos[attrType];
159                                         if (firstAttribute != null)
160                                         {
161                                                 usage = firstAttribute.Usage;
162                                         }
163                                         else
164                                         {
165                                                 usage = RetrieveAttributeUsage (attrType);
166                                         }
167
168                                         // only add attribute to the list of attributes if 
169                                         // - we are on the first inheritance level, or the attribute can be inherited anyway
170                                         // and (
171                                         // - multiple attributes of the type are allowed
172                                         // or (
173                                         // - this is the first attribute we've discovered
174                                         // or
175                                         // - the attribute is on same inheritance level than the first 
176                                         //   attribute that was discovered for this attribute type ))
177                                         if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple || 
178                                                 (firstAttribute == null || (firstAttribute != null 
179                                                         && firstAttribute.InheritanceLevel == inheritanceLevel))))
180                                         {
181                                                 a.Add (attr);
182                                         }
183
184                                         if (firstAttribute == null)
185                                         {
186                                                 attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel));
187                                         }
188                                 }
189
190                                 if ((btype = GetBase (btype)) != null)
191                                 {
192                                         inheritanceLevel++;
193                                         res = GetCustomAttributesBase (btype);
194                                 }
195                         } while (inherit && btype != null);
196
197                         object[] array = null;
198                         if (attributeType == null || attributeType.IsValueType)
199                         {
200                                 array = (object[]) Array.CreateInstance (typeof(Attribute), a.Count);
201                         }
202                         else
203                         {
204                                 array = Array.CreateInstance (attributeType, a.Count) as object[];
205                         }
206
207                         // copy attributes to array
208                         a.CopyTo (array, 0);
209
210                         return array;
211                 }
212
213                 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit)
214                 {
215                         if (obj == null)
216                                 throw new ArgumentNullException ("obj");
217
218                         if (!inherit)
219                                 return (object[]) GetCustomAttributesBase (obj).Clone ();
220
221                         return GetCustomAttributes (obj, null, inherit);
222                 }
223
224                 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit)
225                 {
226                         object [] res = GetCustomAttributesBase (obj);
227                         foreach (object attr in res)
228                                 if (attributeType.Equals (attr.GetType ()))
229                                         return true;
230
231                         ICustomAttributeProvider btype;
232                         if (inherit && ((btype = GetBase (obj)) != null))
233                                 return IsDefined (btype, attributeType, inherit);
234
235                         return false;
236                 }
237
238                 // Handles Type, MonoProperty and MonoMethod.
239                 // The runtime has also cases for MonoEvent, MonoField, Assembly and ParameterInfo,
240                 // but for those we return null here.
241                 static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj)
242                 {
243                         if (obj == null)
244                                 return null;
245
246                         if (obj is Type)
247                                 return ((Type) obj).BaseType;
248
249                         MethodInfo method = null;
250                         if (obj is MonoProperty)
251                         {
252                                 MonoProperty prop = (MonoProperty) obj;
253                                 method = prop.GetGetMethod (true);
254                                 if (method == null)
255                                         method = prop.GetSetMethod (true);
256                         }
257                         else if (obj is MonoMethod)
258                         {
259                                 method = (MethodInfo) obj;
260                         }
261
262                         /**
263                          * ParameterInfo -> null
264                          * Assembly -> null
265                          * MonoEvent -> null
266                          * MonoField -> null
267                          */
268                         if (method == null || !method.IsVirtual)
269                                 return null;
270
271                         MethodInfo baseMethod = method.GetBaseDefinition ();
272                         if (baseMethod == method)
273                                 return null;
274
275                         return baseMethod;
276                 }
277
278                 private static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType)
279                 {
280                         if (attributeType == typeof (AttributeUsageAttribute))
281                                 /* Avoid endless recursion */
282                                 return new AttributeUsageAttribute (AttributeTargets.Class);
283
284                         AttributeUsageAttribute usageAttribute = null;
285                         object[] attribs = GetCustomAttributes (attributeType,
286                                 MonoCustomAttrs.AttributeUsageType, false);
287                         if (attribs.Length == 0)
288                         {
289                                 // if no AttributeUsage was defined on the attribute level, then
290                                 // try to retrieve if from its base type
291                                 if (attributeType.BaseType != null)
292                                 {
293                                         usageAttribute = RetrieveAttributeUsage (attributeType.BaseType);
294
295                                 }
296                                 if (usageAttribute != null)
297                                 {
298                                         // return AttributeUsage of base class
299                                         return usageAttribute;
300
301                                 }
302                                 // return default AttributeUsageAttribute if no AttributeUsage 
303                                 // was defined on attribute, or its base class
304                                 return DefaultAttributeUsage;
305                         }
306                         // check if more than one AttributeUsageAttribute has been specified 
307                         // on the type
308                         // NOTE: compilers should prevent this, but that doesn't prevent
309                         // anyone from using IL ofcourse
310                         if (attribs.Length > 1)
311                         {
312                                 throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type.");
313                         }
314
315                         return ((AttributeUsageAttribute) attribs[0]);
316                 }
317
318                 private static readonly Type AttributeUsageType = typeof(AttributeUsageAttribute);
319                 private static readonly AttributeUsageAttribute DefaultAttributeUsage =
320                         new AttributeUsageAttribute (AttributeTargets.All);
321
322                 private class AttributeInfo
323                 {
324                         private AttributeUsageAttribute _usage;
325                         private int _inheritanceLevel;
326
327                         public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel)
328                         {
329                                 _usage = usage;
330                                 _inheritanceLevel = inheritanceLevel;
331                         }
332
333                         public AttributeUsageAttribute Usage
334                         {
335                                 get
336                                 {
337                                         return _usage;
338                                 }
339                         }
340
341                         public int InheritanceLevel
342                         {
343                                 get
344                                 {
345                                         return _inheritanceLevel;
346                                 }
347                         }
348                 }
349         }
350 }
351