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