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