2004-05-27 Umadevi S <sumadevi@novell.com>
[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                 public string IndexerName_GetIndexerName (EmitContext ec)
675                 {
676                         if (Arguments == null || Arguments [0] == null){
677                                 Error_AttributeConstructorMismatch ();
678                                 return null;
679                         }
680                         ArrayList pos_args = (ArrayList) Arguments [0];
681                         if (pos_args.Count != 1) {
682                                 Error_AttributeConstructorMismatch ();
683                                 return null;
684                         }
685                         
686                         Argument arg = (Argument) pos_args [0];
687                         if (!arg.Resolve (ec, Location))
688                                 return null;
689                         
690                         StringConstant sc = arg.Expr as StringConstant;
691                         if (sc == null){
692                                 Error_AttributeConstructorMismatch ();
693                                 return null;
694                         }
695                         
696                         return sc.Value;
697                 }
698
699                 /// <summary>
700                 /// Creates the instance of ObsoleteAttribute from this attribute instance
701                 /// </summary>
702                 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
703                 {
704                         if (pos_values == null) {
705                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
706
707                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
708                                 // But because a lot of attribute class code must be rewritten will be better to wait...
709                                 Resolve (ec);
710                         }
711
712                         // Some error occurred
713                         if (pos_values == null)
714                                 return null;
715
716                         if (pos_values.Length == 0)
717                                 return new ObsoleteAttribute ();
718
719                         if (pos_values.Length == 1)
720                                 return new ObsoleteAttribute ((string)pos_values [0]);
721
722                         return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
723                 }
724
725                 /// <summary>
726                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
727                 /// before ApplyAttribute. We need to resolve the arguments.
728                 /// This situation occurs when class deps is differs from Emit order.  
729                 /// </summary>
730                 public bool GetClsCompliantAttributeValue (DeclSpace ds)
731                 {
732                         if (pos_values == null) {
733                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
734
735                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
736                                 // But because a lot of attribute class code must be rewritten will be better to wait...
737                                 Resolve (ec);
738                         }
739
740                         // Some error occurred
741                         if (pos_values [0] == null)
742                                 return false;
743
744                         return (bool)pos_values [0];
745                 }
746
747                 public object GetPositionalValue (int i)
748                 {
749                         return (pos_values == null) ? null : pos_values[i];
750                 }
751
752                 object GetFieldValue (string name)
753                 {
754                         int i;
755                         if (field_info_arr == null)
756                                 return null;
757                         i = 0;
758                         foreach (FieldInfo fi in field_info_arr) {
759                                 if (fi.Name == name)
760                                         return field_values_arr [i];
761                                 i++;
762                         }
763                         return null;
764                 }
765
766                 public UnmanagedMarshal GetMarshal ()
767                 {
768                         object o = GetFieldValue ("ArraySubType");
769                         UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
770                         
771                         switch (UnmanagedType) {
772                         case UnmanagedType.CustomMarshaler:
773                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
774                                                                        BindingFlags.Static | BindingFlags.Public);
775                                 if (define_custom == null)
776                                         return null;
777                                 
778                                 object [] args = new object [4];
779                                 args [0] = GetFieldValue ("MarshalTypeRef");
780                                 args [1] = GetFieldValue ("MarshalCookie");
781                                 args [2] = GetFieldValue ("MarshalType");
782                                 args [3] = Guid.Empty;
783                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
784                                 
785                         case UnmanagedType.LPArray:                             
786                                 return UnmanagedMarshal.DefineLPArray (array_sub_type);
787                         
788                         case UnmanagedType.SafeArray:
789                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
790                         
791                         case UnmanagedType.ByValArray:
792                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
793                         
794                         case UnmanagedType.ByValTStr:
795                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
796                         
797                         default:
798                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
799                         }
800                 }
801
802                 public bool IsInternalCall
803                 {
804                         get { return ImplOptions == MethodImplOptions.InternalCall; }
805                 }
806
807                 /// <summary>
808                 /// Emit attribute for Attributable symbol
809                 /// </summary>
810                 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
811                 {
812                         CustomAttributeBuilder cb = Resolve (ec);
813                         if (cb == null)
814                                 return;
815
816                         AttributeUsageAttribute usage_attr = GetAttributeUsage ();
817                         if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
818                                 Error_AttributeNotValidForElement (this, Location);
819                                 return;
820                         }
821
822                         ias.ApplyAttributeBuilder (this, cb);
823
824                         if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
825                                 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
826                         }
827
828                         emitted_attr [Type] = Target;
829
830                         // Here we are testing attribute arguments for array usage (error 3016)
831                         if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
832                                 if (Arguments == null)
833                                         return;
834
835                                 ArrayList pos_args = (ArrayList) Arguments [0];
836                                 if (pos_args != null) {
837                                         foreach (Argument arg in pos_args) { 
838                                                 // Type is undefined (was error 246)
839                                                 if (arg.Type == null)
840                                                         return;
841
842                                                 if (arg.Type.IsArray) {
843                                                         Report.Error_T (3016, Location);
844                                                         return;
845                                                 }
846                                         }
847                                 }
848                         
849                                 if (Arguments.Count < 2)
850                                         return;
851                         
852                                 ArrayList named_args = (ArrayList) Arguments [1];
853                                 foreach (DictionaryEntry de in named_args) {
854                                         Argument arg  = (Argument) de.Value;
855
856                                         // Type is undefined (was error 246)
857                                         if (arg.Type == null)
858                                                 return;
859
860                                         if (arg.Type.IsArray) {
861                                                 Report.Error_T (3016, Location);
862                                                 return;
863                                         }
864                                 }
865                         }
866                 }
867
868                 public object GetValue (EmitContext ec, Constant c, Type target)
869                 {
870                         if (Convert.ImplicitConversionExists (ec, c, target))
871                                 return c.GetValue ();
872
873                         Convert.Error_CannotImplicitConversion (Location, c.Type, target);
874                         return null;
875                 }
876                 
877                 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
878                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
879                 {
880                         //
881                         // We extract from the attribute the information we need 
882                         //
883
884                         if (Arguments == null) {
885                                 Console.WriteLine ("Internal error : this is not supposed to happen !");
886                                 return null;
887                         }
888
889                         ResolveType (ec, true);
890                         if (Type == null)
891                                 return null;
892                         
893                         ArrayList named_args = new ArrayList ();
894                         
895                         ArrayList pos_args = (ArrayList) Arguments [0];
896                         if (Arguments.Count > 1)
897                                 named_args = (ArrayList) Arguments [1];
898                         
899
900                         string dll_name = null;
901                         
902                         Argument tmp = (Argument) pos_args [0];
903
904                         if (!tmp.Resolve (ec, Location))
905                                 return null;
906                         
907                         if (tmp.Expr is Constant)
908                                 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
909                         else { 
910                                 Error_AttributeArgumentNotValid (Location);
911                                 return null;
912                         }
913
914                         // Now we process the named arguments
915                         CallingConvention cc = CallingConvention.Winapi;
916                         CharSet charset = CharSet.Ansi;
917                         bool preserve_sig = true;
918 #if FIXME
919                         bool exact_spelling = false;
920 #endif
921                         bool set_last_err = false;
922                         string entry_point = null;
923
924                         for (int i = 0; i < named_args.Count; i++) {
925
926                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
927
928                                 string member_name = (string) de.Key;
929                                 Argument a  = (Argument) de.Value;
930
931                                 if (!a.Resolve (ec, Location))
932                                         return null;
933
934                                 Expression member = Expression.MemberLookup (
935                                         ec, Type, member_name, 
936                                         MemberTypes.Field | MemberTypes.Property,
937                                         BindingFlags.Public | BindingFlags.Instance,
938                                         Location);
939
940                                 if (member == null || !(member is FieldExpr)) {
941                                         Error_InvalidNamedArgument (member_name);
942                                         return null;
943                                 }
944
945                                 if (member is FieldExpr) {
946                                         FieldExpr fe = (FieldExpr) member;
947                                         FieldInfo fi = fe.FieldInfo;
948
949                                         if (fi.IsInitOnly) {
950                                                 Error_InvalidNamedArgument (member_name);
951                                                 return null;
952                                         }
953
954                                         if (a.Expr is Constant) {
955                                                 Constant c = (Constant) a.Expr;
956
957                                                 try {
958                                                         if (member_name == "CallingConvention"){
959                                                                 object val = GetValue (ec, c, typeof (CallingConvention));
960                                                                 if (val == null)
961                                                                         return null;
962                                                                 cc = (CallingConvention) val;
963                                                         } else if (member_name == "CharSet"){
964                                                                 charset = (CharSet) c.GetValue ();
965                                                         } else if (member_name == "EntryPoint")
966                                                                 entry_point = (string) c.GetValue ();
967                                                         else if (member_name == "SetLastError")
968                                                                 set_last_err = (bool) c.GetValue ();
969 #if FIXME
970                                                         else if (member_name == "ExactSpelling")
971                                                                 exact_spelling = (bool) c.GetValue ();
972 #endif
973                                                         else if (member_name == "PreserveSig")
974                                                                 preserve_sig = (bool) c.GetValue ();
975                                                 } catch (InvalidCastException){
976                                                         Error_InvalidNamedArgument (member_name);
977                                                         Error_AttributeArgumentNotValid (Location);
978                                                 }
979                                         } else { 
980                                                 Error_AttributeArgumentNotValid (Location);
981                                                 return null;
982                                         }
983                                         
984                                 }
985                         }
986
987                         if (entry_point == null)
988                                 entry_point = name;
989                         if (set_last_err)
990                                 charset = (CharSet)((int)charset | 0x40);
991                         
992                         MethodBuilder mb = builder.DefinePInvokeMethod (
993                                 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
994                                 CallingConventions.Standard,
995                                 ret_type,
996                                 param_types,
997                                 cc,
998                                 charset);
999
1000                         if (preserve_sig)
1001                                 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1002                         
1003                         return mb;
1004                 }
1005
1006                 private Expression GetValue () 
1007                 {
1008                         if ((Arguments == null) || (Arguments.Count < 1))
1009                                 return null;
1010                         ArrayList al = (ArrayList) Arguments [0];
1011                         if ((al == null) || (al.Count < 1))
1012                                 return null;
1013                         Argument arg = (Argument) al [0];
1014                         if ((arg == null) || (arg.Expr == null))
1015                                 return null;
1016                         return arg.Expr;
1017                 }
1018
1019                 public string GetString () 
1020                 {
1021                         Expression e = GetValue ();
1022                         if (e is StringLiteral)
1023                                 return (e as StringLiteral).Value;
1024                         return null;
1025                 }
1026
1027                 public bool GetBoolean () 
1028                 {
1029                         Expression e = GetValue ();
1030                         if (e is BoolLiteral)
1031                                 return (e as BoolLiteral).Value;
1032                         return false;
1033                 }
1034         }
1035         
1036
1037         /// <summary>
1038         /// For global attributes (assembly, module) we need special handling.
1039         /// Attributes can be located in the several files
1040         /// </summary>
1041         public class GlobalAttribute: Attribute
1042         {
1043                 public readonly NamespaceEntry ns;
1044
1045                 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1046                         base (target, name, args, loc)
1047                 {
1048                         ns = container.NamespaceEntry;
1049                 }
1050
1051                 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1052                 {
1053                         NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1054                         if (old == null || old.NS == null || old.NS == Namespace.Root) 
1055                                 ec.DeclSpace.NamespaceEntry = ns;
1056                         return base.CheckAttributeType (ec, complain);
1057                 }
1058         }
1059
1060         public class Attributes {
1061                 public ArrayList Attrs;
1062
1063                 public Attributes (Attribute a)
1064                 {
1065                         Attrs = new ArrayList ();
1066                         Attrs.Add (a);
1067                 }
1068
1069                 public Attributes (ArrayList attrs)
1070                 {
1071                         Attrs = attrs;
1072                 }
1073
1074                 public void AddAttributes (ArrayList attrs)
1075                 {
1076                         Attrs.AddRange (attrs);
1077                 }
1078
1079                 /// <summary>
1080                 /// Checks whether attribute target is valid for the current element
1081                 /// </summary>
1082                 public void CheckTargets (string[] possible_targets)
1083                 {
1084                         foreach (Attribute a in Attrs) {
1085                                 if (a.Target == null) {
1086                                         a.Target = possible_targets [0];
1087                                         continue;
1088                                 }
1089
1090                                 if (((IList) possible_targets).Contains (a.Target))
1091                                         continue;
1092
1093                                 StringBuilder sb = new StringBuilder ();
1094                                 foreach (string s in possible_targets) {
1095                                         sb.Append (s);
1096                                         sb.Append (", ");
1097                                 }
1098                                 sb.Remove (sb.Length - 2, 2);
1099                                 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1100                         }
1101                 }
1102
1103                 private Attribute Search (Type t, EmitContext ec, bool complain)
1104                 {
1105                         foreach (Attribute a in Attrs) {
1106                                 if (a.ResolveType (ec, false) == t)
1107                                         return a;
1108                         }
1109                         return null;
1110                 }
1111
1112                 public Attribute Search (Type t, EmitContext ec)
1113                 {
1114                         return Search (t, ec, true);
1115                 }
1116
1117                 public void Emit (EmitContext ec, Attributable ias)
1118                 {
1119                         ListDictionary ld = new ListDictionary ();
1120
1121                         foreach (Attribute a in Attrs)
1122                                 a.Emit (ec, ias, ld);
1123                 }
1124
1125                 public bool Contains (Type t, EmitContext ec)
1126                 {
1127                         return Search (t, ec) != null;
1128                 }
1129
1130                 public Attribute GetClsCompliantAttribute (EmitContext ec)
1131                 {
1132                         return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1133                 }
1134
1135                 /// <summary>
1136                 /// Pulls the IndexerName attribute from an Indexer if it exists.
1137                 /// </summary>
1138                 public string ScanForIndexerName (EmitContext ec)
1139                 {
1140                         Attribute a = Search (TypeManager.indexer_name_type, ec);
1141                         if (a == null)
1142                                 return null;
1143
1144                         // Remove the attribute from the list
1145                         //TODO: It is very close to hack and it can crash here
1146                         Attrs.Remove (a);
1147
1148                         return a.IndexerName_GetIndexerName (ec);
1149                 }
1150
1151         }
1152
1153         /// <summary>
1154         /// Helper class for attribute verification routine.
1155         /// </summary>
1156         sealed class AttributeTester
1157         {
1158                 static PtrHashtable analyzed_types = new PtrHashtable ();
1159                 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1160
1161                 private AttributeTester ()
1162                 {
1163                 }
1164
1165                 /// <summary>
1166                 /// Returns true if parameters of two compared methods are CLS-Compliant.
1167                 /// It tests differing only in ref or out, or in array rank.
1168                 /// </summary>
1169                 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b) 
1170                 {
1171                         if (types_a == null || types_b == null)
1172                                 return true;
1173
1174                         if (types_a.Length != types_b.Length)
1175                                 return true;
1176
1177                         for (int i = 0; i < types_b.Length; ++i) {
1178                                 Type aType = types_a [i];
1179                                 Type bType = types_b [i];
1180
1181                                 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1182                                         return false;
1183                                 }
1184
1185                                 Type aBaseType = aType;
1186                                 bool is_either_ref_or_out = false;
1187
1188                                 if (aType.IsByRef || aType.IsPointer) {
1189                                         aBaseType = aType.GetElementType ();
1190                                         is_either_ref_or_out = true;
1191                                 }
1192
1193                                 Type bBaseType = bType;
1194                                 if (bType.IsByRef || bType.IsPointer) 
1195                                 {
1196                                         bBaseType = bType.GetElementType ();
1197                                         is_either_ref_or_out = !is_either_ref_or_out;
1198                                 }
1199
1200                                 if (aBaseType != bBaseType)
1201                                         continue;
1202
1203                                 if (is_either_ref_or_out)
1204                                         return false;
1205                         }
1206                         return true;
1207                 }
1208
1209                 /// <summary>
1210                 /// Goes through all parameters and test if they are CLS-Compliant.
1211                 /// </summary>
1212                 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1213                 {
1214                         if (fixedParameters == null)
1215                                 return true;
1216
1217                         foreach (Parameter arg in fixedParameters) {
1218                                 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1219                                         Report.Error_T (3001, loc, arg.GetSignatureForError ());
1220                                         return false;
1221                                 }
1222                         }
1223                         return true;
1224                 }
1225
1226
1227                 /// <summary>
1228                 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1229                 /// </summary>
1230                 public static bool IsClsCompliant (Type type) 
1231                 {
1232                         if (type == null)
1233                                 return true;
1234
1235                         object type_compliance = analyzed_types[type];
1236                         if (type_compliance != null)
1237                                 return type_compliance == TRUE;
1238
1239                         if (type.IsPointer) {
1240                                 analyzed_types.Add (type, null);
1241                                 return false;
1242                         }
1243
1244                         bool result;
1245                         if (type.IsArray || type.IsByRef)       {
1246                                 result = IsClsCompliant (TypeManager.GetElementType (type));
1247                         } else {
1248                                 result = AnalyzeTypeCompliance (type);
1249                         }
1250                         analyzed_types.Add (type, result ? TRUE : FALSE);
1251                         return result;
1252                 }                
1253
1254                 static object TRUE = new object ();
1255                 static object FALSE = new object ();
1256
1257                 /// <summary>
1258                 /// Non-hierarchical CLS Compliance analyzer
1259                 /// </summary>
1260                 public static bool IsComplianceRequired (MemberInfo mi, DeclSpace ds)
1261                 {
1262                         DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
1263
1264                         // Type is external, we can get attribute directly
1265                         if (temp_ds == null) {
1266                                 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1267                                 return (cls_attribute.Length == 1 && ((CLSCompliantAttribute)cls_attribute[0]).IsCompliant);
1268                         }
1269
1270                         string tmp_name;
1271                         // Interface doesn't store full name
1272                         if (temp_ds is Interface)
1273                                 tmp_name = mi.Name;
1274                         else
1275                                 tmp_name = String.Concat (temp_ds.Name, ".", mi.Name);
1276
1277                         MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
1278                         return mc.IsClsCompliaceRequired (ds);
1279                 }
1280
1281                 public static void VerifyModulesClsCompliance ()
1282                 {
1283                         Module[] modules = TypeManager.Modules;
1284                         if (modules == null)
1285                                 return;
1286
1287                         // The first module is generated assembly
1288                         for (int i = 1; i < modules.Length; ++i) {
1289                                 Module module = modules [i];
1290                                 if (!IsClsCompliant (module)) {
1291                                         Report.Error_T (3013, module.Name);
1292                                         return;
1293                                 }
1294                         }
1295                 }
1296
1297                 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider) 
1298                 {
1299                         object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1300                         if (CompliantAttribute.Length == 0)
1301                                 return false;
1302
1303                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1304                 }
1305
1306                 static bool AnalyzeTypeCompliance (Type type)
1307                 {
1308                         DeclSpace ds = TypeManager.LookupDeclSpace (type);
1309                         if (ds != null) {
1310                                 return ds.IsClsCompliaceRequired (ds.Parent);
1311                         }
1312
1313                         object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1314                         if (CompliantAttribute.Length == 0) 
1315                                 return IsClsCompliant (type.Assembly);
1316
1317                         return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1318                 }
1319
1320                 /// <summary>
1321                 /// Returns instance of ObsoleteAttribute when method is obsolete
1322                 /// </summary>
1323                 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1324                 {
1325                         IMethodData mc = TypeManager.GetMethod (mb);
1326                         if (mc != null) 
1327                                 return mc.GetObsoleteAttribute ();
1328
1329                         // TODO: remove after Constructor will be ready for IMethodData
1330                         if (mb.DeclaringType is TypeBuilder)
1331                                 return null;
1332
1333                         return GetMemberObsoleteAttribute (mb);
1334                 }
1335
1336                 /// <summary>
1337                 /// Returns instance of ObsoleteAttribute when member is obsolete
1338                 /// </summary>
1339                 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1340                 {
1341                         object type_obsolete = analyzed_member_obsolete [mi];
1342                         if (type_obsolete == FALSE)
1343                                 return null;
1344
1345                         if (type_obsolete != null)
1346                                 return (ObsoleteAttribute)type_obsolete;
1347
1348                         ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1349                         analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1350                         return oa;
1351                 }
1352
1353                 /// <summary>
1354                 /// Common method for Obsolete error/warning reporting.
1355                 /// </summary>
1356                 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1357                 {
1358                         if (oa.IsError) {
1359                                 Report.Error_T (619, loc, member, oa.Message);
1360                                 return;
1361                         }
1362
1363                         if (oa.Message == null) {
1364                                 Report.Warning_T (612, loc, member);
1365                                 return;
1366                         }
1367                         Report.Warning_T (618, loc, member, oa.Message);
1368                 }
1369         }
1370 }