New test.
[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 #if  NET_2_0
40 using System.Collections.Generic;
41 #endif
42
43 namespace System
44 {
45         internal class MonoCustomAttrs
46         {
47                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
48                 internal static extern object[] GetCustomAttributesInternal (ICustomAttributeProvider obj, Type attributeType, bool pseudoAttrs);
49
50                 internal static object[] GetPseudoCustomAttributes (ICustomAttributeProvider obj, Type attributeType) {
51 #if NET_2_0 || BOOTSTRAP_NET_2_0
52                         object[] pseudoAttrs = null;
53
54                         /* FIXME: Add other types */
55                         if (obj is MonoMethod)
56                                 pseudoAttrs = ((MonoMethod)obj).GetPseudoCustomAttributes ();
57                         else if (obj is FieldInfo)
58                                 pseudoAttrs = ((FieldInfo)obj).GetPseudoCustomAttributes ();
59                         else if (obj is ParameterInfo)
60                                 pseudoAttrs = ((ParameterInfo)obj).GetPseudoCustomAttributes ();
61                         else if (obj is Type)
62                                 pseudoAttrs = ((Type)obj).GetPseudoCustomAttributes ();
63
64                         if ((attributeType != null) && (pseudoAttrs != null)) {
65                                 for (int i = 0; i < pseudoAttrs.Length; ++i)
66                                         if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
67                                                 if (pseudoAttrs.Length == 1)
68                                                         return pseudoAttrs;
69                                                 else
70                                                         return new object [] { pseudoAttrs [i] };
71                                 return new object [0];
72                         }
73                         else
74                                 return pseudoAttrs;
75 #else
76                         return null;
77 #endif
78                 }
79
80                 internal static object[] GetCustomAttributesBase (ICustomAttributeProvider obj, Type attributeType)
81                 {
82                         object[] attrs = GetCustomAttributesInternal (obj, attributeType, false);
83
84                         object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
85                         if (pseudoAttrs != null) {
86                                 object[] res = new object [attrs.Length + pseudoAttrs.Length];
87                                 System.Array.Copy (attrs, res, attrs.Length);
88                                 System.Array.Copy (pseudoAttrs, 0, res, attrs.Length, pseudoAttrs.Length);
89                                 return res;
90                         }
91                         else
92                                 return attrs;
93                 }
94
95                 internal static Attribute GetCustomAttribute (ICustomAttributeProvider obj,
96                                                                 Type attributeType,
97                                                                 bool inherit)
98                 {
99                         object[] res = GetCustomAttributes (obj, attributeType, inherit);
100                         if (res.Length == 0)
101                         {
102                                 return null;
103                         }
104                         else if (res.Length > 1)
105                         {
106                                 string msg = "'{0}' has more than one attribute of type '{1}";
107                                 msg = String.Format (msg, obj, attributeType);
108                                 throw new AmbiguousMatchException (msg);
109                         }
110
111                         return (Attribute) res[0];
112                 }
113
114                 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, Type attributeType, bool inherit)
115                 {
116                         if (obj == null)
117                                 throw new ArgumentNullException ("obj");
118
119                         object[] r;
120                         object[] res = GetCustomAttributesBase (obj, attributeType);
121                         // shortcut
122                         if (!inherit && res.Length == 1)
123                         {
124                                 if (attributeType != null)
125                                 {
126                                         if (attributeType.IsAssignableFrom (res[0].GetType ()))
127                                         {
128                                                 r = (object[]) Array.CreateInstance (attributeType, 1);
129                                                 r[0] = res[0];
130                                         }
131                                         else
132                                         {
133                                                 r = (object[]) Array.CreateInstance (attributeType, 0);
134                                         }
135                                 }
136                                 else
137                                 {
138                                         r = (object[]) Array.CreateInstance (res[0].GetType (), 1);
139                                         r[0] = res[0];
140                                 }
141                                 return r;
142                         }
143
144                         // if AttributeType is sealed, and Inherited is set to false, then 
145                         // there's no use in scanning base types 
146                         if ((attributeType != null && attributeType.IsSealed) && inherit)
147                         {
148                                 AttributeUsageAttribute usageAttribute = RetrieveAttributeUsage (
149                                         attributeType);
150                                 if (!usageAttribute.Inherited)
151                                 {
152                                         inherit = false;
153                                 }
154                         }
155
156                         int initialSize = res.Length < 16 ? res.Length : 16;
157
158                         Hashtable attributeInfos = new Hashtable (initialSize);
159                         ArrayList a = new ArrayList (initialSize);
160                         ICustomAttributeProvider btype = obj;
161
162                         int inheritanceLevel = 0;
163
164                         do
165                         {
166                                 foreach (object attr in res)
167                                 {
168                                         AttributeUsageAttribute usage;
169
170                                         Type attrType = attr.GetType ();
171                                         if (attributeType != null)
172                                         {
173                                                 if (!attributeType.IsAssignableFrom (attrType))
174                                                 {
175                                                         continue;
176                                                 }
177                                         }
178
179                                         AttributeInfo firstAttribute = (AttributeInfo) attributeInfos[attrType];
180                                         if (firstAttribute != null)
181                                         {
182                                                 usage = firstAttribute.Usage;
183                                         }
184                                         else
185                                         {
186                                                 usage = RetrieveAttributeUsage (attrType);
187                                         }
188
189                                         // only add attribute to the list of attributes if 
190                                         // - we are on the first inheritance level, or the attribute can be inherited anyway
191                                         // and (
192                                         // - multiple attributes of the type are allowed
193                                         // or (
194                                         // - this is the first attribute we've discovered
195                                         // or
196                                         // - the attribute is on same inheritance level than the first 
197                                         //   attribute that was discovered for this attribute type ))
198                                         if ((inheritanceLevel == 0 || usage.Inherited) && (usage.AllowMultiple || 
199                                                 (firstAttribute == null || (firstAttribute != null 
200                                                         && firstAttribute.InheritanceLevel == inheritanceLevel))))
201                                         {
202                                                 a.Add (attr);
203                                         }
204
205                                         if (firstAttribute == null)
206                                         {
207                                                 attributeInfos.Add (attrType, new AttributeInfo (usage, inheritanceLevel));
208                                         }
209                                 }
210
211                                 if ((btype = GetBase (btype)) != null)
212                                 {
213                                         inheritanceLevel++;
214                                         res = GetCustomAttributesBase (btype, attributeType);
215                                 }
216                         } while (inherit && btype != null);
217
218                         object[] array = null;
219                         if (attributeType == null || attributeType.IsValueType)
220                         {
221                                 array = (object[]) Array.CreateInstance (typeof(Attribute), a.Count);
222                         }
223                         else
224                         {
225                                 array = Array.CreateInstance (attributeType, a.Count) as object[];
226                         }
227
228                         // copy attributes to array
229                         a.CopyTo (array, 0);
230
231                         return array;
232                 }
233
234                 internal static object[] GetCustomAttributes (ICustomAttributeProvider obj, bool inherit)
235                 {
236                         if (obj == null)
237                                 throw new ArgumentNullException ("obj");
238
239                         if (!inherit)
240                                 return (object[]) GetCustomAttributesBase (obj, null).Clone ();
241
242                         return GetCustomAttributes (obj, null, inherit);
243                 }
244
245 #if NET_2_0
246                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
247                 static extern CustomAttributeData [] GetCustomAttributesDataInternal (ICustomAttributeProvider obj);
248
249                 internal static IList<CustomAttributeData> GetCustomAttributesData (ICustomAttributeProvider obj)
250                 {
251                         if (obj == null)
252                                 throw new ArgumentNullException ("obj");
253
254                         CustomAttributeData [] attrs = GetCustomAttributesDataInternal (obj);
255                         return Array.AsReadOnly<CustomAttributeData> (attrs);
256                 }
257 #endif
258
259                 internal static bool IsDefined (ICustomAttributeProvider obj, Type attributeType, bool inherit)
260                 {
261                         if (obj.GetType ().Assembly != typeof (int).Assembly)
262                                 // User types might overwrite GetCustomAttributes () but not 
263                                 // IsDefined ().
264                                 return obj.GetCustomAttributes (attributeType, inherit).Length > 0;
265
266                         if (IsDefinedInternal (obj, attributeType))
267                                 return true;
268
269                         object[] pseudoAttrs = GetPseudoCustomAttributes (obj, attributeType);
270                         if (pseudoAttrs != null) {
271                                 for (int i = 0; i < pseudoAttrs.Length; ++i)
272                                         if (attributeType.IsAssignableFrom (pseudoAttrs [i].GetType ()))
273                                                 return true;
274                         }
275
276                         ICustomAttributeProvider btype;
277                         if (inherit && ((btype = GetBase (obj)) != null))
278                                 return IsDefined (btype, attributeType, inherit);
279
280                         return false;
281                 }
282
283                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
284                 internal static extern bool IsDefinedInternal (ICustomAttributeProvider obj, Type AttributeType);
285
286                 // Handles Type, MonoProperty and MonoMethod.
287                 // The runtime has also cases for MonoEvent, MonoField, Assembly and ParameterInfo,
288                 // but for those we return null here.
289                 static ICustomAttributeProvider GetBase (ICustomAttributeProvider obj)
290                 {
291                         if (obj == null)
292                                 return null;
293
294                         if (obj is Type)
295                                 return ((Type) obj).BaseType;
296
297                         MethodInfo method = null;
298                         if (obj is MonoProperty)
299                         {
300                                 MonoProperty prop = (MonoProperty) obj;
301                                 method = prop.GetGetMethod (true);
302                                 if (method == null)
303                                         method = prop.GetSetMethod (true);
304                         }
305                         else if (obj is MonoMethod)
306                         {
307                                 method = (MethodInfo) obj;
308                         }
309
310                         /**
311                          * ParameterInfo -> null
312                          * Assembly -> null
313                          * MonoEvent -> null
314                          * MonoField -> null
315                          */
316                         if (method == null || !method.IsVirtual)
317                                 return null;
318
319                         MethodInfo baseMethod = method.GetBaseDefinition ();
320                         if (baseMethod == method)
321                                 return null;
322
323                         return baseMethod;
324                 }
325
326                 private static AttributeUsageAttribute RetrieveAttributeUsage (Type attributeType)
327                 {
328                         if (attributeType == typeof (AttributeUsageAttribute))
329                                 /* Avoid endless recursion */
330                                 return new AttributeUsageAttribute (AttributeTargets.Class);
331
332                         AttributeUsageAttribute usageAttribute = null;
333                         object[] attribs = GetCustomAttributes (attributeType,
334                                 MonoCustomAttrs.AttributeUsageType, false);
335                         if (attribs.Length == 0)
336                         {
337                                 // if no AttributeUsage was defined on the attribute level, then
338                                 // try to retrieve if from its base type
339                                 if (attributeType.BaseType != null)
340                                 {
341                                         usageAttribute = RetrieveAttributeUsage (attributeType.BaseType);
342
343                                 }
344                                 if (usageAttribute != null)
345                                 {
346                                         // return AttributeUsage of base class
347                                         return usageAttribute;
348
349                                 }
350                                 // return default AttributeUsageAttribute if no AttributeUsage 
351                                 // was defined on attribute, or its base class
352                                 return DefaultAttributeUsage;
353                         }
354                         // check if more than one AttributeUsageAttribute has been specified 
355                         // on the type
356                         // NOTE: compilers should prevent this, but that doesn't prevent
357                         // anyone from using IL ofcourse
358                         if (attribs.Length > 1)
359                         {
360                                 throw new FormatException ("Duplicate AttributeUsageAttribute cannot be specified on an attribute type.");
361                         }
362
363                         return ((AttributeUsageAttribute) attribs[0]);
364                 }
365
366                 private static readonly Type AttributeUsageType = typeof(AttributeUsageAttribute);
367                 private static readonly AttributeUsageAttribute DefaultAttributeUsage =
368                         new AttributeUsageAttribute (AttributeTargets.All);
369
370                 private class AttributeInfo
371                 {
372                         private AttributeUsageAttribute _usage;
373                         private int _inheritanceLevel;
374
375                         public AttributeInfo (AttributeUsageAttribute usage, int inheritanceLevel)
376                         {
377                                 _usage = usage;
378                                 _inheritanceLevel = inheritanceLevel;
379                         }
380
381                         public AttributeUsageAttribute Usage
382                         {
383                                 get
384                                 {
385                                         return _usage;
386                                 }
387                         }
388
389                         public int InheritanceLevel
390                         {
391                                 get
392                                 {
393                                         return _inheritanceLevel;
394                                 }
395                         }
396                 }
397         }
398 }
399