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