Reverted everything until 24 hours ago.
[mono.git] / mcs / gmcs / attribute.cs
1 //
2 // attribute.cs: Attribute Handler
3 //
4 // Author: Ravi Pratap (ravi@ximian.com)
5 //         Marek Safar (marek.safar@seznam.cz)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11 //
12
13 using System;
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
21 using System.Text;
22
23 namespace Mono.CSharp {
24
25         /// <summary>
26         ///   Base class for objects that can have Attributes applied to them.
27         /// </summary>
28         public abstract class Attributable {
29                 /// <summary>
30                 ///   Attributes for this type
31                 /// </summary>
32                 Attributes attributes;
33
34                 public Attributable(Attributes attrs)
35                 {
36                         attributes = attrs;
37                         if (attributes != null)
38                                 attributes.CheckTargets (this);
39                 }
40
41                 public Attributes OptAttributes 
42                 {
43                         get {
44                                 return attributes;
45                         }
46                         set {
47                                 attributes = value;
48                                 if (attributes != null)
49                                         attributes.CheckTargets (this);
50                         }
51                 }
52
53                 /// <summary>
54                 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
55                 /// </summary>
56                 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
57
58                 /// <summary>
59                 /// Returns one AttributeTarget for this element.
60                 /// </summary>
61                 public abstract AttributeTargets AttributeTargets { get; }
62
63                 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
64
65                 /// <summary>
66                 /// Gets list of valid attribute targets for explicit target declaration.
67                 /// The first array item is default target. Don't break this rule.
68                 /// </summary>
69                 public abstract string[] ValidAttributeTargets { get; }
70         };
71
72         public class Attribute {
73                 public readonly string ExplicitTarget;
74                 public AttributeTargets Target;
75
76                 public readonly string    Name;
77                 public readonly ArrayList Arguments;
78
79                 public readonly Location Location;
80
81                 public Type Type;
82                 
83                 // Is non-null if type is AttributeUsageAttribute
84                 AttributeUsageAttribute usage_attribute;
85
86                 public AttributeUsageAttribute UsageAttribute {
87                         get {
88                                 return usage_attribute;
89                         }
90                 }
91                 
92                 MethodImplOptions ImplOptions;
93                 UnmanagedType     UnmanagedType;
94                 CustomAttributeBuilder cb;
95         
96                 // non-null if named args present after Resolve () is called
97                 PropertyInfo [] prop_info_arr;
98                 FieldInfo [] field_info_arr;
99                 object [] field_values_arr;
100                 object [] prop_values_arr;
101                 object [] pos_values;
102
103                 static PtrHashtable usage_attr_cache = new PtrHashtable ();
104                 
105                 public Attribute (string target, string name, ArrayList args, Location loc)
106                 {
107                         Name = name;
108                         Arguments = args;
109                         Location = loc;
110                         ExplicitTarget = target;
111                 }
112
113                 void Error_InvalidNamedArgument (string name)
114                 {
115                         Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
116                                       "argument. Named attribute arguments must be fields which are not " +
117                                       "readonly, static or const, or read-write properties which are not static.");
118                 }
119
120                 static void Error_AttributeArgumentNotValid (Location loc)
121                 {
122                         Report.Error (182, loc,
123                                       "An attribute argument must be a constant expression, typeof " +
124                                       "expression or array creation expression");
125                 }
126
127                 static void Error_TypeParameterInAttribute (Location loc)
128                 {
129                         Report.Error (
130                                 -202, loc, "Can not use a type parameter in an attribute");
131                 }
132
133                 void Error_AttributeConstructorMismatch ()
134                 {
135                         Report.Error (-6, Location,
136                                       "Could not find a constructor for this argument list.");
137                 }
138
139                 /// <summary>
140                 ///   Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
141                 /// </summary>
142                 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
143                 {
144                         TypeExpr t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
145                         // FIXME: Shouldn't do this for quoted attributes: [@A]
146                         TypeExpr t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
147
148                         String err0616 = null;
149                         if (t1 != null && ! t1.IsAttribute) {
150                                 t1 = null;
151                                 err0616 = "'" + Name + "': is not an attribute class";
152                         }
153                         if (t2 != null && ! t2.IsAttribute) {
154                                 t2 = null;
155                                 err0616 = (err0616 != null) 
156                                         ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
157                                         : "'" + Name + "Attribute': is not an attribute class";
158                         }
159
160                         if (t1 != null && t2 != null) {
161                                 Report.Error(1614, Location, "'" + Name + "': is ambiguous; " 
162                                              + " use either '@" + Name + "' or '" + Name + "Attribute'");
163                                 return null;
164                         }
165                         if (t1 != null)
166                                 return t1.ResolveType (ec);
167                         if (t2 != null)
168                                 return t2.ResolveType (ec);
169                         if (err0616 != null) {
170                                 Report.Error (616, Location, err0616);
171                                 return null;
172                         }
173
174                         if (complain)
175                                 Report.Error (246, Location, 
176                                               "Could not find attribute '" + Name 
177                                               + "' (are you missing a using directive or an assembly reference ?)");
178                         return null;
179                 }
180
181                 public Type ResolveType (EmitContext ec, bool complain)
182                 {
183                         if (Type == null)
184                                 Type = CheckAttributeType (ec, complain);
185                         return Type;
186                 }
187
188                 /// <summary>
189                 ///   Validates the guid string
190                 /// </summary>
191                 bool ValidateGuid (string guid)
192                 {
193                         try {
194                                 new Guid (guid);
195                                 return true;
196                         } catch {
197                                 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
198                                 return false;
199                         }
200                 }
201
202                 string GetFullMemberName (string member)
203                 {
204                         return Type.FullName + '.' + member;
205                 }
206
207                 //
208                 // Given an expression, if the expression is a valid attribute-argument-expression
209                 // returns an object that can be used to encode it, or null on failure.
210                 //
211                 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
212                 {
213                         if (e is EnumConstant) {
214                                 result = e;
215                                 return true;
216                         }
217
218                         Constant constant = e as Constant;
219                         if (constant != null) {
220                                 if (e.Type != arg_type) {
221                                         constant = Const.ChangeType (loc, constant, arg_type);
222                                         if (constant == null) {
223                                                 result = null;
224                                                 Error_AttributeArgumentNotValid (loc);
225                                                 return false;
226                                         }
227                                 }
228                                 result = constant.GetValue ();
229                                 return true;
230                         } else if (e is TypeOf) {
231                                 result = ((TypeOf) e).TypeArg;
232                                 return true;
233                         } else if (e is ArrayCreation){
234                                 result =  ((ArrayCreation) e).EncodeAsAttribute ();
235                                 if (result != null)
236                                         return true;
237                         } else if (e is EmptyCast) {
238                                 Expression child = ((EmptyCast)e).Child;
239                                 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
240                         }
241
242                         result = null;
243                         Error_AttributeArgumentNotValid (loc);
244                         return false;
245                 }
246                 
247                 public CustomAttributeBuilder Resolve (EmitContext ec)
248                 {
249                         Type oldType = Type;
250                         
251                         // Sanity check.
252                         Type = CheckAttributeType (ec, true);
253
254                         if (oldType == null && Type == null)
255                                 return null;
256                         if (oldType != null && oldType != Type){
257                                 Report.Error (-27, Location,
258                                               "Attribute {0} resolved to different types at different times: {1} vs. {2}",
259                                               Name, oldType, Type);
260                                 return null;
261                         }
262
263                         if (Type.IsAbstract) {
264                                 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
265                                 return null;
266                         }
267
268                         bool MethodImplAttr = false;
269                         bool MarshalAsAttr = false;
270                         bool GuidAttr = false;
271                         bool usage_attr = false;
272
273                         bool DoCompares = true;
274
275                         //
276                         // If we are a certain special attribute, we
277                         // set the information accordingly
278                         //
279                         
280                         if (Type == TypeManager.attribute_usage_type)
281                                 usage_attr = true;
282                         else if (Type == TypeManager.methodimpl_attr_type)
283                                 MethodImplAttr = true;
284                         else if (Type == TypeManager.marshal_as_attr_type)
285                                 MarshalAsAttr = true;
286                         else if (Type == TypeManager.guid_attr_type)
287                                 GuidAttr = true;
288                         else
289                                 DoCompares = false;
290
291                         // Now we extract the positional and named arguments
292                         
293                         ArrayList pos_args = new ArrayList ();
294                         ArrayList named_args = new ArrayList ();
295                         int pos_arg_count = 0;
296                         
297                         if (Arguments != null) {
298                                 pos_args = (ArrayList) Arguments [0];
299                                 if (pos_args != null)
300                                         pos_arg_count = pos_args.Count;
301                                 if (Arguments.Count > 1)
302                                         named_args = (ArrayList) Arguments [1];
303                         }
304
305                         pos_values = new object [pos_arg_count];
306                         object[] real_pos_values = new object [pos_arg_count];
307
308                         //
309                         // First process positional arguments 
310                         //
311
312                         int i;
313                         for (i = 0; i < pos_arg_count; i++) {
314                                 Argument a = (Argument) pos_args [i];
315                                 Expression e;
316
317                                 if (!a.Resolve (ec, Location))
318                                         return null;
319
320                                 e = a.Expr;
321
322                                 object val;
323                                 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
324                                         return null;
325                                 
326                                 if (val is EnumConstant) {
327                                         EnumConstant econst = (EnumConstant) e;
328
329                                         pos_values [i] = val = econst.GetValue ();
330                                         real_pos_values [i] = econst.GetValueAsEnumType ();
331                                 } else {
332                                         real_pos_values [i] = pos_values [i] = val;
333                                 }
334
335                                 if (DoCompares){
336                                         if (usage_attr)
337                                                 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) val);
338                                         else if (MethodImplAttr)
339                                                 this.ImplOptions = (MethodImplOptions) val;
340                                         else if (GuidAttr){
341                                                 //
342                                                 // we will later check the validity of the type
343                                                 //
344                                                 if (val is string){
345                                                         if (!ValidateGuid ((string) val))
346                                                                 return null;
347                                                 }
348                                                 
349                                         } else if (MarshalAsAttr)
350                                                 this.UnmanagedType =
351                                                 (System.Runtime.InteropServices.UnmanagedType) val;
352                                 }
353                         }
354
355                         //
356                         // Now process named arguments
357                         //
358
359                         ArrayList field_infos = null;
360                         ArrayList prop_infos  = null;
361                         ArrayList field_values = null;
362                         ArrayList prop_values = null;
363
364                         if (named_args.Count > 0) {
365                                 field_infos = new ArrayList ();
366                                 prop_infos  = new ArrayList ();
367                                 field_values = new ArrayList ();
368                                 prop_values = new ArrayList ();
369                         }
370
371                         Hashtable seen_names = new Hashtable();
372                         
373                         for (i = 0; i < named_args.Count; i++) {
374                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
375                                 string member_name = (string) de.Key;
376                                 Argument a  = (Argument) de.Value;
377                                 Expression e;
378
379                                 if (seen_names.Contains(member_name)) {
380                                         Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
381                                         return null;
382                                 }                               
383                                 seen_names.Add(member_name, 1);
384                                 
385                                 if (!a.Resolve (ec, Location))
386                                         return null;
387
388                                 Expression member = Expression.MemberLookup (
389                                         ec, Type, member_name,
390                                         MemberTypes.Field | MemberTypes.Property,
391                                         BindingFlags.Public | BindingFlags.Instance,
392                                         Location);
393
394                                 if (member == null) {
395                                         member = Expression.MemberLookup (ec, Type, member_name,
396                                                 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
397                                                 Location);
398
399                                         if (member != null) {
400                                                 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
401                                                 return null;
402                                         }
403                                 }
404
405                                 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
406                                         Error_InvalidNamedArgument (member_name);
407                                         return null;
408                                 }
409
410                                 e = a.Expr;
411                                 if (e is TypeParameterExpr){
412                                         Error_TypeParameterInAttribute (Location);
413                                         return null;
414                                 }
415                                         
416                                 if (member is PropertyExpr) {
417                                         PropertyExpr pe = (PropertyExpr) member;
418                                         PropertyInfo pi = pe.PropertyInfo;
419
420                                         if (!pi.CanWrite || !pi.CanRead) {
421                                                 Report.SymbolRelatedToPreviousError (pi);
422                                                 Error_InvalidNamedArgument (member_name);
423                                                 return null;
424                                         }
425
426                                         object value;
427                                         if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
428                                                                 return null;
429                                                 
430                                                 if (usage_attribute != null) {
431                                                         if (member_name == "AllowMultiple")
432                                                         usage_attribute.AllowMultiple = (bool) value;
433                                                         if (member_name == "Inherited")
434                                                         usage_attribute.Inherited = (bool) value;
435                                         }
436                                         
437                                         prop_values.Add (value);
438                                         prop_infos.Add (pi);
439                                         
440                                 } else if (member is FieldExpr) {
441                                         FieldExpr fe = (FieldExpr) member;
442                                         FieldInfo fi = fe.FieldInfo;
443
444                                         if (fi.IsInitOnly) {
445                                                 Error_InvalidNamedArgument (member_name);
446                                                 return null;
447                                         }
448
449                                         object value;
450                                         if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
451                                                 return null;
452
453                                         field_values.Add (value);
454
455                                         field_infos.Add (fi);
456                                 }
457                         }
458
459                         Expression mg = Expression.MemberLookup (
460                                 ec, Type, ".ctor", MemberTypes.Constructor,
461                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
462                                 Location);
463
464                         if (mg == null) {
465                                 Error_AttributeConstructorMismatch ();
466                                 return null;
467                         }
468
469                         MethodBase constructor = Invocation.OverloadResolve (
470                                 ec, (MethodGroupExpr) mg, pos_args, false, Location);
471
472                         if (constructor == null) {
473                                 return null;
474                         }
475
476                         //
477                         // Now we perform some checks on the positional args as they
478                         // cannot be null for a constructor which expects a parameter
479                         // of type object
480                         //
481
482                         ParameterData pd = Invocation.GetParameterData (constructor);
483
484                         int group_in_params_array = Int32.MaxValue;
485                         int pc = pd.Count;
486                         if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
487                                 group_in_params_array = pc-1;
488
489                         for (int j = 0; j < pos_arg_count; ++j) {
490                                 Argument a = (Argument) pos_args [j];
491                                 
492                                 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
493                                         Error_AttributeArgumentNotValid (Location);
494                                         return null;
495                                 }
496
497                                 if (j < group_in_params_array)
498                                         continue;
499                                 
500                                 if (j == group_in_params_array){
501                                         object v = real_pos_values [j];
502                                         int count = pos_arg_count - j;
503
504                                         object [] array = new object [count];
505                                         real_pos_values [j] = array;
506                                         array [0] = v;
507                                 } else {
508                                         object [] array = (object []) real_pos_values [group_in_params_array];
509
510                                         array [j - group_in_params_array] = real_pos_values [j];
511                                 }
512                         }
513
514                         //
515                         // Adjust the size of the pos_values if it had params
516                         //
517                         if (group_in_params_array != Int32.MaxValue){
518                                 int argc = group_in_params_array+1;
519                                 object [] new_pos_values = new object [argc];
520
521                                 for (int p = 0; p < argc; p++)
522                                         new_pos_values [p] = real_pos_values [p];
523                                 real_pos_values = new_pos_values;
524                         }
525
526                         try {
527                                 if (named_args.Count > 0) {
528                                         prop_info_arr = new PropertyInfo [prop_infos.Count];
529                                         field_info_arr = new FieldInfo [field_infos.Count];
530                                         field_values_arr = new object [field_values.Count];
531                                         prop_values_arr = new object [prop_values.Count];
532
533                                         field_infos.CopyTo  (field_info_arr, 0);
534                                         field_values.CopyTo (field_values_arr, 0);
535
536                                         prop_values.CopyTo  (prop_values_arr, 0);
537                                         prop_infos.CopyTo   (prop_info_arr, 0);
538
539                                         cb = new CustomAttributeBuilder (
540                                                 (ConstructorInfo) constructor, real_pos_values,
541                                                 prop_info_arr, prop_values_arr,
542                                                 field_info_arr, field_values_arr);
543                                 }
544                                 else
545                                         cb = new CustomAttributeBuilder (
546                                                 (ConstructorInfo) constructor, real_pos_values);
547                         } catch (NullReferenceException) {
548                                 // 
549                                 // Don't know what to do here
550                                 //
551                                 Report.Warning (
552                                         -101, Location, "NullReferenceException while trying to create attribute." +
553                                         "Something's wrong!");
554                         } catch (Exception e) {
555                                 //
556                                 // Sample:
557                                 // using System.ComponentModel;
558                                 // [DefaultValue (CollectionChangeAction.Add)]
559                                 // class X { static void Main () {} }
560                                 //
561                                 Report.Warning (
562                                         -23, Location, "The compiler can not encode this attribute in .NET due to a bug in the .NET runtime. Try the Mono runtime. The exception was: " + e.Message);
563                         }
564                         
565                         return cb;
566                 }
567
568                 /// <summary>
569                 ///   Get a string containing a list of valid targets for the attribute 'attr'
570                 /// </summary>
571                 public string GetValidTargets ()
572                 {
573                         StringBuilder sb = new StringBuilder ();
574                         AttributeTargets targets = GetAttributeUsage ().ValidOn;
575
576                         if ((targets & AttributeTargets.Assembly) != 0)
577                                 sb.Append ("'assembly' ");
578
579                         if ((targets & AttributeTargets.Class) != 0)
580                                 sb.Append ("'class' ");
581
582                         if ((targets & AttributeTargets.Constructor) != 0)
583                                 sb.Append ("'constructor' ");
584
585                         if ((targets & AttributeTargets.Delegate) != 0)
586                                 sb.Append ("'delegate' ");
587
588                         if ((targets & AttributeTargets.Enum) != 0)
589                                 sb.Append ("'enum' ");
590
591                         if ((targets & AttributeTargets.Event) != 0)
592                                 sb.Append ("'event' ");
593
594                         if ((targets & AttributeTargets.Field) != 0)
595                                 sb.Append ("'field' ");
596
597                         if ((targets & AttributeTargets.Interface) != 0)
598                                 sb.Append ("'interface' ");
599
600                         if ((targets & AttributeTargets.Method) != 0)
601                                 sb.Append ("'method' ");
602
603                         if ((targets & AttributeTargets.Module) != 0)
604                                 sb.Append ("'module' ");
605
606                         if ((targets & AttributeTargets.Parameter) != 0)
607                                 sb.Append ("'parameter' ");
608
609                         if ((targets & AttributeTargets.Property) != 0)
610                                 sb.Append ("'property' ");
611
612                         if ((targets & AttributeTargets.ReturnValue) != 0)
613                                 sb.Append ("'return' ");
614
615                         if ((targets & AttributeTargets.Struct) != 0)
616                                 sb.Append ("'struct' ");
617
618                         return sb.ToString ();
619
620                 }
621
622                 /// <summary>
623                 /// Returns AttributeUsage attribute for this type
624                 /// </summary>
625                 public AttributeUsageAttribute GetAttributeUsage ()
626                 {
627                         AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
628                         if (ua != null)
629                                 return ua;
630
631                         Class attr_class = TypeManager.LookupClass (Type);
632
633                         if (attr_class == null) {
634                                 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
635                                 ua = (AttributeUsageAttribute)usage_attr [0];
636                                 usage_attr_cache.Add (Type, ua);
637                                 return ua;
638                         }
639                 
640                         return attr_class.AttributeUsage;
641                 }
642
643                 /// <summary>
644                 /// Returns custom name of indexer
645                 /// </summary>
646                 public string GetIndexerAttributeValue (EmitContext ec)
647                 {
648                         if (pos_values == null) {
649                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
650                                 // But because a lot of attribute class code must be rewritten will be better to wait...
651                                 Resolve (ec);
652                         }
653                         
654                         return pos_values [0] as string;
655                 }
656
657                 /// <summary>
658                 /// Returns condition of ConditionalAttribute
659                 /// </summary>
660                 public string GetConditionalAttributeValue (DeclSpace ds)
661                 {
662                         if (pos_values == null) {
663                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
664
665                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
666                                 // But because a lot of attribute class code must be rewritten will be better to wait...
667                                 Resolve (ec);
668                         }
669
670                         // Some error occurred
671                         if (pos_values [0] == null)
672                                 return null;
673
674                         return (string)pos_values [0];
675                 }
676
677                 /// <summary>
678                 /// Creates the instance of ObsoleteAttribute from this attribute instance
679                 /// </summary>
680                 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
681                 {
682                         if (pos_values == null) {
683                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
684
685                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
686                                 // But because a lot of attribute class code must be rewritten will be better to wait...
687                                 Resolve (ec);
688                         }
689
690                         // Some error occurred
691                         if (pos_values == null)
692                                 return null;
693
694                         if (pos_values.Length == 0)
695                                 return new ObsoleteAttribute ();
696
697                         if (pos_values.Length == 1)
698                                 return new ObsoleteAttribute ((string)pos_values [0]);
699
700                         return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
701                 }
702
703                 /// <summary>
704                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
705                 /// before ApplyAttribute. We need to resolve the arguments.
706                 /// This situation occurs when class deps is differs from Emit order.  
707                 /// </summary>
708                 public bool GetClsCompliantAttributeValue (DeclSpace ds)
709                 {
710                         if (pos_values == null) {
711                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
712
713                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
714                                 // But because a lot of attribute class code must be rewritten will be better to wait...
715                                 Resolve (ec);
716                         }
717
718                         // Some error occurred
719                         if (pos_values [0] == null)
720                                 return false;
721
722                         return (bool)pos_values [0];
723                 }
724
725                 object GetValue (object value)
726                 {
727                         if (value is EnumConstant)
728                                 return ((EnumConstant) value).GetValue ();
729                         else
730                                 return value;                           
731                 }
732
733                 public object GetPositionalValue (int i)
734                 {
735                         return (pos_values == null) ? null : pos_values[i];
736                 }
737
738                 object GetFieldValue (string name)
739                 {
740                         int i;
741                         if (field_info_arr == null)
742                                 return null;
743                         i = 0;
744                         foreach (FieldInfo fi in field_info_arr) {
745                                 if (fi.Name == name)
746                                         return GetValue (field_values_arr [i]);
747                                 i++;
748                         }
749                         return null;
750                 }
751
752                 public UnmanagedMarshal GetMarshal ()
753                 {
754                         object o = GetFieldValue ("ArraySubType");
755                         UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
756                         
757                         switch (UnmanagedType) {
758                         case UnmanagedType.CustomMarshaler:
759                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
760                                                                        BindingFlags.Static | BindingFlags.Public);
761                                 if (define_custom == null)
762                                         return null;
763                                 
764                                 object [] args = new object [4];
765                                 args [0] = GetFieldValue ("MarshalTypeRef");
766                                 args [1] = GetFieldValue ("MarshalCookie");
767                                 args [2] = GetFieldValue ("MarshalType");
768                                 args [3] = Guid.Empty;
769                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
770                                 
771                         case UnmanagedType.LPArray:                             
772                                 return UnmanagedMarshal.DefineLPArray (array_sub_type);
773                         
774                         case UnmanagedType.SafeArray:
775                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
776                         
777                         case UnmanagedType.ByValArray:
778                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
779                         
780                         case UnmanagedType.ByValTStr:
781                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
782                         
783                         default:
784                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
785                         }
786                 }
787
788                 public bool IsInternalCall
789                 {
790                         get { return ImplOptions == MethodImplOptions.InternalCall; }
791                 }
792
793                 /// <summary>
794                 /// Emit attribute for Attributable symbol
795                 /// </summary>
796                 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
797                 {
798                         CustomAttributeBuilder cb = Resolve (ec);
799                         if (cb == null)
800                                 return;
801
802                         AttributeUsageAttribute usage_attr = GetAttributeUsage ();
803                         if ((usage_attr.ValidOn & Target) == 0) {
804                                 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
805                                 return;
806                         }
807
808                         ias.ApplyAttributeBuilder (this, cb);
809
810                         if (!usage_attr.AllowMultiple) {
811                                 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
812                                 if (emitted_targets == null) {
813                                         emitted_targets = new ArrayList ();
814                                         emitted_attr.Add (Type, emitted_targets);
815                                 } else if (emitted_targets.Contains (Target)) {
816                                 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
817                                         return;
818                                 }
819                                 emitted_targets.Add (Target);
820                         }
821
822                         if (!RootContext.VerifyClsCompliance)
823                                 return;
824
825                         // Here we are testing attribute arguments for array usage (error 3016)
826                         if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
827                                 if (Arguments == null)
828                                         return;
829
830                                 ArrayList pos_args = (ArrayList) Arguments [0];
831                                 if (pos_args != null) {
832                                         foreach (Argument arg in pos_args) { 
833                                                 // Type is undefined (was error 246)
834                                                 if (arg.Type == null)
835                                                         return;
836
837                                                 if (arg.Type.IsArray) {
838                                                         Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
839                                                         return;
840                                                 }
841                                         }
842                                 }
843                         
844                                 if (Arguments.Count < 2)
845                                         return;
846                         
847                                 ArrayList named_args = (ArrayList) Arguments [1];
848                                 foreach (DictionaryEntry de in named_args) {
849                                         Argument arg  = (Argument) de.Value;
850
851                                         // Type is undefined (was error 246)
852                                         if (arg.Type == null)
853                                                 return;
854
855                                         if (arg.Type.IsArray) {
856                                                 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
857                                                 return;
858                                         }
859                                 }
860                         }
861                 }
862
863                 public object GetValue (EmitContext ec, Constant c, Type target)
864                 {
865                         if (Convert.ImplicitConversionExists (ec, c, target))
866                                 return c.GetValue ();
867
868                         Convert.Error_CannotImplicitConversion (Location, c.Type, target);
869                         return null;
870                 }
871                 
872                 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
873                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
874                 {
875                         //
876                         // We extract from the attribute the information we need 
877                         //
878
879                         if (Arguments == null) {
880                                 Console.WriteLine ("Internal error : this is not supposed to happen !");
881                                 return null;
882                         }
883
884                         ResolveType (ec, true);
885                         if (Type == null)
886                                 return null;
887                         
888                         ArrayList named_args = new ArrayList ();
889                         
890                         ArrayList pos_args = (ArrayList) Arguments [0];
891                         if (Arguments.Count > 1)
892                                 named_args = (ArrayList) Arguments [1];
893                         
894
895                         string dll_name = null;
896                         
897                         Argument tmp = (Argument) pos_args [0];
898
899                         if (!tmp.Resolve (ec, Location))
900                                 return null;
901                         
902                         if (tmp.Expr is Constant)
903                                 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
904                         else { 
905                                 Error_AttributeArgumentNotValid (Location);
906                                 return null;
907                         }
908
909                         // Now we process the named arguments
910                         CallingConvention cc = CallingConvention.Winapi;
911                         CharSet charset = CharSet.Ansi;
912                         bool preserve_sig = true;
913 #if FIXME
914                         bool exact_spelling = false;
915 #endif
916                         bool set_last_err = false;
917                         string entry_point = null;
918
919                         for (int i = 0; i < named_args.Count; i++) {
920
921                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
922
923                                 string member_name = (string) de.Key;
924                                 Argument a  = (Argument) de.Value;
925
926                                 if (!a.Resolve (ec, Location))
927                                         return null;
928
929                                 Expression member = Expression.MemberLookup (
930                                         ec, Type, member_name, 
931                                         MemberTypes.Field | MemberTypes.Property,
932                                         BindingFlags.Public | BindingFlags.Instance,
933                                         Location);
934
935                                 if (member == null || !(member is FieldExpr)) {
936                                         Error_InvalidNamedArgument (member_name);
937                                         return null;
938                                 }
939
940                                 if (member is FieldExpr) {
941                                         FieldExpr fe = (FieldExpr) member;
942                                         FieldInfo fi = fe.FieldInfo;
943
944                                         if (fi.IsInitOnly) {
945                                                 Error_InvalidNamedArgument (member_name);
946                                                 return null;
947                                         }
948
949                                         if (a.Expr is Constant) {
950                                                 Constant c = (Constant) a.Expr;
951
952                                                 try {
953                                                         if (member_name == "CallingConvention"){
954                                                                 object val = GetValue (ec, c, typeof (CallingConvention));
955                                                                 if (val == null)
956                                                                         return null;
957                                                                 cc = (CallingConvention) val;
958                                                         } else if (member_name == "CharSet"){
959                                                                 charset = (CharSet) c.GetValue ();
960                                                         } else if (member_name == "EntryPoint")
961                                                                 entry_point = (string) c.GetValue ();
962                                                         else if (member_name == "SetLastError")
963                                                                 set_last_err = (bool) c.GetValue ();
964 #if FIXME
965                                                         else if (member_name == "ExactSpelling")
966                                                                 exact_spelling = (bool) c.GetValue ();
967 #endif
968                                                         else if (member_name == "PreserveSig")
969                                                                 preserve_sig = (bool) c.GetValue ();
970                                                 } catch (InvalidCastException){
971                                                         Error_InvalidNamedArgument (member_name);
972                                                         Error_AttributeArgumentNotValid (Location);
973                                                 }
974                                         } else { 
975                                                 Error_AttributeArgumentNotValid (Location);
976                                                 return null;
977                                         }
978                                         
979                                 }
980                         }
981
982                         if (entry_point == null)
983                                 entry_point = name;
984                         if (set_last_err)
985                                 charset = (CharSet)((int)charset | 0x40);
986                         
987                         MethodBuilder mb = builder.DefinePInvokeMethod (
988                                 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
989                                 CallingConventions.Standard,
990                                 ret_type,
991                                 param_types,
992                                 cc,
993                                 charset);
994
995                         if (preserve_sig)
996                                 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
997                         
998                         return mb;
999                 }
1000
1001                 private Expression GetValue () 
1002                 {
1003                         if ((Arguments == null) || (Arguments.Count < 1))
1004                                 return null;
1005                         ArrayList al = (ArrayList) Arguments [0];
1006                         if ((al == null) || (al.Count < 1))
1007                                 return null;
1008                         Argument arg = (Argument) al [0];
1009                         if ((arg == null) || (arg.Expr == null))
1010                                 return null;
1011                         return arg.Expr;
1012                 }
1013
1014                 public string GetString () 
1015                 {
1016                         Expression e = GetValue ();
1017                         if (e is StringLiteral)
1018                                 return (e as StringLiteral).Value;
1019                         return null;
1020                 }
1021
1022                 public bool GetBoolean () 
1023                 {
1024                         Expression e = GetValue ();
1025                         if (e is BoolLiteral)
1026                                 return (e as BoolLiteral).Value;
1027                         return false;
1028                 }
1029         }
1030         
1031
1032         /// <summary>
1033         /// For global attributes (assembly, module) we need special handling.
1034         /// Attributes can be located in the several files
1035         /// </summary>
1036         public class GlobalAttribute: Attribute
1037         {
1038                 public readonly NamespaceEntry ns;
1039
1040                 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1041                         base (target, name, args, loc)
1042                 {
1043                         ns = container.NamespaceEntry;
1044                 }
1045
1046                 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1047                 {
1048                         NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1049                         if (old == null || old.NS == null || old.NS == Namespace.Root) 
1050                                 ec.DeclSpace.NamespaceEntry = ns;
1051                         return base.CheckAttributeType (ec, complain);
1052                 }
1053         }
1054
1055         public class Attributes {
1056                 public ArrayList Attrs;
1057
1058                 public Attributes (Attribute a)
1059                 {
1060                         Attrs = new ArrayList ();
1061                         Attrs.Add (a);
1062                 }
1063
1064                 public Attributes (ArrayList attrs)
1065                 {
1066                         Attrs = attrs;
1067                 }
1068
1069                 public void AddAttributes (ArrayList attrs)
1070                 {
1071                         Attrs.AddRange (attrs);
1072                 }
1073
1074                 /// <summary>
1075                 /// Checks whether attribute target is valid for the current element
1076                 /// </summary>
1077                 public void CheckTargets (Attributable member)
1078                 {
1079                         string[] valid_targets = member.ValidAttributeTargets;
1080                         foreach (Attribute a in Attrs) {
1081                                 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1082                                         a.Target = member.AttributeTargets;
1083                                         continue;
1084                                 }
1085
1086                                 // TODO: we can skip the first item
1087                                 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1088                                         switch (a.ExplicitTarget) {
1089                                                 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1090                                                 case "param": a.Target = AttributeTargets.Parameter; continue;
1091                                                 case "field": a.Target = AttributeTargets.Field; continue;
1092                                                 case "method": a.Target = AttributeTargets.Method; continue;
1093                                                 case "property": a.Target = AttributeTargets.Property; continue;
1094                                         }
1095                                         throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1096                                 }
1097
1098                                 StringBuilder sb = new StringBuilder ();
1099                                 foreach (string s in valid_targets) {
1100                                         sb.Append (s);
1101                                         sb.Append (", ");
1102                                 }
1103                                 sb.Remove (sb.Length - 2, 2);
1104                                 Report.Error (657, a.Location, "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'", a.Target, sb.ToString ());
1105                         }
1106                 }
1107
1108                 private Attribute Search (Type t, EmitContext ec, bool complain)
1109                 {
1110                         foreach (Attribute a in Attrs) {
1111                                 if (a.ResolveType (ec, complain) == t)
1112                                         return a;
1113                         }
1114                         return null;
1115                 }
1116
1117                 public Attribute Search (Type t, EmitContext ec)
1118                 {
1119                         return Search (t, ec, true);
1120                 }
1121
1122                 /// <summary>
1123                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1124                 /// </summary>
1125                 public Attribute[] SearchMulti (Type t, EmitContext ec)
1126                 {
1127                         ArrayList ar = null;
1128
1129                         foreach (Attribute a in Attrs) {
1130                                 if (a.ResolveType (ec, false) == t) {
1131                                         if (ar == null)
1132                                                 ar = new ArrayList ();
1133                                         ar.Add (a);
1134                                 }
1135                         }
1136
1137                         return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1138                 }
1139
1140                 public void Emit (EmitContext ec, Attributable ias)
1141                 {
1142                         ListDictionary ld = new ListDictionary ();
1143
1144                         foreach (Attribute a in Attrs)
1145                                 a.Emit (ec, ias, ld);
1146                 }
1147
1148                 public bool Contains (Type t, EmitContext ec)
1149                 {
1150                         return Search (t, ec) != null;
1151                 }
1152
1153                 public Attribute GetClsCompliantAttribute (EmitContext ec)
1154                 {
1155                         return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1156                 }
1157
1158                 /// <summary>
1159                 /// Pulls the IndexerName attribute from an Indexer if it exists.
1160                 /// </summary>
1161                 public Attribute GetIndexerNameAttribute (EmitContext ec)
1162                 {
1163                         Attribute a = Search (TypeManager.indexer_name_type, ec, false);
1164                         if (a == null)
1165                                 return null;
1166
1167                         // Remove the attribute from the list because it is not emitted
1168                         Attrs.Remove (a);
1169                         return a;
1170                 }
1171
1172         }
1173
1174         /// <summary>
1175         /// Helper class for attribute verification routine.
1176         /// </summary>
1177         sealed class AttributeTester
1178         {
1179                 static PtrHashtable analyzed_types = new PtrHashtable ();
1180                 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1181                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1182                 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1183
1184                 private AttributeTester ()
1185                 {
1186                 }
1187
1188                 /// <summary>
1189                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1190                 /// It tests differing only in ref or out, or in array rank.
1191                 /// </summary>
1192                 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1193                 {
1194                         if (types_a == null || types_b == null)
1195                                 return true;
1196
1197                         if (types_a.Length != types_b.Length)
1198                                 return true;
1199
1200                         for (int i = 0; i < types_b.Length; ++i) {
1201                                 Type aType = types_a [i];
1202                                 Type bType = types_b [i];
1203
1204                                 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1205                                         return false;
1206                                 }
1207
1208                                 Type aBaseType = aType;
1209                                 bool is_either_ref_or_out = false;
1210
1211                                 if (aType.IsByRef || aType.IsPointer) {
1212                                         aBaseType = aType.GetElementType ();
1213                                         is_either_ref_or_out = true;
1214                                 }
1215
1216                                 Type bBaseType = bType;
1217                                 if (bType.IsByRef || bType.IsPointer) 
1218                                 {
1219                                         bBaseType = bType.GetElementType ();
1220                                         is_either_ref_or_out = !is_either_ref_or_out;
1221                                 }
1222
1223                                 if (aBaseType != bBaseType)
1224                                         continue;
1225
1226                                 if (is_either_ref_or_out)
1227                                         return false;
1228                         }
1229                         return true;
1230                 }
1231
1232                 /// <summary>
1233                 /// Goes through all parameters and test if they are CLS-Compliant.
1234                 /// </summary>
1235                 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1236                 {
1237                         if (fixedParameters == null)
1238                                 return true;
1239
1240                         foreach (Parameter arg in fixedParameters) {
1241                                 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1242                                         Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1243                                         return false;
1244                                 }
1245                         }
1246                         return true;
1247                 }
1248
1249
1250                 /// <summary>
1251                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1252                 /// </summary>
1253                 public static bool IsClsCompliant (Type type) 
1254                 {
1255                         if (type == null)
1256                                 return true;
1257
1258                         object type_compliance = analyzed_types[type];
1259                         if (type_compliance != null)
1260                                 return type_compliance == TRUE;
1261
1262                         if (type.IsPointer) {
1263                                 analyzed_types.Add (type, null);
1264                                 return false;
1265                         }
1266
1267                         bool result;
1268                         if (type.IsArray || type.IsByRef)       {
1269                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1270                         } else {
1271                                 result = AnalyzeTypeCompliance (type);
1272                         }
1273                         analyzed_types.Add (type, result ? TRUE : FALSE);
1274                         return result;
1275                 }                
1276
1277                 static object TRUE = new object ();
1278                 static object FALSE = new object ();
1279
1280                 public static void VerifyModulesClsCompliance ()
1281                 {
1282                         Module[] modules = TypeManager.Modules;
1283                         if (modules == null)
1284                                 return;
1285
1286                         // The first module is generated assembly
1287                         for (int i = 1; i < modules.Length; ++i) {
1288                                 Module module = modules [i];
1289                                 if (!IsClsCompliant (module)) {
1290                                         Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1291                                         return;
1292                                 }
1293                         }
1294                 }
1295
1296                 /// <summary>
1297                 /// Tests container name for CLS-Compliant name (differing only in case)
1298                 /// </summary>
1299                 public static void VerifyTopLevelNameClsCompliance ()
1300                 {
1301                         Hashtable locase_table = new Hashtable ();
1302
1303                         // Convert imported type names to lower case and ignore not cls compliant
1304                         foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1305                                 Type t = (Type)de.Value;
1306                                 if (!AttributeTester.IsClsCompliant (t))
1307                                         continue;
1308
1309                                 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1310                         }
1311
1312                         foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1313                                 DeclSpace decl = (DeclSpace)de.Value;
1314                                 if (!decl.IsClsCompliaceRequired (decl))
1315                                         continue;
1316
1317                                 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1318                                 if (!locase_table.Contains (lcase)) {
1319                                         locase_table.Add (lcase, decl);
1320                                         continue;
1321                                 }
1322
1323                                 object conflict = locase_table [lcase];
1324                                 if (conflict is Type)
1325                                         Report.SymbolRelatedToPreviousError ((Type)conflict);
1326                                 else
1327                                         Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1328
1329                                 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1330                         }
1331                 }
1332
1333                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1334                 {
1335                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1336                         if (CompliantAttribute.Length == 0)
1337                                 return false;
1338
1339                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1340                 }
1341
1342                 static bool AnalyzeTypeCompliance (Type type)
1343                 {
1344                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1345                         if (ds != null) {
1346                                 return ds.IsClsCompliaceRequired (ds.Parent);
1347                         }
1348
1349                         if (type.IsGenericParameter)
1350                                 return false;
1351
1352                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1353                         if (CompliantAttribute.Length == 0) 
1354                                 return IsClsCompliant (type.Assembly);
1355
1356                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1357                 }
1358
1359                 /// <summary>
1360                 /// Returns instance of ObsoleteAttribute when type is obsolete
1361                 /// </summary>
1362                 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1363                 {
1364                         object type_obsolete = analyzed_types_obsolete [type];
1365                         if (type_obsolete == FALSE)
1366                                 return null;
1367
1368                         if (type_obsolete != null)
1369                                 return (ObsoleteAttribute)type_obsolete;
1370
1371                         ObsoleteAttribute result = null;
1372                         if (type.IsByRef || type.IsArray || type.IsPointer) {
1373                                 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1374                         } else if (type.IsGenericParameter || type.IsGenericInstance)
1375                                 return null;
1376                         else {
1377                                 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1378
1379                                 // Type is external, we can get attribute directly
1380                                 if (type_ds == null) {
1381                                         object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1382                                         if (attribute.Length == 1)
1383                                                 result = (ObsoleteAttribute)attribute [0];
1384                                 } else {
1385                                         result = type_ds.GetObsoleteAttribute (type_ds);
1386                                 }
1387                         }
1388
1389                         analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1390                         return result;
1391                 }
1392
1393                 /// <summary>
1394                 /// Returns instance of ObsoleteAttribute when method is obsolete
1395                 /// </summary>
1396                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1397                 {
1398                         IMethodData mc = TypeManager.GetMethod (mb);
1399                         if (mc != null) 
1400                                 return mc.GetObsoleteAttribute ();
1401
1402                         // compiler generated methods are not registered by AddMethod
1403                         if (mb.DeclaringType is TypeBuilder)
1404                                 return null;
1405
1406                         return GetMemberObsoleteAttribute (mb);
1407                 }
1408
1409                 /// <summary>
1410                 /// Returns instance of ObsoleteAttribute when member is obsolete
1411                 /// </summary>
1412                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1413                 {
1414                         object type_obsolete = analyzed_member_obsolete [mi];
1415                         if (type_obsolete == FALSE)
1416                                 return null;
1417
1418                         if (type_obsolete != null)
1419                                 return (ObsoleteAttribute)type_obsolete;
1420
1421                         if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1422                                 return null;
1423
1424                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1425                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1426                         return oa;
1427                 }
1428
1429                 /// <summary>
1430                 /// Common method for Obsolete error/warning reporting.
1431                 /// </summary>
1432                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1433                 {
1434                         if (oa.IsError) {
1435                                 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1436                                 return;
1437                         }
1438
1439                         if (oa.Message == null) {
1440                                 Report.Warning (612, loc, "'{0}' is obsolete", member);
1441                                 return;
1442                         }
1443                         if (RootContext.WarningLevel >= 2)
1444                                 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1445                 }
1446
1447                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1448                 {
1449                         object excluded = analyzed_method_excluded [mb];
1450                         if (excluded != null)
1451                                 return excluded == TRUE ? true : false;
1452
1453                         if (mb.Mono_IsInflatedMethod)
1454                                 return false;
1455                         
1456                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1457                         if (attrs.Length == 0) {
1458                                 analyzed_method_excluded.Add (mb, FALSE);
1459                                 return false;
1460                         }
1461
1462                         foreach (ConditionalAttribute a in attrs) {
1463                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1464                                         analyzed_method_excluded.Add (mb, FALSE);
1465                                         return false;
1466                                 }
1467                         }
1468                         analyzed_method_excluded.Add (mb, TRUE);
1469                         return true;
1470                 }
1471         }
1472 }