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