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