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