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