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