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