imported everything from my branch (which is slightly harmless).
[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                                 if (!for_assembly)
828                                         return true;
829                                 break;
830
831                         case SecurityAction.RequestMinimum:
832                         case SecurityAction.RequestOptional:
833                         case SecurityAction.RequestRefuse:
834                                 if (for_assembly)
835                                         return true;
836                                 break;
837
838                         default:
839                                 Error_AttributeEmitError ("SecurityAction is out of range X");
840                                 return false;
841                         }
842
843                         Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
844                         return false;
845                 }
846
847                 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
848                 {
849                         return (SecurityAction)pos_values [0];
850                 }
851
852                 /// <summary>
853                 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
854                 /// </summary>
855                 /// <returns></returns>
856                 public void ExtractSecurityPermissionSet (ListDictionary permissions)
857                 {
858                         if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
859                                 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
860                                 return;
861                         }
862
863                         SecurityAttribute sa;
864                         // For all assemblies except corlib we can avoid all hacks
865                         if (RootContext.StdLib) {
866                                 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
867
868                                 if (prop_info_arr != null) {
869                                         for (int i = 0; i < prop_info_arr.Length; ++i) {
870                                                 PropertyInfo pi = prop_info_arr [i];
871                                                 pi.SetValue (sa, prop_values_arr [i], null);
872                                         }
873                                 }
874                         } else {
875                                 Type temp_type = Type.GetType (Type.FullName);
876                                 // HACK: All mscorlib attributes have same ctor syntax
877                                 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
878
879                                 // All types are from newly created corlib but for invocation with old we need to convert them
880                                 if (prop_info_arr != null) {
881                                         for (int i = 0; i < prop_info_arr.Length; ++i) {
882                                                 PropertyInfo emited_pi = prop_info_arr [i];
883                                                 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
884
885                                                 object old_instance = pi.PropertyType.IsEnum ?
886                                                         System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
887                                                         prop_values_arr [i];
888
889                                                 pi.SetValue (sa, old_instance, null);
890                                         }
891                                 }
892                         }
893
894                         IPermission perm;
895                         perm = sa.CreatePermission ();
896                         SecurityAction action = GetSecurityActionValue ();
897
898                         // IS is correct because for corlib we are using an instance from old corlib
899                         if (!(perm is System.Security.CodeAccessPermission)) {
900                                 switch (action) {
901                                         case SecurityAction.Demand:
902                                                 action = (SecurityAction)13;
903                                                 break;
904                                         case SecurityAction.LinkDemand:
905                                                 action = (SecurityAction)14;
906                                                 break;
907                                         case SecurityAction.InheritanceDemand:
908                                                 action = (SecurityAction)15;
909                                                 break;
910                                 }
911                         }
912
913                         PermissionSet ps = (PermissionSet)permissions [action];
914                         if (ps == null) {
915                                 if (sa is PermissionSetAttribute)
916                                         ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
917                                 else
918                                         ps = new PermissionSet (PermissionState.None);
919
920                                 permissions.Add (action, ps);
921                         } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
922                                 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
923                                 permissions [action] = ps;
924                         }
925                         ps.AddPermission (perm);
926                 }
927
928                 object GetValue (object value)
929                 {
930                         if (value is EnumConstant)
931                                 return ((EnumConstant) value).GetValue ();
932                         else
933                                 return value;                           
934                 }
935
936                 object GetPropertyValue (string name)
937                 {
938                         if (prop_info_arr == null)
939                                 return null;
940
941                         for (int i = 0; i < prop_info_arr.Length; ++i) {
942                                 if (prop_info_arr [i].Name == name)
943                                         return prop_values_arr [i];
944                         }
945
946                         return null;
947                 }
948
949                 object GetFieldValue (string name)
950                 {
951                         int i;
952                         if (field_info_arr == null)
953                                 return null;
954                         i = 0;
955                         foreach (FieldInfo fi in field_info_arr) {
956                                 if (fi.Name == name)
957                                         return GetValue (field_values_arr [i]);
958                                 i++;
959                         }
960                         return null;
961                 }
962
963                 public UnmanagedMarshal GetMarshal (Attributable attr)
964                 {
965                         UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
966
967                         object value = GetFieldValue ("SizeParamIndex");
968                         if (value != null && UnmanagedType != UnmanagedType.LPArray) {
969                                 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
970                                 return null;
971                         }
972
973                         object o = GetFieldValue ("ArraySubType");
974                         UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
975                         
976                         switch (UnmanagedType) {
977                         case UnmanagedType.CustomMarshaler: {
978                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
979                                                                        BindingFlags.Static | BindingFlags.Public);
980                                 if (define_custom == null) {
981                                         Report.RuntimeMissingSupport (Location, "set marshal info");
982                                         return null;
983                                 }
984                                 
985                                 object [] args = new object [4];
986                                 args [0] = GetFieldValue ("MarshalTypeRef");
987                                 args [1] = GetFieldValue ("MarshalCookie");
988                                 args [2] = GetFieldValue ("MarshalType");
989                                 args [3] = Guid.Empty;
990                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
991                         }
992                         case UnmanagedType.LPArray: {
993                                 object size_const = GetFieldValue ("SizeConst");
994                                 object size_param_index = GetFieldValue ("SizeParamIndex");
995
996                                 if ((size_const != null) || (size_param_index != null)) {
997                                         MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
998                                         if (define_array == null) {
999                                                 Report.RuntimeMissingSupport (Location, "set marshal info");
1000                                                 return null;
1001                                         }
1002                                 
1003                                         object [] args = new object [3];
1004                                         args [0] = array_sub_type;
1005                                         args [1] = size_const == null ? -1 : size_const;
1006                                         args [2] = size_param_index == null ? -1 : size_param_index;
1007                                         return (UnmanagedMarshal) define_array.Invoke (null, args);
1008                                 }
1009                                 else
1010                                         return UnmanagedMarshal.DefineLPArray (array_sub_type);
1011                         }
1012                         case UnmanagedType.SafeArray:
1013                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1014                         
1015                         case UnmanagedType.ByValArray:
1016                                 FieldMember fm = attr as FieldMember;
1017                                 if (fm == null) {
1018                                         Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1019                                         return null;
1020                                 }
1021                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1022                         
1023                         case UnmanagedType.ByValTStr:
1024                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1025                         
1026                         default:
1027                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1028                         }
1029                 }
1030
1031                 public CharSet GetCharSetValue ()
1032                 {
1033                         return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1034                 }
1035
1036                 public MethodImplOptions GetMethodImplOptions ()
1037                 {
1038                         return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
1039                 }
1040
1041                 public LayoutKind GetLayoutKindValue ()
1042                 {
1043                         return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
1044                 }
1045
1046                 /// <summary>
1047                 /// Emit attribute for Attributable symbol
1048                 /// </summary>
1049                 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1050                 {
1051                         CustomAttributeBuilder cb = Resolve (ec);
1052                         if (cb == null)
1053                                 return;
1054
1055                         AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1056                         if ((usage_attr.ValidOn & Target) == 0) {
1057                                 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
1058                                 return;
1059                         }
1060
1061                         try {
1062                                 ias.ApplyAttributeBuilder (this, cb);
1063                         }
1064                         catch (Exception e) {
1065                                 Error_AttributeEmitError (e.Message);
1066                                 return;
1067                         }
1068
1069                         if (!usage_attr.AllowMultiple) {
1070                                 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1071                                 if (emitted_targets == null) {
1072                                         emitted_targets = new ArrayList ();
1073                                         emitted_attr.Add (Type, emitted_targets);
1074                                 } else if (emitted_targets.Contains (Target)) {
1075                                 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1076                                         return;
1077                                 }
1078                                 emitted_targets.Add (Target);
1079                         }
1080
1081                         if (!RootContext.VerifyClsCompliance)
1082                                 return;
1083
1084                         // Here we are testing attribute arguments for array usage (error 3016)
1085                         if (ias.IsClsComplianceRequired (ec.DeclSpace)) {
1086                                 if (Arguments == null)
1087                                         return;
1088
1089                                 ArrayList pos_args = (ArrayList) Arguments [0];
1090                                 if (pos_args != null) {
1091                                         foreach (Argument arg in pos_args) { 
1092                                                 // Type is undefined (was error 246)
1093                                                 if (arg.Type == null)
1094                                                         return;
1095
1096                                                 if (arg.Type.IsArray) {
1097                                                         Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1098                                                         return;
1099                                                 }
1100                                         }
1101                                 }
1102                         
1103                                 if (Arguments.Count < 2)
1104                                         return;
1105                         
1106                                 ArrayList named_args = (ArrayList) Arguments [1];
1107                                 foreach (DictionaryEntry de in named_args) {
1108                                         Argument arg  = (Argument) de.Value;
1109
1110                                         // Type is undefined (was error 246)
1111                                         if (arg.Type == null)
1112                                                 return;
1113
1114                                         if (arg.Type.IsArray) {
1115                                                 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1116                                                 return;
1117                                         }
1118                                 }
1119                         }
1120                 }
1121                 
1122                 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1123                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
1124                 {
1125                         if (pos_values == null)
1126                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1127                                 // But because a lot of attribute class code must be rewritten will be better to wait...
1128                                 Resolve (ec);
1129
1130                         if (resolve_error)
1131                                 return null;
1132                         
1133                         string dll_name = (string)pos_values [0];
1134
1135                         // Default settings
1136                         CallingConvention cc = CallingConvention.Winapi;
1137                         CharSet charset = CodeGen.Module.DefaultCharSet;
1138                         bool preserve_sig = true;
1139                         string entry_point = name;
1140                         bool best_fit_mapping = false;
1141                         bool throw_on_unmappable = false;
1142                         bool exact_spelling = false;
1143                         bool set_last_error = false;
1144
1145                         bool best_fit_mapping_set = false;
1146                         bool throw_on_unmappable_set = false;
1147                         bool exact_spelling_set = false;
1148                         bool set_last_error_set = false;
1149
1150                         MethodInfo set_best_fit = null;
1151                         MethodInfo set_throw_on = null;
1152                         MethodInfo set_exact_spelling = null;
1153                         MethodInfo set_set_last_error = null;
1154
1155                         if (field_info_arr != null) {
1156
1157                                 for (int i = 0; i < field_info_arr.Length; i++) {
1158                                         switch (field_info_arr [i].Name) {
1159                                                 case "BestFitMapping":
1160                                                         best_fit_mapping = (bool) field_values_arr [i];
1161                                                         best_fit_mapping_set = true;
1162                                                         break;
1163                                                 case "CallingConvention":
1164                                                         cc = (CallingConvention) field_values_arr [i];
1165                                                         break;
1166                                                 case "CharSet":
1167                                                         charset = (CharSet) field_values_arr [i];
1168                                                         break;
1169                                                 case "EntryPoint":
1170                                                         entry_point = (string) field_values_arr [i];
1171                                                         break;
1172                                                 case "ExactSpelling":
1173                                                         exact_spelling = (bool) field_values_arr [i];
1174                                                         exact_spelling_set = true;
1175                                                         break;
1176                                                 case "PreserveSig":
1177                                                         preserve_sig = (bool) field_values_arr [i];
1178                                                         break;
1179                                                 case "SetLastError":
1180                                                         set_last_error = (bool) field_values_arr [i];
1181                                                         set_last_error_set = true;
1182                                                         break;
1183                                                 case "ThrowOnUnmappableChar":
1184                                                         throw_on_unmappable = (bool) field_values_arr [i];
1185                                                         throw_on_unmappable_set = true;
1186                                                         break;
1187                                                 default: 
1188                                                         throw new InternalErrorException (field_info_arr [i].ToString ());
1189                                         }
1190                                 }
1191                         }
1192
1193                         if (throw_on_unmappable_set || best_fit_mapping_set || exact_spelling_set || set_last_error_set) {
1194                                 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1195                                 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1196                                 set_exact_spelling = typeof (MethodBuilder).GetMethod ("set_ExactSpelling", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1197                                 set_set_last_error = typeof (MethodBuilder).GetMethod ("set_SetLastError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1198
1199                                 if ((set_best_fit == null) || (set_throw_on == null) || (set_exact_spelling == null) || (set_set_last_error == null)) {
1200                                         Report.Error (-1, Location,
1201                                                                   "The ThrowOnUnmappableChar, BestFitMapping, SetLastError, and ExactSpelling attributes can only be emitted when running on the mono runtime.");
1202                                         return null;
1203                                 }
1204                         }
1205
1206                         try {
1207                                 MethodBuilder mb = builder.DefinePInvokeMethod (
1208                                         name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1209                                         CallingConventions.Standard, ret_type, param_types, cc, charset);
1210
1211                                 if (preserve_sig)
1212                                         mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1213
1214                                 if (throw_on_unmappable_set)
1215                                         set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1216                                 if (best_fit_mapping_set)
1217                                         set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1218                                 if (exact_spelling_set)
1219                                         set_exact_spelling.Invoke  (mb, 0, null, new object [] { exact_spelling }, null);
1220                                 if (set_last_error_set)
1221                                         set_set_last_error.Invoke  (mb, 0, null, new object [] { set_last_error }, null);
1222                         
1223                                 return mb;
1224                         }
1225                         catch (ArgumentException e) {
1226                                 Error_AttributeEmitError (e.Message);
1227                                 return null;
1228                         }
1229                 }
1230
1231                 private Expression GetValue () 
1232                 {
1233                         if ((Arguments == null) || (Arguments.Count < 1))
1234                                 return null;
1235                         ArrayList al = (ArrayList) Arguments [0];
1236                         if ((al == null) || (al.Count < 1))
1237                                 return null;
1238                         Argument arg = (Argument) al [0];
1239                         if ((arg == null) || (arg.Expr == null))
1240                                 return null;
1241                         return arg.Expr;
1242                 }
1243
1244                 public string GetString () 
1245                 {
1246                         Expression e = GetValue ();
1247                         if (e is StringLiteral)
1248                                 return (e as StringLiteral).Value;
1249                         return null;
1250                 }
1251
1252                 public bool GetBoolean () 
1253                 {
1254                         Expression e = GetValue ();
1255                         if (e is BoolLiteral)
1256                                 return (e as BoolLiteral).Value;
1257                         return false;
1258                 }
1259         }
1260         
1261
1262         /// <summary>
1263         /// For global attributes (assembly, module) we need special handling.
1264         /// Attributes can be located in the several files
1265         /// </summary>
1266         public class GlobalAttribute: Attribute
1267         {
1268                 public readonly NamespaceEntry ns;
1269
1270                 public GlobalAttribute (TypeContainer container, string target, 
1271                                         Expression left_expr, string identifier, ArrayList args, Location loc):
1272                         base (target, left_expr, identifier, args, loc)
1273                 {
1274                         ns = container.NamespaceEntry;
1275                 }
1276
1277                 void Enter ()
1278                 {
1279                         // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1280                         // each time a new file is parsed.  However, we need to use the NamespaceEntry
1281                         // in effect where the attribute was used.  Since code elsewhere cannot assume
1282                         // that the NamespaceEntry is right, just overwrite it.
1283                         //
1284                         // Precondition: RootContext.Tree.Types == null
1285
1286                         if (RootContext.Tree.Types.NamespaceEntry != null)
1287                                 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1288
1289                         RootContext.Tree.Types.NamespaceEntry = ns;
1290                 }
1291
1292                 void Leave ()
1293                 {
1294                         RootContext.Tree.Types.NamespaceEntry = null;
1295                 }
1296
1297                 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
1298                 {
1299                         try {
1300                                 Enter ();
1301                                 return base.ResolveAsTypeStep (expr, ec);
1302                         }
1303                         finally {
1304                                 Leave ();
1305                         }
1306                 }
1307
1308                 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1309                 {
1310                         try {
1311                                 Enter ();
1312                                 return base.ResolveArguments (ec);
1313                         }
1314                         finally {
1315                                 Leave ();
1316                         }
1317                 }
1318         }
1319
1320         public class Attributes {
1321                 public ArrayList Attrs;
1322
1323                 public Attributes (Attribute a)
1324                 {
1325                         Attrs = new ArrayList ();
1326                         Attrs.Add (a);
1327                 }
1328
1329                 public Attributes (ArrayList attrs)
1330                 {
1331                         Attrs = attrs;
1332                 }
1333
1334                 public void AddAttributes (ArrayList attrs)
1335                 {
1336                         Attrs.AddRange (attrs);
1337                 }
1338
1339                 /// <summary>
1340                 /// Checks whether attribute target is valid for the current element
1341                 /// </summary>
1342                 public bool CheckTargets (Attributable member)
1343                 {
1344                         string[] valid_targets = member.ValidAttributeTargets;
1345                         foreach (Attribute a in Attrs) {
1346                                 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1347                                         a.Target = member.AttributeTargets;
1348                                         continue;
1349                                 }
1350
1351                                 // TODO: we can skip the first item
1352                                 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1353                                         switch (a.ExplicitTarget) {
1354                                                 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1355                                                 case "param": a.Target = AttributeTargets.Parameter; continue;
1356                                                 case "field": a.Target = AttributeTargets.Field; continue;
1357                                                 case "method": a.Target = AttributeTargets.Method; continue;
1358                                                 case "property": a.Target = AttributeTargets.Property; continue;
1359                                         }
1360                                         throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1361                                 }
1362
1363                                 StringBuilder sb = new StringBuilder ();
1364                                 foreach (string s in valid_targets) {
1365                                         sb.Append (s);
1366                                         sb.Append (", ");
1367                                 }
1368                                 sb.Remove (sb.Length - 2, 2);
1369                                 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 ());
1370                                 return false;
1371                         }
1372                         return true;
1373                 }
1374
1375                 public Attribute Search (Type t, EmitContext ec)
1376                 {
1377                         foreach (Attribute a in Attrs) {
1378                                 if (a.ResolveType (ec) == t)
1379                                         return a;
1380                         }
1381                         return null;
1382                 }
1383
1384                 /// <summary>
1385                 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1386                 /// </summary>
1387                 public Attribute[] SearchMulti (Type t, EmitContext ec)
1388                 {
1389                         ArrayList ar = null;
1390
1391                         foreach (Attribute a in Attrs) {
1392                                 if (a.ResolveType (ec) == t) {
1393                                         if (ar == null)
1394                                                 ar = new ArrayList ();
1395                                         ar.Add (a);
1396                                 }
1397                         }
1398
1399                         return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1400                 }
1401
1402                 public void Emit (EmitContext ec, Attributable ias)
1403                 {
1404                         CheckTargets (ias);
1405
1406                         ListDictionary ld = new ListDictionary ();
1407
1408                         foreach (Attribute a in Attrs)
1409                                 a.Emit (ec, ias, ld);
1410                 }
1411
1412                 public bool Contains (Type t, EmitContext ec)
1413                 {
1414                         return Search (t, ec) != null;
1415                 }
1416         }
1417
1418         /// <summary>
1419         /// Helper class for attribute verification routine.
1420         /// </summary>
1421         sealed class AttributeTester
1422         {
1423                 static PtrHashtable analyzed_types = new PtrHashtable ();
1424                 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1425                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1426                 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1427
1428                 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1429
1430                 static object TRUE = new object ();
1431                 static object FALSE = new object ();
1432
1433                 private AttributeTester ()
1434                 {
1435                 }
1436
1437                 public enum Result {
1438                         Ok,
1439                         RefOutArrayError,
1440                         ArrayArrayError
1441                 }
1442
1443                 /// <summary>
1444                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1445                 /// It tests differing only in ref or out, or in array rank.
1446                 /// </summary>
1447                 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1448                 {
1449                         if (types_a == null || types_b == null)
1450                                 return Result.Ok;
1451
1452                         if (types_a.Length != types_b.Length)
1453                                 return Result.Ok;
1454
1455                         Result result = Result.Ok;
1456                         for (int i = 0; i < types_b.Length; ++i) {
1457                                 Type aType = types_a [i];
1458                                 Type bType = types_b [i];
1459
1460                                 if (aType.IsArray && bType.IsArray) {
1461                                         Type a_el_type = aType.GetElementType ();
1462                                         Type b_el_type = bType.GetElementType ();
1463                                         if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1464                                                 result = Result.RefOutArrayError;
1465                                                 continue;
1466                                         }
1467
1468                                         if (a_el_type.IsArray || b_el_type.IsArray) {
1469                                                 result = Result.ArrayArrayError;
1470                                                 continue;
1471                                         }
1472                                 }
1473
1474                                 Type aBaseType = aType;
1475                                 bool is_either_ref_or_out = false;
1476
1477                                 if (aType.IsByRef || aType.IsPointer) {
1478                                         aBaseType = aType.GetElementType ();
1479                                         is_either_ref_or_out = true;
1480                                 }
1481
1482                                 Type bBaseType = bType;
1483                                 if (bType.IsByRef || bType.IsPointer) 
1484                                 {
1485                                         bBaseType = bType.GetElementType ();
1486                                         is_either_ref_or_out = !is_either_ref_or_out;
1487                                 }
1488
1489                                 if (aBaseType != bBaseType)
1490                                         return Result.Ok;
1491
1492                                 if (is_either_ref_or_out)
1493                                         result = Result.RefOutArrayError;
1494                         }
1495                         return result;
1496                 }
1497
1498                 /// <summary>
1499                 /// Goes through all parameters and test if they are CLS-Compliant.
1500                 /// </summary>
1501                 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1502                 {
1503                         if (fixedParameters == null)
1504                                 return true;
1505
1506                         foreach (Parameter arg in fixedParameters) {
1507                                 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1508                                         Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1509                                         return false;
1510                                 }
1511                         }
1512                         return true;
1513                 }
1514
1515
1516                 /// <summary>
1517                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1518                 /// </summary>
1519                 public static bool IsClsCompliant (Type type) 
1520                 {
1521                         if (type == null)
1522                                 return true;
1523
1524                         object type_compliance = analyzed_types[type];
1525                         if (type_compliance != null)
1526                                 return type_compliance == TRUE;
1527
1528                         if (type.IsPointer) {
1529                                 analyzed_types.Add (type, null);
1530                                 return false;
1531                         }
1532
1533                         bool result;
1534                         if (type.IsArray || type.IsByRef)       {
1535                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1536                         } else {
1537                                 result = AnalyzeTypeCompliance (type);
1538                         }
1539                         analyzed_types.Add (type, result ? TRUE : FALSE);
1540                         return result;
1541                 }        
1542         
1543                 /// <summary>
1544                 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1545                 /// </summary>
1546                 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1547                 {
1548                         FieldBase fb = TypeManager.GetField (fi);
1549                         if (fb != null) {
1550                                 return fb as IFixedBuffer;
1551                         }
1552
1553                         object o = fixed_buffer_cache [fi];
1554                         if (o == null) {
1555                                 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1556                                         fixed_buffer_cache.Add (fi, FALSE);
1557                                         return null;
1558                                 }
1559                                 
1560                                 IFixedBuffer iff = new FixedFieldExternal (fi);
1561                                 fixed_buffer_cache.Add (fi, iff);
1562                                 return iff;
1563                         }
1564
1565                         if (o == FALSE)
1566                                 return null;
1567
1568                         return (IFixedBuffer)o;
1569                 }
1570
1571                 public static void VerifyModulesClsCompliance ()
1572                 {
1573                         Module[] modules = TypeManager.Modules;
1574                         if (modules == null)
1575                                 return;
1576
1577                         // The first module is generated assembly
1578                         for (int i = 1; i < modules.Length; ++i) {
1579                                 Module module = modules [i];
1580                                 if (!IsClsCompliant (module)) {
1581                                         Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1582                                         return;
1583                                 }
1584                         }
1585                 }
1586
1587                 /// <summary>
1588                 /// Tests container name for CLS-Compliant name (differing only in case)
1589                 /// </summary>
1590                 public static void VerifyTopLevelNameClsCompliance ()
1591                 {
1592                         Hashtable locase_table = new Hashtable ();
1593
1594                         // Convert imported type names to lower case and ignore not cls compliant
1595                         foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1596                                 Type t = (Type)de.Value;
1597                                 if (!AttributeTester.IsClsCompliant (t))
1598                                         continue;
1599
1600                                 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1601                         }
1602
1603                         foreach (DictionaryEntry de in RootContext.Tree.AllDecls) {
1604                                 if (!(de.Key is MemberName))
1605                                         throw new InternalErrorException ("");
1606                                 DeclSpace decl = (DeclSpace) de.Value;
1607                                 if (!decl.IsClsComplianceRequired (decl))
1608                                         continue;
1609
1610                                 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1611                                 if (!locase_table.Contains (lcase)) {
1612                                         locase_table.Add (lcase, decl);
1613                                         continue;
1614                                 }
1615
1616                                 object conflict = locase_table [lcase];
1617                                 if (conflict is Type)
1618                                         Report.SymbolRelatedToPreviousError ((Type)conflict);
1619                                 else
1620                                         Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1621
1622                                 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1623                         }
1624                 }
1625
1626                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1627                 {
1628                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1629                         if (CompliantAttribute.Length == 0)
1630                                 return false;
1631
1632                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1633                 }
1634
1635                 static bool AnalyzeTypeCompliance (Type type)
1636                 {
1637                         if (type.IsGenericInstance)
1638                                 type = type.GetGenericTypeDefinition ();
1639                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1640                         if (ds != null)
1641                                 return ds.IsClsComplianceRequired (ds.Parent);
1642
1643                         if (type.IsGenericParameter)
1644                                 return true;
1645
1646                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1647                         if (CompliantAttribute.Length == 0) 
1648                                 return IsClsCompliant (type.Assembly);
1649
1650                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1651                 }
1652
1653                 /// <summary>
1654                 /// Returns instance of ObsoleteAttribute when type is obsolete
1655                 /// </summary>
1656                 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1657                 {
1658                         object type_obsolete = analyzed_types_obsolete [type];
1659                         if (type_obsolete == FALSE)
1660                                 return null;
1661
1662                         if (type_obsolete != null)
1663                                 return (ObsoleteAttribute)type_obsolete;
1664
1665                         ObsoleteAttribute result = null;
1666                         if (type.IsByRef || type.IsArray || type.IsPointer) {
1667                                 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1668                         } else if (type.IsGenericParameter || type.IsGenericInstance)
1669                                 return null;
1670                         else {
1671                                 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1672
1673                                 // Type is external, we can get attribute directly
1674                                 if (type_ds == null) {
1675                                         object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1676                                         if (attribute.Length == 1)
1677                                                 result = (ObsoleteAttribute)attribute [0];
1678                                 } else {
1679                                         result = type_ds.GetObsoleteAttribute (type_ds);
1680                                 }
1681                         }
1682
1683                         analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1684                         return result;
1685                 }
1686
1687                 /// <summary>
1688                 /// Returns instance of ObsoleteAttribute when method is obsolete
1689                 /// </summary>
1690                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1691                 {
1692                         IMethodData mc = TypeManager.GetMethod (mb);
1693                         if (mc != null) 
1694                                 return mc.GetObsoleteAttribute ();
1695
1696                         // compiler generated methods are not registered by AddMethod
1697                         if (mb.DeclaringType is TypeBuilder)
1698                                 return null;
1699
1700                         PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1701                         if (pi != null)
1702                                 return GetMemberObsoleteAttribute (pi);
1703
1704                         return GetMemberObsoleteAttribute (mb);
1705                 }
1706
1707                 /// <summary>
1708                 /// Returns instance of ObsoleteAttribute when member is obsolete
1709                 /// </summary>
1710                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1711                 {
1712                         object type_obsolete = analyzed_member_obsolete [mi];
1713                         if (type_obsolete == FALSE)
1714                                 return null;
1715
1716                         if (type_obsolete != null)
1717                                 return (ObsoleteAttribute)type_obsolete;
1718
1719                         if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1720                                 return null;
1721
1722                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1723                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1724                         return oa;
1725                 }
1726
1727                 /// <summary>
1728                 /// Common method for Obsolete error/warning reporting.
1729                 /// </summary>
1730                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1731                 {
1732                         if (oa.IsError) {
1733                                 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1734                                 return;
1735                         }
1736
1737                         if (oa.Message == null) {
1738                                 Report.Warning (612, loc, "'{0}' is obsolete", member);
1739                                 return;
1740                         }
1741                         if (RootContext.WarningLevel >= 2)
1742                                 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1743                 }
1744
1745                 public static bool IsConditionalMethodExcluded (MethodBase mb)
1746                 {
1747                         object excluded = analyzed_method_excluded [mb];
1748                         if (excluded != null)
1749                                 return excluded == TRUE ? true : false;
1750
1751                         if (mb.Mono_IsInflatedMethod)
1752                                 return false;
1753                         
1754                         ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1755                         if (attrs.Length == 0) {
1756                                 analyzed_method_excluded.Add (mb, FALSE);
1757                                 return false;
1758                         }
1759
1760                         foreach (ConditionalAttribute a in attrs) {
1761                                 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1762                                         analyzed_method_excluded.Add (mb, FALSE);
1763                                         return false;
1764                                 }
1765                         }
1766                         analyzed_method_excluded.Add (mb, TRUE);
1767                         return true;
1768                 }
1769
1770                 /// <summary>
1771                 /// Analyzes class whether it has attribute which has ConditionalAttribute
1772                 /// and its condition is not defined.
1773                 /// </summary>
1774                 public static bool IsAttributeExcluded (Type type)
1775                 {
1776                         if (!type.IsClass)
1777                                 return false;
1778
1779                         Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1780
1781                         // TODO: add caching
1782                         // TODO: merge all Type bases attribute caching to one cache to save memory
1783                         if (class_decl == null) {
1784                                 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1785                                 foreach (ConditionalAttribute ca in attributes) {
1786                                         if (RootContext.AllDefines.Contains (ca.ConditionString))
1787                                                 return false;
1788                                 }
1789                                 return attributes.Length > 0;
1790                         }
1791
1792                         return class_decl.IsExcluded ();
1793                 }
1794         }
1795 }