2005-01-19 Sureshkumar T <tsureshkumar@novell.com>
[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                         // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1183                         // each time a new file is parsed.  However, we need to use the NamespaceEntry
1184                         // in effect where the attribute was used.  Since code elsewhere cannot assume
1185                         // that the NamespaceEntry is right, just overwrite it.
1186                         //
1187                         // FIXME: Check every place the NamespaceEntry of RootContext.Tree.Types is used
1188                         //        to ensure the right one is used.
1189                         if (ec.DeclSpace == RootContext.Tree.Types)
1190                                 ec.DeclSpace.NamespaceEntry = ns;
1191
1192                         return base.CheckAttributeType (ec);
1193                 }
1194         }
1195
1196         public class Attributes {
1197                 public ArrayList Attrs;
1198
1199                 public Attributes (Attribute a)
1200                 {
1201                         Attrs = new ArrayList ();
1202                         Attrs.Add (a);
1203                 }
1204
1205                 public Attributes (ArrayList attrs)
1206                 {
1207                         Attrs = attrs;
1208                 }
1209
1210                 public void AddAttributes (ArrayList attrs)
1211                 {
1212                         Attrs.AddRange (attrs);
1213                 }
1214
1215                 /// <summary>
1216                 /// Checks whether attribute target is valid for the current element
1217                 /// </summary>
1218                 public bool CheckTargets (Attributable member)
1219                 {
1220                         string[] valid_targets = member.ValidAttributeTargets;
1221                         foreach (Attribute a in Attrs) {
1222                                 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1223                                         a.Target = member.AttributeTargets;
1224                                         continue;
1225                                 }
1226
1227                                 // TODO: we can skip the first item
1228                                 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1229                                         switch (a.ExplicitTarget) {
1230                                                 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1231                                                 case "param": a.Target = AttributeTargets.Parameter; continue;
1232                                                 case "field": a.Target = AttributeTargets.Field; continue;
1233                                                 case "method": a.Target = AttributeTargets.Method; continue;
1234                                                 case "property": a.Target = AttributeTargets.Property; continue;
1235                                         }
1236                                         throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1237                                 }
1238
1239                                 StringBuilder sb = new StringBuilder ();
1240                                 foreach (string s in valid_targets) {
1241                                         sb.Append (s);
1242                                         sb.Append (", ");
1243                                 }
1244                                 sb.Remove (sb.Length - 2, 2);
1245                                 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 ());
1246                                 return false;
1247                         }
1248                         return true;
1249                 }
1250
1251                 public Attribute Search (Type t, EmitContext ec)
1252                 {
1253                         foreach (Attribute a in Attrs) {
1254                                 if (a.ResolveType (ec) == t)
1255                                         return a;
1256                         }
1257                         return null;
1258                 }
1259
1260                 /// <summary>
1261                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1262                 /// </summary>
1263                 public Attribute[] SearchMulti (Type t, EmitContext ec)
1264                 {
1265                         ArrayList ar = null;
1266
1267                         foreach (Attribute a in Attrs) {
1268                                 if (a.ResolveType (ec) == t) {
1269                                         if (ar == null)
1270                                                 ar = new ArrayList ();
1271                                         ar.Add (a);
1272                                 }
1273                         }
1274
1275                         return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1276                 }
1277
1278                 public void Emit (EmitContext ec, Attributable ias)
1279                 {
1280                         if (!CheckTargets (ias))
1281                                 return;
1282
1283                         ListDictionary ld = new ListDictionary ();
1284
1285                         foreach (Attribute a in Attrs)
1286                                 a.Emit (ec, ias, ld);
1287                 }
1288
1289                 public bool Contains (Type t, EmitContext ec)
1290                 {
1291                         return Search (t, ec) != null;
1292                 }
1293         }
1294
1295         /// <summary>
1296         /// Helper class for attribute verification routine.
1297         /// </summary>
1298         sealed class AttributeTester
1299         {
1300                 static PtrHashtable analyzed_types = new PtrHashtable ();
1301                 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1302                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1303                 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1304
1305                 private AttributeTester ()
1306                 {
1307                 }
1308
1309                 /// <summary>
1310                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1311                 /// It tests differing only in ref or out, or in array rank.
1312                 /// </summary>
1313                 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1314                 {
1315                         if (types_a == null || types_b == null)
1316                                 return true;
1317
1318                         if (types_a.Length != types_b.Length)
1319                                 return true;
1320
1321                         for (int i = 0; i < types_b.Length; ++i) {
1322                                 Type aType = types_a [i];
1323                                 Type bType = types_b [i];
1324
1325                                 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1326                                         return false;
1327                                 }
1328
1329                                 Type aBaseType = aType;
1330                                 bool is_either_ref_or_out = false;
1331
1332                                 if (aType.IsByRef || aType.IsPointer) {
1333                                         aBaseType = aType.GetElementType ();
1334                                         is_either_ref_or_out = true;
1335                                 }
1336
1337                                 Type bBaseType = bType;
1338                                 if (bType.IsByRef || bType.IsPointer) 
1339                                 {
1340                                         bBaseType = bType.GetElementType ();
1341                                         is_either_ref_or_out = !is_either_ref_or_out;
1342                                 }
1343
1344                                 if (aBaseType != bBaseType)
1345                                         continue;
1346
1347                                 if (is_either_ref_or_out)
1348                                         return false;
1349                         }
1350                         return true;
1351                 }
1352
1353                 /// <summary>
1354                 /// Goes through all parameters and test if they are CLS-Compliant.
1355                 /// </summary>
1356                 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1357                 {
1358                         if (fixedParameters == null)
1359                                 return true;
1360
1361                         foreach (Parameter arg in fixedParameters) {
1362                                 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1363                                         Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1364                                         return false;
1365                                 }
1366                         }
1367                         return true;
1368                 }
1369
1370
1371                 /// <summary>
1372                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1373                 /// </summary>
1374                 public static bool IsClsCompliant (Type type) 
1375                 {
1376                         if (type == null)
1377                                 return true;
1378
1379                         object type_compliance = analyzed_types[type];
1380                         if (type_compliance != null)
1381                                 return type_compliance == TRUE;
1382
1383                         if (type.IsPointer) {
1384                                 analyzed_types.Add (type, null);
1385                                 return false;
1386                         }
1387
1388                         bool result;
1389                         if (type.IsArray || type.IsByRef)       {
1390                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1391                         } else {
1392                                 result = AnalyzeTypeCompliance (type);
1393                         }
1394                         analyzed_types.Add (type, result ? TRUE : FALSE);
1395                         return result;
1396                 }                
1397
1398                 static object TRUE = new object ();
1399                 static object FALSE = new object ();
1400
1401                 public static void VerifyModulesClsCompliance ()
1402                 {
1403                         Module[] modules = TypeManager.Modules;
1404                         if (modules == null)
1405                                 return;
1406
1407                         // The first module is generated assembly
1408                         for (int i = 1; i < modules.Length; ++i) {
1409                                 Module module = modules [i];
1410                                 if (!IsClsCompliant (module)) {
1411                                         Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1412                                         return;
1413                                 }
1414                         }
1415                 }
1416
1417                 /// <summary>
1418                 /// Tests container name for CLS-Compliant name (differing only in case)
1419                 /// </summary>
1420                 public static void VerifyTopLevelNameClsCompliance ()
1421                 {
1422                         Hashtable locase_table = new Hashtable ();
1423
1424                         // Convert imported type names to lower case and ignore not cls compliant
1425                         foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1426                                 Type t = (Type)de.Value;
1427                                 if (!AttributeTester.IsClsCompliant (t))
1428                                         continue;
1429
1430                                 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1431                         }
1432
1433                         foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1434                                 DeclSpace decl = (DeclSpace)de.Value;
1435                                 if (!decl.IsClsCompliaceRequired (decl))
1436                                         continue;
1437
1438                                 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1439                                 if (!locase_table.Contains (lcase)) {
1440                                         locase_table.Add (lcase, decl);
1441                                         continue;
1442                                 }
1443
1444                                 object conflict = locase_table [lcase];
1445                                 if (conflict is Type)
1446                                         Report.SymbolRelatedToPreviousError ((Type)conflict);
1447                                 else
1448                                         Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1449
1450                                 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1451                         }
1452                 }
1453
1454                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1455                 {
1456                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1457                         if (CompliantAttribute.Length == 0)
1458                                 return false;
1459
1460                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1461                 }
1462
1463                 static bool AnalyzeTypeCompliance (Type type)
1464                 {
1465                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1466                         if (ds != null) {
1467                                 return ds.IsClsCompliaceRequired (ds.Parent);
1468                         }
1469
1470                         if (type.IsGenericParameter || type.IsGenericInstance)
1471                                 return false;
1472
1473                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1474                         if (CompliantAttribute.Length == 0) 
1475                                 return IsClsCompliant (type.Assembly);
1476
1477                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1478                 }
1479
1480                 /// <summary>
1481                 /// Returns instance of ObsoleteAttribute when type is obsolete
1482                 /// </summary>
1483                 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1484                 {
1485                         object type_obsolete = analyzed_types_obsolete [type];
1486                         if (type_obsolete == FALSE)
1487                                 return null;
1488
1489                         if (type_obsolete != null)
1490                                 return (ObsoleteAttribute)type_obsolete;
1491
1492                         ObsoleteAttribute result = null;
1493                         if (type.IsByRef || type.IsArray || type.IsPointer) {
1494                                 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1495                         } else if (type.IsGenericParameter || type.IsGenericInstance)
1496                                 return null;
1497                         else {
1498                                 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1499
1500                                 // Type is external, we can get attribute directly
1501                                 if (type_ds == null) {
1502                                         object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1503                                         if (attribute.Length == 1)
1504                                                 result = (ObsoleteAttribute)attribute [0];
1505                                 } else {
1506                                         result = type_ds.GetObsoleteAttribute (type_ds);
1507                                 }
1508                         }
1509
1510                         analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1511                         return result;
1512                 }
1513
1514                 /// <summary>
1515                 /// Returns instance of ObsoleteAttribute when method is obsolete
1516                 /// </summary>
1517                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1518                 {
1519                         IMethodData mc = TypeManager.GetMethod (mb);
1520                         if (mc != null) 
1521                                 return mc.GetObsoleteAttribute ();
1522
1523                         // compiler generated methods are not registered by AddMethod
1524                         if (mb.DeclaringType is TypeBuilder)
1525                                 return null;
1526
1527                         return GetMemberObsoleteAttribute (mb);
1528                 }
1529
1530                 /// <summary>
1531                 /// Returns instance of ObsoleteAttribute when member is obsolete
1532                 /// </summary>
1533                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1534                 {
1535                         object type_obsolete = analyzed_member_obsolete [mi];
1536                         if (type_obsolete == FALSE)
1537                                 return null;
1538
1539                         if (type_obsolete != null)
1540                                 return (ObsoleteAttribute)type_obsolete;
1541
1542                         if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1543                                 return null;
1544
1545                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1546                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1547                         return oa;
1548                 }
1549
1550                 /// <summary>
1551                 /// Common method for Obsolete error/warning reporting.
1552                 /// </summary>
1553                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1554                 {
1555                         if (oa.IsError) {
1556                                 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1557                                 return;
1558                         }
1559
1560                         if (oa.Message == null) {
1561                                 Report.Warning (612, loc, "'{0}' is obsolete", member);
1562                                 return;
1563                         }
1564                         if (RootContext.WarningLevel >= 2)
1565                                 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1566                 }
1567
1568                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1569                 {
1570                         object excluded = analyzed_method_excluded [mb];
1571                         if (excluded != null)
1572                                 return excluded == TRUE ? true : false;
1573
1574                         if (mb.Mono_IsInflatedMethod)
1575                                 return false;
1576                         
1577                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1578                         if (attrs.Length == 0) {
1579                                 analyzed_method_excluded.Add (mb, FALSE);
1580                                 return false;
1581                         }
1582
1583                         foreach (ConditionalAttribute a in attrs) {
1584                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1585                                         analyzed_method_excluded.Add (mb, FALSE);
1586                                         return false;
1587                                 }
1588                         }
1589                         analyzed_method_excluded.Add (mb, TRUE);
1590                         return true;
1591                 }
1592         }
1593 }