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