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