2005-08-26 Iain McCoy <iain@mccoy.id.au>
[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                 readonly bool nameEscaped;
89
90                 static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
91                 static Assembly orig_sec_assembly;
92
93                 // non-null if named args present after Resolve () is called
94                 PropertyInfo [] prop_info_arr;
95                 FieldInfo [] field_info_arr;
96                 object [] field_values_arr;
97                 object [] prop_values_arr;
98                 object [] pos_values;
99
100                 static PtrHashtable usage_attr_cache = new PtrHashtable ();
101                 
102                 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc, bool nameEscaped)
103                 {
104                         LeftExpr = left_expr;
105                         Identifier = identifier;
106                         Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
107                         Arguments = args;
108                         Location = loc;
109                         ExplicitTarget = target;
110                         this.nameEscaped = nameEscaped;
111                 }
112
113                 void Error_InvalidNamedArgument (string name)
114                 {
115                         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",
116                               name);
117                 }
118
119                 void Error_InvalidNamedAgrumentType (string name)
120                 {
121                         Report.Error (655, Location, "`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type", name);
122                 }
123
124                 static void Error_AttributeArgumentNotValid (string extra, Location loc)
125                 {
126                         Report.Error (182, loc,
127                                       "An attribute argument must be a constant expression, typeof " +
128                                       "expression or array creation expression" + extra);
129                 }
130
131                 static void Error_AttributeArgumentNotValid (Location loc)
132                 {
133                         Error_AttributeArgumentNotValid ("", loc);
134                 }
135                 
136
137                 /// <summary>
138                 /// This is rather hack. We report many emit attribute error with same error to be compatible with
139                 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
140                 /// </summary>
141                 public void Error_AttributeEmitError (string inner)
142                 {
143                         Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'", TypeManager.CSharpName (Type), inner);
144                 }
145
146                 public void Error_InvalidSecurityParent ()
147                 {
148                         Error_AttributeEmitError ("it is attached to invalid parent");
149                 }
150
151                 protected virtual FullNamedExpression ResolveAsTypeTerminal (Expression expr, EmitContext ec, bool silent)
152                 {
153                         return expr.ResolveAsTypeTerminal (ec, silent);
154                 }
155
156                 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec, bool silent)
157                 {
158                         return expr.ResolveAsTypeStep (ec, silent);
159                 }
160
161                 Type ResolvePossibleAttributeType (EmitContext ec, string name, bool silent, ref bool is_attr)
162                 {
163                         FullNamedExpression fn;
164                         if (LeftExpr == null) {
165                                 fn = ResolveAsTypeTerminal (new SimpleName (name, Location), ec, silent);
166                         } else {
167                                 fn = ResolveAsTypeStep (LeftExpr, ec, silent);
168                                 if (fn == null)
169                                         return null;
170                                 fn = new MemberAccess (fn, name, Location).ResolveAsTypeTerminal (ec, silent);
171                         }
172
173                         TypeExpr te = fn as TypeExpr;
174                         if (te == null)
175                                 return null;
176
177                         Type t = te.Type;
178                         if (t.IsSubclassOf (TypeManager.attribute_type)) {
179                                 is_attr = true;
180                         } else if (!silent) {
181                                 Report.SymbolRelatedToPreviousError (t);
182                                 Report.Error (616, Location, "`{0}': is not an attribute class", TypeManager.CSharpName (t));
183                         }
184                         return t;
185                 }
186
187                 /// <summary>
188                 ///   Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
189                 /// </summary>
190                 void ResolveAttributeType (EmitContext ec)
191                 {
192                         bool t1_is_attr = false;
193                         Type t1 = ResolvePossibleAttributeType (ec, Identifier, true, ref t1_is_attr);
194
195                         // FIXME: Shouldn't do this for quoted attributes: [@A]
196                         bool t2_is_attr = false;
197                         Type t2 = ResolvePossibleAttributeType (ec, Identifier + "Attribute", true, ref t2_is_attr);
198
199                         if (t1_is_attr && t2_is_attr && !nameEscaped) {
200                                 Report.Error (1614, Location, "`{0}' is ambiguous between `{0}' and `{0}Attribute'. Use either `@{0}' or `{0}Attribute'", GetSignatureForError ());
201                                 resolve_error = true;
202                                 return;
203                         }
204
205                         if (t1_is_attr) {
206                                 Type = t1;
207                                 return;
208                         }
209
210                         if (t2_is_attr) {
211                                 Type = t2;
212                                 return;
213                         }
214
215                         if (t1 == null && t2 == null)
216                                 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
217                         if (t1 != null)
218                                 ResolvePossibleAttributeType (ec, Identifier, false, ref t1_is_attr);
219                         if (t2 != null)
220                                 ResolvePossibleAttributeType (ec, Identifier + "Attribute", false, ref t2_is_attr);
221
222                         resolve_error = true;
223                 }
224
225                 public virtual Type ResolveType (EmitContext ec)
226                 {
227                         if (Type == null && !resolve_error)
228                                 ResolveAttributeType (ec);
229                         return Type;
230                 }
231
232                 public string GetSignatureForError ()
233                 {
234                         return LeftExpr == null ? Identifier : LeftExpr.GetSignatureForError () + "." + Identifier;
235                 }
236
237                 //
238                 // Given an expression, if the expression is a valid attribute-argument-expression
239                 // returns an object that can be used to encode it, or null on failure.
240                 //
241                 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
242                 {
243                         Constant constant = e as Constant;
244                         if (constant != null) {
245                                 constant = constant.ToType (arg_type, loc);
246                                 if (constant == null) {
247                                         result = null;
248                                         return false;
249                                 }
250                                 result = constant.GetTypedValue ();
251                                 return true;
252                         } else if (e is TypeOf) {
253                                 result = ((TypeOf) e).TypeArg;
254                                 return true;
255                         } else if (e is ArrayCreation){
256                                 result =  ((ArrayCreation) e).EncodeAsAttribute ();
257                                 if (result != null)
258                                         return true;
259                         } else if (e is EmptyCast) {
260                                 Expression child = ((EmptyCast)e).Child;
261                                 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
262                         }
263
264                         result = null;
265                         Error_AttributeArgumentNotValid (loc);
266                         return false;
267                 }
268
269                 bool IsValidArgumentType (Type t)
270                 {
271                         return TypeManager.IsPrimitiveType (t) ||
272                                 (t.IsArray && TypeManager.IsPrimitiveType (t.GetElementType ())) ||
273                                 TypeManager.IsEnumType (t) ||
274                                 t == TypeManager.string_type ||
275                                 t == TypeManager.object_type ||
276                                 t == TypeManager.type_type;
277                 }
278
279                 // Cache for parameter-less attributes
280                 static PtrHashtable att_cache = new PtrHashtable ();
281
282                 public CustomAttributeBuilder Resolve (EmitContext ec)
283                 {
284                         if (resolve_error)
285                                 return null;
286
287                         resolve_error = true;
288
289                         if (Type == null) {
290                                 ResolveAttributeType (ec);
291                                 if (Type == null)
292                                         return null;
293                         }
294
295                         if (Type.IsAbstract) {
296                                 Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
297                                 return null;
298                         }
299
300                         if (Arguments == null) {
301                                 object o = att_cache [Type];
302                                 if (o != null) {
303                                         resolve_error = false;
304                                         return (CustomAttributeBuilder)o;
305                                 }
306                         }
307
308                         ConstructorInfo ctor = ResolveArguments (ec);
309                         if (ctor == null)
310                                 return null;
311
312                         CustomAttributeBuilder cb;
313
314                         try {
315                                 if (prop_info_arr != null || field_info_arr != null) {
316                                         cb = new CustomAttributeBuilder (
317                                                 ctor, pos_values,
318                                                 prop_info_arr, prop_values_arr,
319                                                 field_info_arr, field_values_arr);
320                                 } else {
321                                         cb = new CustomAttributeBuilder (
322                                                 ctor, pos_values);
323
324                                         if (pos_values.Length == 0)
325                                                 att_cache.Add (Type, cb);
326                                 }
327                         }
328                         catch (Exception) {
329                                 Error_AttributeArgumentNotValid (Location);
330                                 return null;
331                         }
332
333                         resolve_error = false;
334                         return cb;
335                 }
336
337                 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
338                 {
339                         // Now we extract the positional and named arguments
340                         
341                         ArrayList pos_args = null;
342                         ArrayList named_args = null;
343                         int pos_arg_count = 0;
344                         int named_arg_count = 0;
345                         
346                         if (Arguments != null) {
347                                 pos_args = (ArrayList) Arguments [0];
348                                 if (pos_args != null)
349                                         pos_arg_count = pos_args.Count;
350                                 if (Arguments.Count > 1) {
351                                         named_args = (ArrayList) Arguments [1];
352                                         named_arg_count = named_args.Count;
353                                 }
354                         }
355
356                         pos_values = new object [pos_arg_count];
357
358                         //
359                         // First process positional arguments 
360                         //
361
362                         int i;
363                         for (i = 0; i < pos_arg_count; i++) {
364                                 Argument a = (Argument) pos_args [i];
365                                 Expression e;
366
367                                 if (!a.Resolve (ec, Location))
368                                         return null;
369
370                                 e = a.Expr;
371
372                                 object val;
373                                 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
374                                         return null;
375
376                                 pos_values [i] = val;
377
378                                 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
379                                         Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
380                                         return null;
381                                 }
382                         }
383
384                         //
385                         // Now process named arguments
386                         //
387
388                         ArrayList field_infos = null;
389                         ArrayList prop_infos  = null;
390                         ArrayList field_values = null;
391                         ArrayList prop_values = null;
392                         Hashtable seen_names = null;
393
394                         if (named_arg_count > 0) {
395                                 field_infos = new ArrayList ();
396                                 prop_infos  = new ArrayList ();
397                                 field_values = new ArrayList ();
398                                 prop_values = new ArrayList ();
399
400                                 seen_names = new Hashtable();
401                         }
402                         
403                         for (i = 0; i < named_arg_count; i++) {
404                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
405                                 string member_name = (string) de.Key;
406                                 Argument a  = (Argument) de.Value;
407                                 Expression e;
408
409                                 if (seen_names.Contains(member_name)) {
410                                         Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
411                                         return null;
412                                 }                               
413                                 seen_names.Add(member_name, 1);
414                                 
415                                 if (!a.Resolve (ec, Location))
416                                         return null;
417
418                                 Expression member = Expression.MemberLookup (
419                                         ec, Type, member_name,
420                                         MemberTypes.Field | MemberTypes.Property,
421                                         BindingFlags.Public | BindingFlags.Instance,
422                                         Location);
423
424                                 if (member == null) {
425                                         member = Expression.MemberLookup (ec, Type, member_name,
426                                                 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
427                                                 Location);
428
429                                         if (member != null) {
430                                                 Expression.ErrorIsInaccesible (Location, member.GetSignatureForError ());
431                                                 return null;
432                                         }
433                                 }
434
435                                 if (member == null){
436                                         Report.Error (117, Location, "`{0}' does not contain a definition for `{1}'",
437                                                       Type, member_name);
438                                         return null;
439                                 }
440                                 
441                                 if (!(member is PropertyExpr || member is FieldExpr)) {
442                                         Error_InvalidNamedArgument (member_name);
443                                         return null;
444                                 }
445
446                                 e = a.Expr;
447                                 if (member is PropertyExpr) {
448                                         PropertyExpr pe = (PropertyExpr) member;
449                                         PropertyInfo pi = pe.PropertyInfo;
450
451                                         if (!pi.CanWrite || !pi.CanRead) {
452                                                 Report.SymbolRelatedToPreviousError (pi);
453                                                 Error_InvalidNamedArgument (member_name);
454                                                 return null;
455                                         }
456
457                                         if (!IsValidArgumentType (pi.PropertyType)) {
458                                                 Report.SymbolRelatedToPreviousError (pi);
459                                                 Error_InvalidNamedAgrumentType (member_name);
460                                                 return null;
461                                         }
462
463                                         object value;
464                                         if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
465                                                 return null;
466
467                                         prop_values.Add (value);
468                                         prop_infos.Add (pi);
469                                         
470                                 } else if (member is FieldExpr) {
471                                         FieldExpr fe = (FieldExpr) member;
472                                         FieldInfo fi = fe.FieldInfo;
473
474                                         if (fi.IsInitOnly) {
475                                                 Error_InvalidNamedArgument (member_name);
476                                                 return null;
477                                         }
478
479                                         if (!IsValidArgumentType (fi.FieldType)) {
480                                                 Report.SymbolRelatedToPreviousError (fi);
481                                                 Error_InvalidNamedAgrumentType (member_name);
482                                                 return null;
483                                         }
484
485                                         object value;
486                                         if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
487                                                 return null;
488
489                                         field_values.Add (value);                                       
490                                         field_infos.Add (fi);
491                                 }
492                         }
493
494                         Expression mg = Expression.MemberLookup (
495                                 ec, Type, ".ctor", MemberTypes.Constructor,
496                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
497                                 Location);
498
499                         MethodBase constructor = Invocation.OverloadResolve (
500                                 ec, (MethodGroupExpr) mg, pos_args, false, Location);
501
502                         if (constructor == null) {
503                                 return null;
504                         }
505
506
507                         // Here we do the checks which should be done by corlib or by runtime.
508                         // However Zoltan doesn't like it and every Mono compiler has to do it again.
509                         
510                         if (Type == TypeManager.guid_attr_type) {
511                                 try {
512                                         new Guid ((string)pos_values [0]);
513                                 }
514                                 catch (Exception e) {
515                                         Error_AttributeEmitError (e.Message);
516                                 }
517                         }
518 // TODO: reenable
519 //                      if (Type == TypeManager.methodimpl_attr_type &&
520 //                              pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
521 //                              !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
522 //                                      Error_AttributeEmitError ("Incorrect argument value.");
523 //                      }
524
525                         //
526                         // Now we perform some checks on the positional args as they
527                         // cannot be null for a constructor which expects a parameter
528                         // of type object
529                         //
530
531                         ParameterData pd = TypeManager.GetParameterData (constructor);
532
533                         int last_real_param = pd.Count;
534                         if (pd.HasParams) {
535                                 // When the params is not filled we need to put one
536                                 if (last_real_param > pos_arg_count) {
537                                         object [] new_pos_values = new object [pos_arg_count + 1];
538                                         pos_values.CopyTo (new_pos_values, 0);
539                                         new_pos_values [pos_arg_count] = new object [] {} ;
540                                         pos_values = new_pos_values;
541                                 }
542                                 last_real_param--;
543                         }
544
545                         for (int j = 0; j < pos_arg_count; ++j) {
546                                 Argument a = (Argument) pos_args [j];
547                                 
548                                 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
549                                         Error_AttributeArgumentNotValid (Location);
550                                         return null;
551                                 }
552
553                                 object value = pos_values [j];
554                                 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
555                                         bool fail;
556                                         pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
557                                         if (fail) {
558                                                 // TODO: Can failed ?
559                                                 throw new NotImplementedException ();
560                                         }
561                                 }
562
563                                 if (j < last_real_param)
564                                         continue;
565                                 
566                                 if (j == last_real_param) {
567                                         object [] array = new object [pos_arg_count - last_real_param];
568                                         array [0] = pos_values [j];
569                                         pos_values [j] = array;
570                                         continue;
571                                 }
572
573                                 object [] params_array = (object []) pos_values [last_real_param];
574                                 params_array [j - last_real_param] = pos_values [j];
575                         }
576
577                         // Adjust the size of the pos_values if it had params
578                         if (last_real_param != pos_arg_count) {
579                                 object [] new_pos_values = new object [last_real_param + 1];
580                                 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
581                                 pos_values = new_pos_values;
582                         }
583
584                         if (named_arg_count > 0) {
585                                 prop_info_arr = new PropertyInfo [prop_infos.Count];
586                                 field_info_arr = new FieldInfo [field_infos.Count];
587                                 field_values_arr = new object [field_values.Count];
588                                 prop_values_arr = new object [prop_values.Count];
589
590                                 field_infos.CopyTo  (field_info_arr, 0);
591                                 field_values.CopyTo (field_values_arr, 0);
592
593                                 prop_values.CopyTo  (prop_values_arr, 0);
594                                 prop_infos.CopyTo   (prop_info_arr, 0);
595                         }
596
597                         return (ConstructorInfo) constructor;
598                 }
599
600                 /// <summary>
601                 ///   Get a string containing a list of valid targets for the attribute 'attr'
602                 /// </summary>
603                 public string GetValidTargets ()
604                 {
605                         StringBuilder sb = new StringBuilder ();
606                         AttributeTargets targets = GetAttributeUsage (null).ValidOn;
607
608                         if ((targets & AttributeTargets.Assembly) != 0)
609                                 sb.Append ("assembly, ");
610
611                         if ((targets & AttributeTargets.Module) != 0)
612                                 sb.Append ("module, ");
613
614                         if ((targets & AttributeTargets.Class) != 0)
615                                 sb.Append ("class, ");
616
617                         if ((targets & AttributeTargets.Struct) != 0)
618                                 sb.Append ("struct, ");
619
620                         if ((targets & AttributeTargets.Enum) != 0)
621                                 sb.Append ("enum, ");
622
623                         if ((targets & AttributeTargets.Constructor) != 0)
624                                 sb.Append ("constructor, ");
625
626                         if ((targets & AttributeTargets.Method) != 0)
627                                 sb.Append ("method, ");
628
629                         if ((targets & AttributeTargets.Property) != 0)
630                                 sb.Append ("property, indexer, ");
631
632                         if ((targets & AttributeTargets.Field) != 0)
633                                 sb.Append ("field, ");
634
635                         if ((targets & AttributeTargets.Event) != 0)
636                                 sb.Append ("event, ");
637
638                         if ((targets & AttributeTargets.Interface) != 0)
639                                 sb.Append ("interface, ");
640
641                         if ((targets & AttributeTargets.Parameter) != 0)
642                                 sb.Append ("parameter, ");
643
644                         if ((targets & AttributeTargets.Delegate) != 0)
645                                 sb.Append ("delegate, ");
646
647                         if ((targets & AttributeTargets.ReturnValue) != 0)
648                                 sb.Append ("return, ");
649
650 #if NET_2_0
651                         if ((targets & AttributeTargets.GenericParameter) != 0)
652                                 sb.Append ("type parameter, ");
653 #endif                  
654                         return sb.Remove (sb.Length - 2, 2).ToString ();
655                 }
656
657                 /// <summary>
658                 /// Returns AttributeUsage attribute for this type
659                 /// </summary>
660                 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
661                 {
662                         AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
663                         if (ua != null)
664                                 return ua;
665
666                         Class attr_class = TypeManager.LookupClass (Type);
667
668                         if (attr_class == null) {
669                                 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
670                                 ua = (AttributeUsageAttribute)usage_attr [0];
671                                 usage_attr_cache.Add (Type, ua);
672                                 return ua;
673                         }
674
675                         Attribute a = attr_class.OptAttributes == null
676                                 ? null
677                                 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
678
679                         ua = a == null
680                                 ? DefaultUsageAttribute 
681                                 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
682
683                         usage_attr_cache.Add (Type, ua);
684                         return ua;
685                 }
686
687                 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
688                 {
689                         if (pos_values == null)
690                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
691                                 // But because a lot of attribute class code must be rewritten will be better to wait...
692                                 Resolve (ec);
693
694                         if (resolve_error)
695                                 return DefaultUsageAttribute;
696
697                         AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
698
699                         object field = GetPropertyValue ("AllowMultiple");
700                         if (field != null)
701                                 usage_attribute.AllowMultiple = (bool)field;
702
703                         field = GetPropertyValue ("Inherited");
704                         if (field != null)
705                                 usage_attribute.Inherited = (bool)field;
706
707                         return usage_attribute;
708                 }
709
710                 /// <summary>
711                 /// Returns custom name of indexer
712                 /// </summary>
713                 public string GetIndexerAttributeValue (EmitContext ec)
714                 {
715                         if (pos_values == null)
716                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
717                                 // But because a lot of attribute class code must be rewritten will be better to wait...
718                                 Resolve (ec);
719
720                         if (resolve_error)
721                                 return null;
722
723                         return pos_values [0] as string;
724                 }
725
726                 /// <summary>
727                 /// Returns condition of ConditionalAttribute
728                 /// </summary>
729                 public string GetConditionalAttributeValue (EmitContext ec)
730                 {
731                         if (pos_values == null)
732                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
733                                 // But because a lot of attribute class code must be rewritten will be better to wait...
734                                 Resolve (ec);
735
736                         if (resolve_error)
737                                 return null;
738
739                         return (string)pos_values [0];
740                 }
741
742                 /// <summary>
743                 /// Creates the instance of ObsoleteAttribute from this attribute instance
744                 /// </summary>
745                 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
746                 {
747                         if (pos_values == null)
748                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
749                                 // But because a lot of attribute class code must be rewritten will be better to wait...
750                                 Resolve (ec);
751
752                         if (resolve_error)
753                                 return null;
754
755                         if (pos_values == null || pos_values.Length == 0)
756                                 return new ObsoleteAttribute ();
757
758                         if (pos_values.Length == 1)
759                                 return new ObsoleteAttribute ((string)pos_values [0]);
760
761                         return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
762                 }
763
764                 /// <summary>
765                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
766                 /// before ApplyAttribute. We need to resolve the arguments.
767                 /// This situation occurs when class deps is differs from Emit order.  
768                 /// </summary>
769                 public bool GetClsCompliantAttributeValue (EmitContext ec)
770                 {
771                         if (pos_values == null)
772                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
773                                 // But because a lot of attribute class code must be rewritten will be better to wait...
774                                 Resolve (ec);
775
776                         if (resolve_error)
777                                 return false;
778
779                         return (bool)pos_values [0];
780                 }
781
782                 /// <summary>
783                 /// Tests permitted SecurityAction for assembly or other types
784                 /// </summary>
785                 public bool CheckSecurityActionValidity (bool for_assembly)
786                 {
787                         SecurityAction action  = GetSecurityActionValue ();
788
789                         if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
790                                 return true;
791
792                         if (!for_assembly) {
793                                 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
794                                         Error_AttributeEmitError ("SecurityAction is out of range");
795                                         return false;
796                                 }
797
798                                 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
799                                         return true;
800                         }
801
802                         Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
803                         return false;
804                 }
805
806                 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
807                 {
808                         return (SecurityAction)pos_values [0];
809                 }
810
811                 /// <summary>
812                 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
813                 /// </summary>
814                 /// <returns></returns>
815                 public void ExtractSecurityPermissionSet (ListDictionary permissions)
816                 {
817                         Type orig_assembly_type = null;
818
819                         if (TypeManager.LookupDeclSpace (Type) != null) {
820                                 if (!RootContext.StdLib) {
821                                         orig_assembly_type = Type.GetType (Type.FullName);
822                                 } else {
823                                         string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
824                                         if (orig_version_path == null) {
825                                                 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
826                                                 return;
827                                         }
828
829                                         if (orig_sec_assembly == null) {
830                                                 string file = Path.Combine (orig_version_path, Driver.OutputFile);
831                                                 orig_sec_assembly = Assembly.LoadFile (file);
832                                         }
833
834                                         orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
835                                         if (orig_assembly_type == null) {
836                                                 Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' was not found in previous version of assembly");
837                                                 return;
838                                         }
839                                 }
840                         }
841
842                         SecurityAttribute sa;
843                         // For all non-selfreferencing security attributes we can avoid all hacks
844                         if (orig_assembly_type == null) {
845                                 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
846
847                                 if (prop_info_arr != null) {
848                                         for (int i = 0; i < prop_info_arr.Length; ++i) {
849                                                 PropertyInfo pi = prop_info_arr [i];
850                                                 pi.SetValue (sa, prop_values_arr [i], null);
851                                         }
852                                 }
853                         } else {
854                                 // HACK: All security attributes have same ctor syntax
855                                 sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
856
857                                 // All types are from newly created assembly but for invocation with old one we need to convert them
858                                 if (prop_info_arr != null) {
859                                         for (int i = 0; i < prop_info_arr.Length; ++i) {
860                                                 PropertyInfo emited_pi = prop_info_arr [i];
861                                                 PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
862
863                                                 object old_instance = pi.PropertyType.IsEnum ?
864                                                         System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
865                                                         prop_values_arr [i];
866
867                                                 pi.SetValue (sa, old_instance, null);
868                                         }
869                                 }
870                         }
871
872                         IPermission perm;
873                         perm = sa.CreatePermission ();
874                         SecurityAction action = GetSecurityActionValue ();
875
876                         // IS is correct because for corlib we are using an instance from old corlib
877                         if (!(perm is System.Security.CodeAccessPermission)) {
878                                 switch (action) {
879                                         case SecurityAction.Demand:
880                                                 action = (SecurityAction)13;
881                                                 break;
882                                         case SecurityAction.LinkDemand:
883                                                 action = (SecurityAction)14;
884                                                 break;
885                                         case SecurityAction.InheritanceDemand:
886                                                 action = (SecurityAction)15;
887                                                 break;
888                                 }
889                         }
890
891                         PermissionSet ps = (PermissionSet)permissions [action];
892                         if (ps == null) {
893                                 if (sa is PermissionSetAttribute)
894                                         ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
895                                 else
896                                         ps = new PermissionSet (PermissionState.None);
897
898                                 permissions.Add (action, ps);
899                         } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
900                                 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
901                                 permissions [action] = ps;
902                         }
903                         ps.AddPermission (perm);
904                 }
905
906                 object GetValue (object value)
907                 {
908                         if (value is EnumConstant)
909                                 return ((EnumConstant) value).GetValue ();
910                         else
911                                 return value;                           
912                 }
913
914                 object GetPropertyValue (string name)
915                 {
916                         if (prop_info_arr == null)
917                                 return null;
918
919                         for (int i = 0; i < prop_info_arr.Length; ++i) {
920                                 if (prop_info_arr [i].Name == name)
921                                         return prop_values_arr [i];
922                         }
923
924                         return null;
925                 }
926
927                 object GetFieldValue (string name)
928                 {
929                         int i;
930                         if (field_info_arr == null)
931                                 return null;
932                         i = 0;
933                         foreach (FieldInfo fi in field_info_arr) {
934                                 if (fi.Name == name)
935                                         return GetValue (field_values_arr [i]);
936                                 i++;
937                         }
938                         return null;
939                 }
940
941                 public UnmanagedMarshal GetMarshal (Attributable attr)
942                 {
943                         UnmanagedType UnmanagedType;
944                         if (!RootContext.StdLib || pos_values [0].GetType () != typeof (UnmanagedType))
945                                 UnmanagedType = (UnmanagedType)System.Enum.ToObject (typeof (UnmanagedType), pos_values [0]);
946                         else
947                                 UnmanagedType = (UnmanagedType) pos_values [0];
948
949                         object value = GetFieldValue ("SizeParamIndex");
950                         if (value != null && UnmanagedType != UnmanagedType.LPArray) {
951                                 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
952                                 return null;
953                         }
954
955                         object o = GetFieldValue ("ArraySubType");
956                         UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
957                         
958                         switch (UnmanagedType) {
959                         case UnmanagedType.CustomMarshaler: {
960                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
961                                                                        BindingFlags.Static | BindingFlags.Public);
962                                 if (define_custom == null) {
963                                         Report.RuntimeMissingSupport (Location, "set marshal info");
964                                         return null;
965                                 }
966                                 
967                                 object [] args = new object [4];
968                                 args [0] = GetFieldValue ("MarshalTypeRef");
969                                 args [1] = GetFieldValue ("MarshalCookie");
970                                 args [2] = GetFieldValue ("MarshalType");
971                                 args [3] = Guid.Empty;
972                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
973                         }
974                         case UnmanagedType.LPArray: {
975                                 object size_const = GetFieldValue ("SizeConst");
976                                 object size_param_index = GetFieldValue ("SizeParamIndex");
977
978                                 if ((size_const != null) || (size_param_index != null)) {
979                                         MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
980                                         if (define_array == null) {
981                                                 Report.RuntimeMissingSupport (Location, "set marshal info");
982                                                 return null;
983                                         }
984                                 
985                                         object [] args = new object [3];
986                                         args [0] = array_sub_type;
987                                         args [1] = size_const == null ? -1 : size_const;
988                                         args [2] = size_param_index == null ? -1 : size_param_index;
989                                         return (UnmanagedMarshal) define_array.Invoke (null, args);
990                                 }
991                                 else
992                                         return UnmanagedMarshal.DefineLPArray (array_sub_type);
993                         }
994                         case UnmanagedType.SafeArray:
995                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
996                         
997                         case UnmanagedType.ByValArray:
998                                 FieldMember fm = attr as FieldMember;
999                                 if (fm == null) {
1000                                         Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1001                                         return null;
1002                                 }
1003                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1004                         
1005                         case UnmanagedType.ByValTStr:
1006                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1007                         
1008                         default:
1009                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1010                         }
1011                 }
1012
1013                 public CharSet GetCharSetValue ()
1014                 {
1015                         return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1016                 }
1017
1018                 public MethodImplOptions GetMethodImplOptions ()
1019                 {
1020                         if (pos_values [0].GetType () != typeof (MethodImplOptions))
1021                                 return (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values [0]);
1022                         return (MethodImplOptions)pos_values [0];
1023                 }
1024
1025                 public LayoutKind GetLayoutKindValue ()
1026                 {
1027                         if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
1028                                 return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
1029
1030                         return (LayoutKind)pos_values [0];
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, bool nameEscaped):
1260                         base (target, left_expr, identifier, args, loc, nameEscaped)
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                         if (mb.IsSpecialName) {
1675                                 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1676                                 if (pi != null) {
1677                                         // FIXME: This is buggy as properties from this assembly are included as well
1678                                         return null;
1679                                         //return GetMemberObsoleteAttribute (pi);
1680                                 }
1681                         }
1682
1683                         return GetMemberObsoleteAttribute (mb);
1684                 }
1685
1686                 /// <summary>
1687                 /// Returns instance of ObsoleteAttribute when member is obsolete
1688                 /// </summary>
1689                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1690                 {
1691                         object type_obsolete = analyzed_member_obsolete [mi];
1692                         if (type_obsolete == FALSE)
1693                                 return null;
1694
1695                         if (type_obsolete != null)
1696                                 return (ObsoleteAttribute)type_obsolete;
1697
1698                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1699                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1700                         return oa;
1701                 }
1702
1703                 /// <summary>
1704                 /// Common method for Obsolete error/warning reporting.
1705                 /// </summary>
1706                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1707                 {
1708                         if (oa.IsError) {
1709                                 Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1710                                 return;
1711                         }
1712
1713                         if (oa.Message == null) {
1714                                 Report.Warning (612, loc, "`{0}' is obsolete", member);
1715                                 return;
1716                         }
1717                         if (RootContext.WarningLevel >= 2)
1718                                 Report.Warning (618, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
1719                 }
1720
1721                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1722                 {
1723                         object excluded = analyzed_method_excluded [mb];
1724                         if (excluded != null)
1725                                 return excluded == TRUE ? true : false;
1726                         
1727                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1728                         if (attrs.Length == 0) {
1729                                 analyzed_method_excluded.Add (mb, FALSE);
1730                                 return false;
1731                         }
1732
1733                         foreach (ConditionalAttribute a in attrs) {
1734                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1735                                         analyzed_method_excluded.Add (mb, FALSE);
1736                                         return false;
1737                                 }
1738                         }
1739                         analyzed_method_excluded.Add (mb, TRUE);
1740                         return true;
1741                 }
1742
1743                 /// <summary>
1744                 /// Analyzes class whether it has attribute which has ConditionalAttribute
1745                 /// and its condition is not defined.
1746                 /// </summary>
1747                 public static bool IsAttributeExcluded (Type type)
1748                 {
1749                         if (!type.IsClass)
1750                                 return false;
1751
1752                         Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1753
1754                         // TODO: add caching
1755                         // TODO: merge all Type bases attribute caching to one cache to save memory
1756                         if (class_decl == null) {
1757                                 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1758                                 foreach (ConditionalAttribute ca in attributes) {
1759                                         if (RootContext.AllDefines.Contains (ca.ConditionString))
1760                                                 return false;
1761                                 }
1762                                 return attributes.Length > 0;
1763                         }
1764
1765                         return class_decl.IsExcluded ();
1766                 }
1767         }
1768 }