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