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