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