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