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