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