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