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