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