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