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