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