2004-05-22 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / mcs / attribute.cs
1 //
2 // attribute.cs: Attribute Handler
3 //
4 // Author: Ravi Pratap (ravi@ximian.com)
5 //
6 // Licensed under the terms of the GNU GPL
7 //
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
9 //
10 //
11
12 using System;
13 using System.Diagnostics;
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.InteropServices;
19 using System.Runtime.CompilerServices;
20 using System.Text;
21
22 namespace Mono.CSharp {
23
24         /// <summary>
25         ///   Base class for objects that can have Attributes applied to them.
26         /// </summary>
27         public abstract class Attributable {
28                 /// <summary>
29                 ///   Attributes for this type
30                 /// </summary>
31                 Attributes attributes;
32
33                 public Attributable(Attributes attrs)
34                 {
35                         attributes = attrs;
36                         if (attributes != null)
37                                 attributes.CheckTargets (ValidAttributeTargets);
38                 }
39
40                 public Attributes OptAttributes 
41                 {
42                         get {
43                                 return attributes;
44                         }
45                         set {
46                                 attributes = value;
47                                 if (attributes != null)
48                                         attributes.CheckTargets (ValidAttributeTargets);
49                         }
50                 }
51
52                 /// <summary>
53                 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
54                 /// </summary>
55                 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
56
57                 /// <summary>
58                 /// Returns combination of enabled AttributeTargets
59                 /// </summary>
60                 public abstract AttributeTargets AttributeTargets { get; }
61
62                 public abstract bool IsClsCompliaceRequired (DeclSpace ds);
63
64                 /// <summary>
65                 /// Gets list of valid attribute targets for explicit target declaration.
66                 /// The first array item is default target. Don't break this rule.
67                 /// </summary>
68                 protected abstract string[] ValidAttributeTargets { get; }
69         };
70
71         public class Attribute {
72                 public string Target;
73                 public readonly string    Name;
74                 public readonly ArrayList Arguments;
75
76                 public readonly Location Location;
77
78                 public Type Type;
79                 
80                 // Is non-null if type is AttributeUsageAttribute
81                 AttributeUsageAttribute usage_attribute;
82
83                 public AttributeUsageAttribute UsageAttribute {
84                         get {
85                                 return usage_attribute;
86                         }
87                 }
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, string name, ArrayList args, Location loc)
103                 {
104                         Name = name;
105                         Arguments = args;
106                         Location = loc;
107                         Target = target;
108                 }
109
110                 void Error_InvalidNamedArgument (string name)
111                 {
112                         Report.Error (617, Location, "'" + name + "' is not a valid named attribute " +
113                                       "argument. Named attribute arguments must be fields which are not " +
114                                       "readonly, static or const, or properties with a set accessor which "+
115                                       "are not static.");
116                 }
117
118                 static void Error_AttributeArgumentNotValid (Location loc)
119                 {
120                         Report.Error (182, loc,
121                                       "An attribute argument must be a constant expression, typeof " +
122                                       "expression or array creation expression");
123                 }
124
125                 void Error_AttributeConstructorMismatch ()
126                 {
127                         Report.Error (-6, Location,
128                                       "Could not find a constructor for this argument list.");
129                 }
130
131                 /// <summary>
132                 ///   Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
133                 /// </summary>
134                 protected virtual Type CheckAttributeType (EmitContext ec, bool complain)
135                 {
136                         Type t1 = RootContext.LookupType (ec.DeclSpace, Name, true, Location);
137
138                         // FIXME: Shouldn't do this for quoted attributes: [@A]
139                         Type t2 = RootContext.LookupType (ec.DeclSpace, Name + "Attribute", true, Location);
140
141                         String err0616 = null;
142
143                         if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
144                                 t1 = null;
145                                 err0616 = "'" + Name + "': is not an attribute class";
146                         }
147                         if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
148                                 t2 = null;
149                                 err0616 = (err0616 != null) 
150                                         ? "Neither '" + Name + "' nor '" + Name + "Attribute' is an attribute class"
151                                         : "'" + Name + "Attribute': is not an attribute class";
152                         }
153
154                         if (t1 != null && t2 != null) {
155                                 Report.Error(1614, Location, "'" + Name + "': is ambiguous; " 
156                                              + " use either '@" + Name + "' or '" + Name + "Attribute'");
157                                 return null;
158                         }
159                         if (t1 != null)
160                                 return t1;
161                         if (t2 != null)
162                                 return t2;
163
164                         if (err0616 != null) {
165                                 Report.Error (616, Location, err0616);
166                                 return null;
167                         }
168
169                         if (complain)
170                                 Report.Error (246, Location, 
171                                               "Could not find attribute '" + Name 
172                                               + "' (are you missing a using directive or an assembly reference ?)");
173                         return null;
174                 }
175
176                 public Type ResolveType (EmitContext ec, bool complain)
177                 {
178                         if (Type == null)
179                                 Type = CheckAttributeType (ec, complain);
180                         return Type;
181                 }
182
183                 /// <summary>
184                 ///   Validates the guid string
185                 /// </summary>
186                 bool ValidateGuid (string guid)
187                 {
188                         try {
189                                 new Guid (guid);
190                                 return true;
191                         } catch {
192                                 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
193                                 return false;
194                         }
195                 }
196
197                 string GetFullMemberName (string member)
198                 {
199                         return Type.FullName + '.' + member;
200                 }
201
202                 //
203                 // Given an expression, if the expression is a valid attribute-argument-expression
204                 // returns an object that can be used to encode it, or null on failure.
205                 //
206                 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
207                 {
208                         if (e is Constant) {
209                                 result = ((Constant) e).GetValue ();
210                                 return true;
211                         } else if (e is TypeOf) {
212                                 result = ((TypeOf) e).TypeArg;
213                                 return true;
214                         } else if (e is ArrayCreation){
215                                 result =  ((ArrayCreation) e).EncodeAsAttribute ();
216                                 if (result != null)
217                                         return true;
218                         } else if (e is EmptyCast) {
219                                 result = e;
220                                 if (((EmptyCast) e).Child is Constant) {
221                                         result = ((Constant) ((EmptyCast)e).Child).GetValue();
222                                 }
223                                 return true;
224                         }
225
226                         result = null;
227                         Error_AttributeArgumentNotValid (loc);
228                         return false;
229                 }
230                 
231                 public CustomAttributeBuilder Resolve (EmitContext ec)
232                 {
233                         Type oldType = Type;
234                         
235                         // Sanity check.
236                         Type = CheckAttributeType (ec, true);
237                         if (oldType == null && Type == null)
238                                 return null;
239                         if (oldType != null && oldType != Type) {
240                                 Report.Error (-6, Location,
241                                               "Attribute {0} resolved to different types at different times: {1} vs. {2}",
242                                               Name, oldType, Type);
243                                 return null;
244                         }
245
246                         bool MethodImplAttr = false;
247                         bool MarshalAsAttr = false;
248                         bool GuidAttr = false;
249                         bool usage_attr = false;
250
251                         bool DoCompares = true;
252
253                         //
254                         // If we are a certain special attribute, we
255                         // set the information accordingly
256                         //
257                         
258                         if (Type == TypeManager.attribute_usage_type)
259                                 usage_attr = true;
260                         else if (Type == TypeManager.methodimpl_attr_type)
261                                 MethodImplAttr = true;
262                         else if (Type == TypeManager.marshal_as_attr_type)
263                                 MarshalAsAttr = true;
264                         else if (Type == TypeManager.guid_attr_type)
265                                 GuidAttr = true;
266                         else
267                                 DoCompares = false;
268
269                         // Now we extract the positional and named arguments
270                         
271                         ArrayList pos_args = new ArrayList ();
272                         ArrayList named_args = new ArrayList ();
273                         int pos_arg_count = 0;
274                         
275                         if (Arguments != null) {
276                                 pos_args = (ArrayList) Arguments [0];
277                                 if (pos_args != null)
278                                         pos_arg_count = pos_args.Count;
279                                 if (Arguments.Count > 1)
280                                         named_args = (ArrayList) Arguments [1];
281                         }
282
283                         pos_values = new object [pos_arg_count];
284
285                         //
286                         // First process positional arguments 
287                         //
288
289                         int i;
290                         for (i = 0; i < pos_arg_count; i++) {
291                                 Argument a = (Argument) pos_args [i];
292                                 Expression e;
293
294                                 if (!a.Resolve (ec, Location))
295                                         return null;
296
297                                 e = a.Expr;
298
299                                 object val;
300                                 if (!GetAttributeArgumentExpression (e, Location, out val))
301                                         return null;
302                                 
303                                 pos_values [i] = val;
304                                 if (DoCompares){
305                                         if (usage_attr)
306                                                 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
307                                         else if (MethodImplAttr)
308                                                 this.ImplOptions = (MethodImplOptions) pos_values [0];
309                                         else if (GuidAttr){
310                                                 //
311                                                 // we will later check the validity of the type
312                                                 //
313                                                 if (pos_values [0] is string){
314                                                         if (!ValidateGuid ((string) pos_values [0]))
315                                                                 return null;
316                                                 }
317                                                 
318                                         } else if (MarshalAsAttr)
319                                                 this.UnmanagedType =
320                                                 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
321                                 }
322                         }
323
324                         //
325                         // Now process named arguments
326                         //
327
328                         ArrayList field_infos = null;
329                         ArrayList prop_infos  = null;
330                         ArrayList field_values = null;
331                         ArrayList prop_values = null;
332
333                         if (named_args.Count > 0) {
334                                 field_infos = new ArrayList ();
335                                 prop_infos  = new ArrayList ();
336                                 field_values = new ArrayList ();
337                                 prop_values = new ArrayList ();
338                         }
339
340                         Hashtable seen_names = new Hashtable();
341                         
342                         for (i = 0; i < named_args.Count; i++) {
343                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
344                                 string member_name = (string) de.Key;
345                                 Argument a  = (Argument) de.Value;
346                                 Expression e;
347
348                                 if (seen_names.Contains(member_name)) {
349                                         Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
350                                         return null;
351                                 }                               
352                                 seen_names.Add(member_name, 1);
353                                 
354                                 if (!a.Resolve (ec, Location))
355                                         return null;
356
357                                 Expression member = Expression.MemberLookup (
358                                         ec, Type, member_name,
359                                         MemberTypes.Field | MemberTypes.Property,
360                                         BindingFlags.Public | BindingFlags.Instance,
361                                         Location);
362
363                                 if (member == null) {
364                                         member = Expression.MemberLookup (ec, Type, member_name,
365                                                 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
366                                                 Location);
367
368                                         if (member != null) {
369                                                 Report.Error_T (122, Location, GetFullMemberName (member_name));
370                                                 return null;
371                                         }
372                                 }
373
374                                 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
375                                         Error_InvalidNamedArgument (member_name);
376                                         return null;
377                                 }
378
379                                 e = a.Expr;
380                                 if (member is PropertyExpr) {
381                                         PropertyExpr pe = (PropertyExpr) member;
382                                         PropertyInfo pi = pe.PropertyInfo;
383
384                                         if (!pi.CanWrite) {
385                                                 Error_InvalidNamedArgument (member_name);
386                                                 return null;
387                                         }
388
389                                         Constant c = e as Constant;
390                                         if (c != null) {
391                                                 if (c.Type != pi.PropertyType) {
392                                                         c = Const.ChangeType (Location, c, pi.PropertyType);
393                                                         if (c == null)
394                                                                 return null;
395                                                 }
396                                                 
397                                                 object o = c.GetValue ();
398                                                 prop_values.Add (o);
399                                                 
400                                                 if (usage_attribute != null) {
401                                                         if (member_name == "AllowMultiple")
402                                                                 usage_attribute.AllowMultiple = (bool) o;
403                                                         if (member_name == "Inherited")
404                                                                 usage_attribute.Inherited = (bool) o;
405                                                 }
406                                                 
407                                         } else if (e is TypeOf) {
408                                                 prop_values.Add (((TypeOf) e).TypeArg);
409                                         } else if (e is ArrayCreation) {
410                                                 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
411                                         } else {
412                                                 Error_AttributeArgumentNotValid (Location);
413                                                 return null;
414                                         }
415                                         
416                                         prop_infos.Add (pi);
417                                         
418                                 } else if (member is FieldExpr) {
419                                         FieldExpr fe = (FieldExpr) member;
420                                         FieldInfo fi = fe.FieldInfo;
421
422                                         if (fi.IsInitOnly) {
423                                                 Error_InvalidNamedArgument (member_name);
424                                                 return null;
425                                         }
426
427                                         //
428                                         // Handle charset here, and set the TypeAttributes
429
430                                         Constant c = e as Constant;
431                                         if (c != null) {
432                                                 if (c.Type != fi.FieldType) {
433                                                         c = Const.ChangeType (Location, c, fi.FieldType);
434                                                         if (c == null)
435                                                                 return null;
436                                                 }                                       
437                                                 
438                                                 object value = c.GetValue ();
439                                                 field_values.Add (value);
440                                         } else if (e is TypeOf) {
441                                                 field_values.Add (((TypeOf) e).TypeArg);
442                                         } else {
443                                                 Error_AttributeArgumentNotValid (Location);
444                                                 return null;
445                                         }
446                                         
447                                         field_infos.Add (fi);
448                                 }
449                         }
450
451                         Expression mg = Expression.MemberLookup (
452                                 ec, Type, ".ctor", MemberTypes.Constructor,
453                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
454                                 Location);
455
456                         if (mg == null) {
457                                 Error_AttributeConstructorMismatch ();
458                                 return null;
459                         }
460
461                         MethodBase constructor = Invocation.OverloadResolve (
462                                 ec, (MethodGroupExpr) mg, pos_args, Location);
463
464                         if (constructor == null) {
465                                 Error_AttributeConstructorMismatch ();
466                                 return null;
467                         }
468
469                         //
470                         // Now we perform some checks on the positional args as they
471                         // cannot be null for a constructor which expects a parameter
472                         // of type object
473                         //
474
475                         ParameterData pd = Invocation.GetParameterData (constructor);
476
477                         int group_in_params_array = Int32.MaxValue;
478                         int pc = pd.Count;
479                         if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
480                                 group_in_params_array = pc-1;
481
482                         for (int j = 0; j < pos_arg_count; ++j) {
483                                 Argument a = (Argument) pos_args [j];
484                                 
485                                 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
486                                         Error_AttributeArgumentNotValid (Location);
487                                         return null;
488                                 }
489
490                                 if (j < group_in_params_array)
491                                         continue;
492                                 
493                                 if (j == group_in_params_array){
494                                         object v = pos_values [j];
495                                         int count = pos_arg_count - j;
496
497                                         object [] array = new object [count];
498                                         pos_values [j] = array;
499                                         array [0] = v;
500                                 } else {
501                                         object [] array = (object []) pos_values [group_in_params_array];
502
503                                         array [j - group_in_params_array] = pos_values [j];
504                                 }
505                         }
506
507                         //
508                         // Adjust the size of the pos_values if it had params
509                         //
510                         if (group_in_params_array != Int32.MaxValue){
511                                 int argc = group_in_params_array+1;
512                                 object [] new_pos_values = new object [argc];
513
514                                 for (int p = 0; p < argc; p++)
515                                         new_pos_values [p] = pos_values [p];
516                                 pos_values = new_pos_values;
517                         }
518
519                         try {
520                                 if (named_args.Count > 0) {
521                                         prop_info_arr = new PropertyInfo [prop_infos.Count];
522                                         field_info_arr = new FieldInfo [field_infos.Count];
523                                         field_values_arr = new object [field_values.Count];
524                                         prop_values_arr = new object [prop_values.Count];
525
526                                         field_infos.CopyTo  (field_info_arr, 0);
527                                         field_values.CopyTo (field_values_arr, 0);
528
529                                         prop_values.CopyTo  (prop_values_arr, 0);
530                                         prop_infos.CopyTo   (prop_info_arr, 0);
531
532                                         cb = new CustomAttributeBuilder (
533                                                 (ConstructorInfo) constructor, pos_values,
534                                                 prop_info_arr, prop_values_arr,
535                                                 field_info_arr, field_values_arr);
536                                 }
537                                 else
538                                         cb = new CustomAttributeBuilder (
539                                                 (ConstructorInfo) constructor, pos_values);
540                         } catch (NullReferenceException) {
541                                 // 
542                                 // Don't know what to do here
543                                 //
544                                 Report.Warning (
545                                         -101, Location, "NullReferenceException while trying to create attribute." +
546                                         "Something's wrong!");
547                         } catch (Exception e) {
548                                 //
549                                 // Sample:
550                                 // using System.ComponentModel;
551                                 // [DefaultValue (CollectionChangeAction.Add)]
552                                 // class X { static void Main () {} }
553                                 //
554                                 Report.Warning (
555                                         -23, Location, "The compiler can not encode this attribute in .NET due to a bug in the .NET runtime. Try the Mono runtime. The exception was: " + e.Message);
556                         }
557                         
558                         return cb;
559                 }
560
561                 /// <summary>
562                 ///   Get a string containing a list of valid targets for the attribute 'attr'
563                 /// </summary>
564                 static string GetValidTargets (Attribute attr)
565                 {
566                         StringBuilder sb = new StringBuilder ();
567                         AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
568
569                         if ((targets & AttributeTargets.Assembly) != 0)
570                                 sb.Append ("'assembly' ");
571
572                         if ((targets & AttributeTargets.Class) != 0)
573                                 sb.Append ("'class' ");
574
575                         if ((targets & AttributeTargets.Constructor) != 0)
576                                 sb.Append ("'constructor' ");
577
578                         if ((targets & AttributeTargets.Delegate) != 0)
579                                 sb.Append ("'delegate' ");
580
581                         if ((targets & AttributeTargets.Enum) != 0)
582                                 sb.Append ("'enum' ");
583
584                         if ((targets & AttributeTargets.Event) != 0)
585                                 sb.Append ("'event' ");
586
587                         if ((targets & AttributeTargets.Field) != 0)
588                                 sb.Append ("'field' ");
589
590                         if ((targets & AttributeTargets.Interface) != 0)
591                                 sb.Append ("'interface' ");
592
593                         if ((targets & AttributeTargets.Method) != 0)
594                                 sb.Append ("'method' ");
595
596                         if ((targets & AttributeTargets.Module) != 0)
597                                 sb.Append ("'module' ");
598
599                         if ((targets & AttributeTargets.Parameter) != 0)
600                                 sb.Append ("'parameter' ");
601
602                         if ((targets & AttributeTargets.Property) != 0)
603                                 sb.Append ("'property' ");
604
605                         if ((targets & AttributeTargets.ReturnValue) != 0)
606                                 sb.Append ("'return' ");
607
608                         if ((targets & AttributeTargets.Struct) != 0)
609                                 sb.Append ("'struct' ");
610
611                         return sb.ToString ();
612
613                 }
614
615                 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
616                 {
617                         Report.Error (
618                                 592, loc, "Attribute '" + a.Name +
619                                 "' is not valid on this declaration type. " +
620                                 "It is valid on " + GetValidTargets (a) + "declarations only.");
621                 }
622
623
624                 /// <summary>
625                 /// Returns AttributeUsage attribute for this type
626                 /// </summary>
627                 public AttributeUsageAttribute GetAttributeUsage ()
628                 {
629                         AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
630                         if (ua != null)
631                                 return ua;
632
633                         Class attr_class = TypeManager.LookupClass (Type);
634
635                         if (attr_class == null) {
636                                 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
637                                 ua = (AttributeUsageAttribute)usage_attr [0];
638                                 usage_attr_cache.Add (Type, ua);
639                                 return ua;
640                         }
641                 
642                         return attr_class.AttributeUsage;
643                 }
644
645
646                 //
647                 // This pulls the condition name out of a Conditional attribute
648                 //
649                 public string Conditional_GetConditionName ()
650                 {
651                         //
652                         // So we have a Conditional, pull the data out.
653                         //
654                         if (Arguments == null || Arguments [0] == null){
655                                 Error_AttributeConstructorMismatch ();
656                                 return null;
657                         }
658
659                         ArrayList pos_args = (ArrayList) Arguments [0];
660                         if (pos_args.Count != 1){
661                                 Error_AttributeConstructorMismatch ();
662                                 return null;
663                         }
664
665                         Argument arg = (Argument) pos_args [0]; 
666                         if (!(arg.Expr is StringConstant)){
667                                 Error_AttributeConstructorMismatch ();
668                                 return null;
669                         }
670
671                         return ((StringConstant) arg.Expr).Value;
672                 }
673
674                 //
675                 // This pulls the obsolete message and error flag out of an Obsolete attribute
676                 //
677                 public string Obsolete_GetObsoleteMessage (out bool is_error)
678                 {
679                         is_error = false;
680                         //
681                         // So we have an Obsolete, pull the data out.
682                         //
683                         if (Arguments == null || Arguments [0] == null)
684                                 return "";
685
686                         ArrayList pos_args = (ArrayList) Arguments [0];
687                         if (pos_args.Count == 0)
688                                 return "";
689                         else if (pos_args.Count > 2){
690                                 Error_AttributeConstructorMismatch ();
691                                 return null;
692                         }
693
694                         Argument arg = (Argument) pos_args [0]; 
695                         if (!(arg.Expr is StringConstant)){
696                                 Error_AttributeConstructorMismatch ();
697                                 return null;
698                         }
699
700                         if (pos_args.Count == 2){
701                                 Argument arg2 = (Argument) pos_args [1];
702                                 if (!(arg2.Expr is BoolConstant)){
703                                         Error_AttributeConstructorMismatch ();
704                                         return null;
705                                 }
706                                 is_error = ((BoolConstant) arg2.Expr).Value;
707                         }
708
709                         return ((StringConstant) arg.Expr).Value;
710                 }
711
712                 public string IndexerName_GetIndexerName (EmitContext ec)
713                 {
714                         if (Arguments == null || Arguments [0] == null){
715                                 Error_AttributeConstructorMismatch ();
716                                 return null;
717                         }
718                         ArrayList pos_args = (ArrayList) Arguments [0];
719                         if (pos_args.Count != 1) {
720                                 Error_AttributeConstructorMismatch ();
721                                 return null;
722                         }
723                         
724                         Argument arg = (Argument) pos_args [0];
725                         if (!arg.Resolve (ec, Location))
726                                 return null;
727                         
728                         StringConstant sc = arg.Expr as StringConstant;
729                         if (sc == null){
730                                 Error_AttributeConstructorMismatch ();
731                                 return null;
732                         }
733                         
734                         return sc.Value;
735                 }
736
737                 /// <summary>
738                 /// Creates the instance of ObsoleteAttribute from this attribute instance
739                 /// </summary>
740                 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
741                 {
742                         if (pos_values == null) {
743                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
744
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
750                         // Some error occurred
751                         if (pos_values == null)
752                                 return null;
753
754                         if (pos_values.Length == 0)
755                                 return new ObsoleteAttribute ();
756
757                         if (pos_values.Length == 1)
758                                 return new ObsoleteAttribute ((string)pos_values [0]);
759
760                         return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
761                 }
762
763                 /// <summary>
764                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
765                 /// before ApplyAttribute. We need to resolve the arguments.
766                 /// This situation occurs when class deps is differs from Emit order.  
767                 /// </summary>
768                 public bool GetClsCompliantAttributeValue (DeclSpace ds)
769                 {
770                         if (pos_values == null) {
771                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
772
773                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
774                                 // But because a lot of attribute class code must be rewritten will be better to wait...
775                                 Resolve (ec);
776                         }
777
778                         // Some error occurred
779                         if (pos_values [0] == null)
780                                 return false;
781
782                         return (bool)pos_values [0];
783                 }
784
785                 public object GetPositionalValue (int i)
786                 {
787                         return (pos_values == null) ? null : pos_values[i];
788                 }
789
790                 object GetFieldValue (string name)
791                 {
792                         int i;
793                         if (field_info_arr == null)
794                                 return null;
795                         i = 0;
796                         foreach (FieldInfo fi in field_info_arr) {
797                                 if (fi.Name == name)
798                                         return field_values_arr [i];
799                                 i++;
800                         }
801                         return null;
802                 }
803
804                 public UnmanagedMarshal GetMarshal ()
805                 {
806                         object o = GetFieldValue ("ArraySubType");
807                         UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
808                         
809                         switch (UnmanagedType) {
810                         case UnmanagedType.CustomMarshaler:
811                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
812                                                                        BindingFlags.Static | BindingFlags.Public);
813                                 if (define_custom == null)
814                                         return null;
815                                 
816                                 object [] args = new object [4];
817                                 args [0] = GetFieldValue ("MarshalTypeRef");
818                                 args [1] = GetFieldValue ("MarshalCookie");
819                                 args [2] = GetFieldValue ("MarshalType");
820                                 args [3] = Guid.Empty;
821                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
822                                 
823                         case UnmanagedType.LPArray:                             
824                                 return UnmanagedMarshal.DefineLPArray (array_sub_type);
825                         
826                         case UnmanagedType.SafeArray:
827                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
828                         
829                         case UnmanagedType.ByValArray:
830                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
831                         
832                         case UnmanagedType.ByValTStr:
833                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
834                         
835                         default:
836                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
837                         }
838                 }
839
840                 public bool IsInternalCall
841                 {
842                         get { return ImplOptions == MethodImplOptions.InternalCall; }
843                 }
844
845                 /// <summary>
846                 /// Emit attribute for Attributable symbol
847                 /// </summary>
848                 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
849                 {
850                         CustomAttributeBuilder cb = Resolve (ec);
851                         if (cb == null)
852                                 return;
853
854                         AttributeUsageAttribute usage_attr = GetAttributeUsage ();
855                         if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
856                                 Error_AttributeNotValidForElement (this, Location);
857                                 return;
858                         }
859
860                         ias.ApplyAttributeBuilder (this, cb);
861
862                         if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
863                                 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
864                         }
865
866                         emitted_attr [Type] = Target;
867
868                         // Here we are testing attribute arguments for array usage (error 3016)
869                         if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
870                                 if (Arguments == null)
871                                         return;
872
873                                 ArrayList pos_args = (ArrayList) Arguments [0];
874                                 if (pos_args != null) {
875                                         foreach (Argument arg in pos_args) { 
876                                                 // Type is undefined (was error 246)
877                                                 if (arg.Type == null)
878                                                         return;
879
880                                                 if (arg.Type.IsArray) {
881                                                         Report.Error_T (3016, Location);
882                                                         return;
883                                                 }
884                                         }
885                                 }
886                         
887                                 if (Arguments.Count < 2)
888                                         return;
889                         
890                                 ArrayList named_args = (ArrayList) Arguments [1];
891                                 foreach (DictionaryEntry de in named_args) {
892                                         Argument arg  = (Argument) de.Value;
893
894                                         // Type is undefined (was error 246)
895                                         if (arg.Type == null)
896                                                 return;
897
898                                         if (arg.Type.IsArray) {
899                                                 Report.Error_T (3016, Location);
900                                                 return;
901                                         }
902                                 }
903                         }
904                 }
905
906                 public object GetValue (EmitContext ec, Constant c, Type target)
907                 {
908                         if (Convert.ImplicitConversionExists (ec, c, target))
909                                 return c.GetValue ();
910
911                         Convert.Error_CannotImplicitConversion (Location, c.Type, target);
912                         return null;
913                 }
914                 
915                 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
916                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
917                 {
918                         //
919                         // We extract from the attribute the information we need 
920                         //
921
922                         if (Arguments == null) {
923                                 Console.WriteLine ("Internal error : this is not supposed to happen !");
924                                 return null;
925                         }
926
927                         ResolveType (ec, true);
928                         if (Type == null)
929                                 return null;
930                         
931                         ArrayList named_args = new ArrayList ();
932                         
933                         ArrayList pos_args = (ArrayList) Arguments [0];
934                         if (Arguments.Count > 1)
935                                 named_args = (ArrayList) Arguments [1];
936                         
937
938                         string dll_name = null;
939                         
940                         Argument tmp = (Argument) pos_args [0];
941
942                         if (!tmp.Resolve (ec, Location))
943                                 return null;
944                         
945                         if (tmp.Expr is Constant)
946                                 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
947                         else { 
948                                 Error_AttributeArgumentNotValid (Location);
949                                 return null;
950                         }
951
952                         // Now we process the named arguments
953                         CallingConvention cc = CallingConvention.Winapi;
954                         CharSet charset = CharSet.Ansi;
955                         bool preserve_sig = true;
956 #if FIXME
957                         bool exact_spelling = false;
958 #endif
959                         bool set_last_err = false;
960                         string entry_point = null;
961
962                         for (int i = 0; i < named_args.Count; i++) {
963
964                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
965
966                                 string member_name = (string) de.Key;
967                                 Argument a  = (Argument) de.Value;
968
969                                 if (!a.Resolve (ec, Location))
970                                         return null;
971
972                                 Expression member = Expression.MemberLookup (
973                                         ec, Type, member_name, 
974                                         MemberTypes.Field | MemberTypes.Property,
975                                         BindingFlags.Public | BindingFlags.Instance,
976                                         Location);
977
978                                 if (member == null || !(member is FieldExpr)) {
979                                         Error_InvalidNamedArgument (member_name);
980                                         return null;
981                                 }
982
983                                 if (member is FieldExpr) {
984                                         FieldExpr fe = (FieldExpr) member;
985                                         FieldInfo fi = fe.FieldInfo;
986
987                                         if (fi.IsInitOnly) {
988                                                 Error_InvalidNamedArgument (member_name);
989                                                 return null;
990                                         }
991
992                                         if (a.Expr is Constant) {
993                                                 Constant c = (Constant) a.Expr;
994
995                                                 try {
996                                                         if (member_name == "CallingConvention"){
997                                                                 object val = GetValue (ec, c, typeof (CallingConvention));
998                                                                 if (val == null)
999                                                                         return null;
1000                                                                 cc = (CallingConvention) val;
1001                                                         } else if (member_name == "CharSet"){
1002                                                                 charset = (CharSet) c.GetValue ();
1003                                                         } else if (member_name == "EntryPoint")
1004                                                                 entry_point = (string) c.GetValue ();
1005                                                         else if (member_name == "SetLastError")
1006                                                                 set_last_err = (bool) c.GetValue ();
1007 #if FIXME
1008                                                         else if (member_name == "ExactSpelling")
1009                                                                 exact_spelling = (bool) c.GetValue ();
1010 #endif
1011                                                         else if (member_name == "PreserveSig")
1012                                                                 preserve_sig = (bool) c.GetValue ();
1013                                                 } catch (InvalidCastException){
1014                                                         Error_InvalidNamedArgument (member_name);
1015                                                         Error_AttributeArgumentNotValid (Location);
1016                                                 }
1017                                         } else { 
1018                                                 Error_AttributeArgumentNotValid (Location);
1019                                                 return null;
1020                                         }
1021                                         
1022                                 }
1023                         }
1024
1025                         if (entry_point == null)
1026                                 entry_point = name;
1027                         if (set_last_err)
1028                                 charset = (CharSet)((int)charset | 0x40);
1029                         
1030                         MethodBuilder mb = builder.DefinePInvokeMethod (
1031                                 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1032                                 CallingConventions.Standard,
1033                                 ret_type,
1034                                 param_types,
1035                                 cc,
1036                                 charset);
1037
1038                         if (preserve_sig)
1039                                 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1040                         
1041                         return mb;
1042                 }
1043
1044                 private Expression GetValue () 
1045                 {
1046                         if ((Arguments == null) || (Arguments.Count < 1))
1047                                 return null;
1048                         ArrayList al = (ArrayList) Arguments [0];
1049                         if ((al == null) || (al.Count < 1))
1050                                 return null;
1051                         Argument arg = (Argument) al [0];
1052                         if ((arg == null) || (arg.Expr == null))
1053                                 return null;
1054                         return arg.Expr;
1055                 }
1056
1057                 public string GetString () 
1058                 {
1059                         Expression e = GetValue ();
1060                         if (e is StringLiteral)
1061                                 return (e as StringLiteral).Value;
1062                         return null;
1063                 }
1064
1065                 public bool GetBoolean () 
1066                 {
1067                         Expression e = GetValue ();
1068                         if (e is BoolLiteral)
1069                                 return (e as BoolLiteral).Value;
1070                         return false;
1071                 }
1072         }
1073         
1074
1075         /// <summary>
1076         /// For global attributes (assembly, module) we need special handling.
1077         /// Attributes can be located in the several files
1078         /// </summary>
1079         public class GlobalAttribute: Attribute
1080         {
1081                 public readonly NamespaceEntry ns;
1082
1083                 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1084                         base (target, name, args, loc)
1085                 {
1086                         ns = container.NamespaceEntry;
1087                 }
1088
1089                 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1090                 {
1091                         NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1092                         if (old == null || old.NS == null || old.NS == Namespace.Root) 
1093                                 ec.DeclSpace.NamespaceEntry = ns;
1094                         return base.CheckAttributeType (ec, complain);
1095                 }
1096         }
1097
1098         public class Attributes {
1099                 public ArrayList Attrs;
1100
1101                 public Attributes (Attribute a)
1102                 {
1103                         Attrs = new ArrayList ();
1104                         Attrs.Add (a);
1105                 }
1106
1107                 public Attributes (ArrayList attrs)
1108                 {
1109                         Attrs = attrs;
1110                 }
1111
1112                 public void AddAttributes (ArrayList attrs)
1113                 {
1114                         Attrs.AddRange (attrs);
1115                 }
1116
1117                 /// <summary>
1118                 /// Checks whether attribute target is valid for the current element
1119                 /// </summary>
1120                 public void CheckTargets (string[] possible_targets)
1121                 {
1122                         foreach (Attribute a in Attrs) {
1123                                 if (a.Target == null) {
1124                                         a.Target = possible_targets [0];
1125                                         continue;
1126                                 }
1127
1128                                 if (((IList) possible_targets).Contains (a.Target))
1129                                         continue;
1130
1131                                 StringBuilder sb = new StringBuilder ();
1132                                 foreach (string s in possible_targets) {
1133                                         sb.Append (s);
1134                                         sb.Append (", ");
1135                                 }
1136                                 sb.Remove (sb.Length - 2, 2);
1137                                 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1138                         }
1139                 }
1140
1141                 private Attribute Search (Type t, EmitContext ec, bool complain)
1142                 {
1143                         foreach (Attribute a in Attrs) {
1144                                 if (a.ResolveType (ec, false) == t)
1145                                         return a;
1146                         }
1147                         return null;
1148                 }
1149
1150                 public Attribute Search (Type t, EmitContext ec)
1151                 {
1152                         return Search (t, ec, true);
1153                 }
1154
1155                 public void Emit (EmitContext ec, Attributable ias)
1156                 {
1157                         ListDictionary ld = new ListDictionary ();
1158
1159                         foreach (Attribute a in Attrs)
1160                                 a.Emit (ec, ias, ld);
1161                 }
1162
1163                 public bool Contains (Type t, EmitContext ec)
1164                 {
1165                         return Search (t, ec) != null;
1166                 }
1167
1168                 public Attribute GetClsCompliantAttribute (EmitContext ec)
1169                 {
1170                         return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1171                 }
1172
1173                 /// <summary>
1174                 /// Pulls the IndexerName attribute from an Indexer if it exists.
1175                 /// </summary>
1176                 public string ScanForIndexerName (EmitContext ec)
1177                 {
1178                         Attribute a = Search (TypeManager.indexer_name_type, ec);
1179                         if (a == null)
1180                                 return null;
1181
1182                         // Remove the attribute from the list
1183                         //TODO: It is very close to hack and it can crash here
1184                         Attrs.Remove (a);
1185
1186                         return a.IndexerName_GetIndexerName (ec);
1187                 }
1188
1189         }
1190
1191         /// <summary>
1192         /// Helper class for attribute verification routine.
1193         /// </summary>
1194         sealed class AttributeTester
1195         {
1196                 static PtrHashtable analyzed_types = new PtrHashtable ();
1197                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1198
1199                 private AttributeTester ()
1200                 {
1201                 }
1202
1203                 /// <summary>
1204                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1205                 /// It tests differing only in ref or out, or in array rank.
1206                 /// </summary>
1207                 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1208                 {
1209                         if (types_a == null || types_b == null)
1210                                 return true;
1211
1212                         if (types_a.Length != types_b.Length)
1213                                 return true;
1214
1215                         for (int i = 0; i < types_b.Length; ++i) {
1216                                 Type aType = types_a [i];
1217                                 Type bType = types_b [i];
1218
1219                                 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1220                                         return false;
1221                                 }
1222
1223                                 Type aBaseType = aType;
1224                                 bool is_either_ref_or_out = false;
1225
1226                                 if (aType.IsByRef || aType.IsPointer) {
1227                                         aBaseType = aType.GetElementType ();
1228                                         is_either_ref_or_out = true;
1229                                 }
1230
1231                                 Type bBaseType = bType;
1232                                 if (bType.IsByRef || bType.IsPointer) 
1233                                 {
1234                                         bBaseType = bType.GetElementType ();
1235                                         is_either_ref_or_out = !is_either_ref_or_out;
1236                                 }
1237
1238                                 if (aBaseType != bBaseType)
1239                                         continue;
1240
1241                                 if (is_either_ref_or_out)
1242                                         return false;
1243                         }
1244                         return true;
1245                 }
1246
1247                 /// <summary>
1248                 /// Goes through all parameters and test if they are CLS-Compliant.
1249                 /// </summary>
1250                 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1251                 {
1252                         if (fixedParameters == null)
1253                                 return true;
1254
1255                         foreach (Parameter arg in fixedParameters) {
1256                                 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1257                                         Report.Error_T (3001, loc, arg.GetSignatureForError ());
1258                                         return false;
1259                                 }
1260                         }
1261                         return true;
1262                 }
1263
1264
1265                 /// <summary>
1266                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1267                 /// </summary>
1268                 public static bool IsClsCompliant (Type type) 
1269                 {
1270                         if (type == null)
1271                                 return true;
1272
1273                         object type_compliance = analyzed_types[type];
1274                         if (type_compliance != null)
1275                                 return type_compliance == TRUE;
1276
1277                         if (type.IsPointer) {
1278                                 analyzed_types.Add (type, null);
1279                                 return false;
1280                         }
1281
1282                         bool result;
1283                         if (type.IsArray || type.IsByRef)       {
1284                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1285                         } else {
1286                                 result = AnalyzeTypeCompliance (type);
1287                         }
1288                         analyzed_types.Add (type, result ? TRUE : FALSE);
1289                         return result;
1290                 }                
1291
1292                 static object TRUE = new object ();
1293                 static object FALSE = new object ();
1294
1295                 /// <summary>
1296                 /// Non-hierarchical CLS Compliance analyzer
1297                 /// </summary>
1298                 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1299                 {
1300                         DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1301
1302                         // Type is external, we can get attribute directly
1303                         if (temp_ds == null) {
1304                                 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1305                                 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1306                         }
1307
1308                         string tmp_name;
1309                         // Interface doesn't store full name
1310                         if (temp_ds is Interface)
1311                                 tmp_name = mi.Name;
1312                         else
1313                                 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1314
1315                         MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1316                         return mc.IsClsCompliaceRequired (ds);
1317                 }
1318
1319                 public static void VerifyModulesClsCompliance ()
1320                 {
1321                         Module[] modules = TypeManager.Modules;
1322                         if (modules == null)
1323                                 return;
1324
1325                         // The first module is generated assembly
1326                         for (int i = 1; i < modules.Length; ++i) {
1327                                 Module module = modules [i];
1328                                 if (!IsClsCompliant (module)) {
1329                                         Report.Error_T (3013, module.Name);
1330                                         return;
1331                                 }
1332                         }
1333                 }
1334
1335                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1336                 {
1337                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1338                         if (CompliantAttribute.Length == 0)
1339                                 return false;
1340
1341                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1342                 }
1343
1344                 static bool AnalyzeTypeCompliance (Type type)
1345                 {
1346                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1347                         if (ds != null) {
1348                                 return ds.IsClsCompliaceRequired (ds.Parent);
1349                         }
1350
1351                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1352                         if (CompliantAttribute.Length == 0) 
1353                                 return IsClsCompliant (type.Assembly);
1354
1355                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1356                 }
1357
1358                 /// <summary>
1359                 /// Returns instance of ObsoleteAttribute when member is obsolete
1360                 /// </summary>
1361                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1362                 {
1363                         object type_obsolete = analyzed_member_obsolete [mi];
1364                         if (type_obsolete == FALSE)
1365                                 return null;
1366
1367                         if (type_obsolete != null)
1368                                 return (ObsoleteAttribute)type_obsolete;
1369
1370                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1371                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1372                         return oa;
1373                 }
1374
1375                 /// <summary>
1376                 /// Common method for Obsolete error/warning reporting.
1377                 /// </summary>
1378                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1379                 {
1380                         if (oa.IsError) {
1381                                 Report.Error_T (619, loc, member, oa.Message);
1382                                 return;
1383                         }
1384
1385                         if (oa.Message == null) {
1386                                 Report.Warning_T (612, loc, member);
1387                                 return;
1388                         }
1389                         Report.Warning_T (618, loc, member, oa.Message);
1390                 }
1391         }
1392 }