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