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