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