2004-05-21 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                 //
198                 // Given an expression, if the expression is a valid attribute-argument-expression
199                 // returns an object that can be used to encode it, or null on failure.
200                 //
201                 public static bool GetAttributeArgumentExpression (Expression e, Location loc, out object result)
202                 {
203                         if (e is Constant) {
204                                 result = ((Constant) e).GetValue ();
205                                 return true;
206                         } else if (e is TypeOf) {
207                                 result = ((TypeOf) e).TypeArg;
208                                 return true;
209                         } else if (e is ArrayCreation){
210                                 result =  ((ArrayCreation) e).EncodeAsAttribute ();
211                                 if (result != null)
212                                         return true;
213                         } else if (e is EmptyCast) {
214                                 result = e;
215                                 if (((EmptyCast) e).Child is Constant) {
216                                         result = ((Constant) ((EmptyCast)e).Child).GetValue();
217                                 }
218                                 return true;
219                         }
220
221                         result = null;
222                         Error_AttributeArgumentNotValid (loc);
223                         return false;
224                 }
225                 
226                 public CustomAttributeBuilder Resolve (EmitContext ec)
227                 {
228                         Type oldType = Type;
229                         
230                         // Sanity check.
231                         Type = CheckAttributeType (ec, true);
232                         if (oldType == null && Type == null)
233                                 return null;
234                         if (oldType != null && oldType != Type) {
235                                 Report.Error (-6, Location,
236                                               "Attribute {0} resolved to different types at different times: {1} vs. {2}",
237                                               Name, oldType, Type);
238                                 return null;
239                         }
240
241                         bool MethodImplAttr = false;
242                         bool MarshalAsAttr = false;
243                         bool GuidAttr = false;
244                         bool usage_attr = false;
245
246                         bool DoCompares = true;
247
248                         //
249                         // If we are a certain special attribute, we
250                         // set the information accordingly
251                         //
252                         
253                         if (Type == TypeManager.attribute_usage_type)
254                                 usage_attr = true;
255                         else if (Type == TypeManager.methodimpl_attr_type)
256                                 MethodImplAttr = true;
257                         else if (Type == TypeManager.marshal_as_attr_type)
258                                 MarshalAsAttr = true;
259                         else if (Type == TypeManager.guid_attr_type)
260                                 GuidAttr = true;
261                         else
262                                 DoCompares = false;
263
264                         // Now we extract the positional and named arguments
265                         
266                         ArrayList pos_args = new ArrayList ();
267                         ArrayList named_args = new ArrayList ();
268                         int pos_arg_count = 0;
269                         
270                         if (Arguments != null) {
271                                 pos_args = (ArrayList) Arguments [0];
272                                 if (pos_args != null)
273                                         pos_arg_count = pos_args.Count;
274                                 if (Arguments.Count > 1)
275                                         named_args = (ArrayList) Arguments [1];
276                         }
277
278                         pos_values = new object [pos_arg_count];
279
280                         //
281                         // First process positional arguments 
282                         //
283
284                         int i;
285                         for (i = 0; i < pos_arg_count; i++) {
286                                 Argument a = (Argument) pos_args [i];
287                                 Expression e;
288
289                                 if (!a.Resolve (ec, Location))
290                                         return null;
291
292                                 e = a.Expr;
293
294                                 object val;
295                                 if (!GetAttributeArgumentExpression (e, Location, out val))
296                                         return null;
297                                 
298                                 pos_values [i] = val;
299                                 if (DoCompares){
300                                         if (usage_attr)
301                                                 usage_attribute = new AttributeUsageAttribute ((AttributeTargets) pos_values [0]);
302                                         else if (MethodImplAttr)
303                                                 this.ImplOptions = (MethodImplOptions) pos_values [0];
304                                         else if (GuidAttr){
305                                                 //
306                                                 // we will later check the validity of the type
307                                                 //
308                                                 if (pos_values [0] is string){
309                                                         if (!ValidateGuid ((string) pos_values [0]))
310                                                                 return null;
311                                                 }
312                                                 
313                                         } else if (MarshalAsAttr)
314                                                 this.UnmanagedType =
315                                                 (System.Runtime.InteropServices.UnmanagedType) pos_values [0];
316                                 }
317                         }
318
319                         //
320                         // Now process named arguments
321                         //
322
323                         ArrayList field_infos = null;
324                         ArrayList prop_infos  = null;
325                         ArrayList field_values = null;
326                         ArrayList prop_values = null;
327
328                         if (named_args.Count > 0) {
329                                 field_infos = new ArrayList ();
330                                 prop_infos  = new ArrayList ();
331                                 field_values = new ArrayList ();
332                                 prop_values = new ArrayList ();
333                         }
334
335                         Hashtable seen_names = new Hashtable();
336                         
337                         for (i = 0; i < named_args.Count; i++) {
338                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
339                                 string member_name = (string) de.Key;
340                                 Argument a  = (Argument) de.Value;
341                                 Expression e;
342
343                                 if (seen_names.Contains(member_name)) {
344                                         Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
345                                         return null;
346                                 }                               
347                                 seen_names.Add(member_name, 1);
348                                 
349                                 if (!a.Resolve (ec, Location))
350                                         return null;
351
352                                 Expression member = Expression.MemberLookup (
353                                         ec, Type, member_name,
354                                         MemberTypes.Field | MemberTypes.Property,
355                                         BindingFlags.Public | BindingFlags.Instance,
356                                         Location);
357
358                                 if (member == null || !(member is PropertyExpr || member is FieldExpr)) {
359                                         Error_InvalidNamedArgument (member_name);
360                                         return null;
361                                 }
362
363                                 e = a.Expr;
364                                 if (member is PropertyExpr) {
365                                         PropertyExpr pe = (PropertyExpr) member;
366                                         PropertyInfo pi = pe.PropertyInfo;
367
368                                         if (!pi.CanWrite) {
369                                                 Error_InvalidNamedArgument (member_name);
370                                                 return null;
371                                         }
372
373                                         if (e is Constant) {
374                                                 Constant c;
375                                                 
376                                                 if (e.Type != pi.PropertyType){
377                                                         c = Const.ChangeType (Location, (Constant) e, pi.PropertyType);
378                                                         if (c == null)
379                                                                 return null;
380                                                 } else
381                                                         c = (Constant) e;
382                                                 
383                                                 object o = c.GetValue ();
384                                                 prop_values.Add (o);
385                                                 
386                                                 if (usage_attribute != null) {
387                                                         if (member_name == "AllowMultiple")
388                                                                 usage_attribute.AllowMultiple = (bool) o;
389                                                         if (member_name == "Inherited")
390                                                                 usage_attribute.Inherited = (bool) o;
391                                                 }
392                                                 
393                                         } else if (e is TypeOf) {
394                                                 prop_values.Add (((TypeOf) e).TypeArg);
395                                         } else if (e is ArrayCreation) {
396                                                 prop_values.Add (((ArrayCreation) e).EncodeAsAttribute());
397                                         } else {
398                                                 Error_AttributeArgumentNotValid (Location);
399                                                 return null;
400                                         }
401                                         
402                                         prop_infos.Add (pi);
403                                         
404                                 } else if (member is FieldExpr) {
405                                         FieldExpr fe = (FieldExpr) member;
406                                         FieldInfo fi = fe.FieldInfo;
407
408                                         if (fi.IsInitOnly) {
409                                                 Error_InvalidNamedArgument (member_name);
410                                                 return null;
411                                         }
412
413                                         //
414                                         // Handle charset here, and set the TypeAttributes
415                                         
416                                         if (e is Constant){
417                                                 Constant c = (Constant) e;;
418                                                 
419                                                 if (c.Type != fi.FieldType){
420                                                         c = Const.ChangeType (Location, (Constant) e, fi.FieldType);
421                                                         if (c == null)
422                                                                 return null;
423                                                 } 
424                                                 
425                                                 object value = c.GetValue ();
426                                                 field_values.Add (value);
427                                         } else if (e is TypeOf) {
428                                                 field_values.Add (((TypeOf) e).TypeArg);
429                                         } else {
430                                                 Error_AttributeArgumentNotValid (Location);
431                                                 return null;
432                                         }
433                                         
434                                         field_infos.Add (fi);
435                                 }
436                         }
437
438                         Expression mg = Expression.MemberLookup (
439                                 ec, Type, ".ctor", MemberTypes.Constructor,
440                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
441                                 Location);
442
443                         if (mg == null) {
444                                 Error_AttributeConstructorMismatch ();
445                                 return null;
446                         }
447
448                         MethodBase constructor = Invocation.OverloadResolve (
449                                 ec, (MethodGroupExpr) mg, pos_args, Location);
450
451                         if (constructor == null) {
452                                 Error_AttributeConstructorMismatch ();
453                                 return null;
454                         }
455
456                         //
457                         // Now we perform some checks on the positional args as they
458                         // cannot be null for a constructor which expects a parameter
459                         // of type object
460                         //
461
462                         ParameterData pd = Invocation.GetParameterData (constructor);
463
464                         int group_in_params_array = Int32.MaxValue;
465                         int pc = pd.Count;
466                         if (pc > 0 && pd.ParameterModifier (pc-1) == Parameter.Modifier.PARAMS)
467                                 group_in_params_array = pc-1;
468
469                         for (int j = 0; j < pos_arg_count; ++j) {
470                                 Argument a = (Argument) pos_args [j];
471                                 
472                                 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
473                                         Error_AttributeArgumentNotValid (Location);
474                                         return null;
475                                 }
476
477                                 if (j < group_in_params_array)
478                                         continue;
479                                 
480                                 if (j == group_in_params_array){
481                                         object v = pos_values [j];
482                                         int count = pos_arg_count - j;
483
484                                         object [] array = new object [count];
485                                         pos_values [j] = array;
486                                         array [0] = v;
487                                 } else {
488                                         object [] array = (object []) pos_values [group_in_params_array];
489
490                                         array [j - group_in_params_array] = pos_values [j];
491                                 }
492                         }
493
494                         //
495                         // Adjust the size of the pos_values if it had params
496                         //
497                         if (group_in_params_array != Int32.MaxValue){
498                                 int argc = group_in_params_array+1;
499                                 object [] new_pos_values = new object [argc];
500
501                                 for (int p = 0; p < argc; p++)
502                                         new_pos_values [p] = pos_values [p];
503                                 pos_values = new_pos_values;
504                         }
505
506                         try {
507                                 if (named_args.Count > 0) {
508                                         prop_info_arr = new PropertyInfo [prop_infos.Count];
509                                         field_info_arr = new FieldInfo [field_infos.Count];
510                                         field_values_arr = new object [field_values.Count];
511                                         prop_values_arr = new object [prop_values.Count];
512
513                                         field_infos.CopyTo  (field_info_arr, 0);
514                                         field_values.CopyTo (field_values_arr, 0);
515
516                                         prop_values.CopyTo  (prop_values_arr, 0);
517                                         prop_infos.CopyTo   (prop_info_arr, 0);
518
519                                         cb = new CustomAttributeBuilder (
520                                                 (ConstructorInfo) constructor, pos_values,
521                                                 prop_info_arr, prop_values_arr,
522                                                 field_info_arr, field_values_arr);
523                                 }
524                                 else
525                                         cb = new CustomAttributeBuilder (
526                                                 (ConstructorInfo) constructor, pos_values);
527                         } catch (NullReferenceException) {
528                                 // 
529                                 // Don't know what to do here
530                                 //
531                                 Report.Warning (
532                                         -101, Location, "NullReferenceException while trying to create attribute." +
533                                         "Something's wrong!");
534                         } catch (Exception e) {
535                                 //
536                                 // Sample:
537                                 // using System.ComponentModel;
538                                 // [DefaultValue (CollectionChangeAction.Add)]
539                                 // class X { static void Main () {} }
540                                 //
541                                 Report.Warning (
542                                         -23, Location,
543                                         "The compiler can not encode this attribute in .NET due to\n" +
544                                         "\ta bug in the .NET runtime.  Try the Mono runtime.\nThe error was: " + e.Message);
545                         }
546                         
547                         return cb;
548                 }
549
550                 /// <summary>
551                 ///   Get a string containing a list of valid targets for the attribute 'attr'
552                 /// </summary>
553                 static string GetValidTargets (Attribute attr)
554                 {
555                         StringBuilder sb = new StringBuilder ();
556                         AttributeTargets targets = attr.GetAttributeUsage ().ValidOn;
557
558                         if ((targets & AttributeTargets.Assembly) != 0)
559                                 sb.Append ("'assembly' ");
560
561                         if ((targets & AttributeTargets.Class) != 0)
562                                 sb.Append ("'class' ");
563
564                         if ((targets & AttributeTargets.Constructor) != 0)
565                                 sb.Append ("'constructor' ");
566
567                         if ((targets & AttributeTargets.Delegate) != 0)
568                                 sb.Append ("'delegate' ");
569
570                         if ((targets & AttributeTargets.Enum) != 0)
571                                 sb.Append ("'enum' ");
572
573                         if ((targets & AttributeTargets.Event) != 0)
574                                 sb.Append ("'event' ");
575
576                         if ((targets & AttributeTargets.Field) != 0)
577                                 sb.Append ("'field' ");
578
579                         if ((targets & AttributeTargets.Interface) != 0)
580                                 sb.Append ("'interface' ");
581
582                         if ((targets & AttributeTargets.Method) != 0)
583                                 sb.Append ("'method' ");
584
585                         if ((targets & AttributeTargets.Module) != 0)
586                                 sb.Append ("'module' ");
587
588                         if ((targets & AttributeTargets.Parameter) != 0)
589                                 sb.Append ("'parameter' ");
590
591                         if ((targets & AttributeTargets.Property) != 0)
592                                 sb.Append ("'property' ");
593
594                         if ((targets & AttributeTargets.ReturnValue) != 0)
595                                 sb.Append ("'return' ");
596
597                         if ((targets & AttributeTargets.Struct) != 0)
598                                 sb.Append ("'struct' ");
599
600                         return sb.ToString ();
601
602                 }
603
604                 public static void Error_AttributeNotValidForElement (Attribute a, Location loc)
605                 {
606                         Report.Error (
607                                 592, loc, "Attribute '" + a.Name +
608                                 "' is not valid on this declaration type. " +
609                                 "It is valid on " + GetValidTargets (a) + "declarations only.");
610                 }
611
612
613                 /// <summary>
614                 /// Returns AttributeUsage attribute for this type
615                 /// </summary>
616                 public AttributeUsageAttribute GetAttributeUsage ()
617                 {
618                         AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
619                         if (ua != null)
620                                 return ua;
621
622                         Class attr_class = TypeManager.LookupClass (Type);
623
624                         if (attr_class == null) {
625                                 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
626                                 ua = (AttributeUsageAttribute)usage_attr [0];
627                                 usage_attr_cache.Add (Type, ua);
628                                 return ua;
629                         }
630                 
631                         return attr_class.AttributeUsage;
632                 }
633
634
635                 //
636                 // This pulls the condition name out of a Conditional attribute
637                 //
638                 public string Conditional_GetConditionName ()
639                 {
640                         //
641                         // So we have a Conditional, pull the data out.
642                         //
643                         if (Arguments == null || Arguments [0] == null){
644                                 Error_AttributeConstructorMismatch ();
645                                 return null;
646                         }
647
648                         ArrayList pos_args = (ArrayList) Arguments [0];
649                         if (pos_args.Count != 1){
650                                 Error_AttributeConstructorMismatch ();
651                                 return null;
652                         }
653
654                         Argument arg = (Argument) pos_args [0]; 
655                         if (!(arg.Expr is StringConstant)){
656                                 Error_AttributeConstructorMismatch ();
657                                 return null;
658                         }
659
660                         return ((StringConstant) arg.Expr).Value;
661                 }
662
663                 //
664                 // This pulls the obsolete message and error flag out of an Obsolete attribute
665                 //
666                 public string Obsolete_GetObsoleteMessage (out bool is_error)
667                 {
668                         is_error = false;
669                         //
670                         // So we have an Obsolete, pull the data out.
671                         //
672                         if (Arguments == null || Arguments [0] == null)
673                                 return "";
674
675                         ArrayList pos_args = (ArrayList) Arguments [0];
676                         if (pos_args.Count == 0)
677                                 return "";
678                         else if (pos_args.Count > 2){
679                                 Error_AttributeConstructorMismatch ();
680                                 return null;
681                         }
682
683                         Argument arg = (Argument) pos_args [0]; 
684                         if (!(arg.Expr is StringConstant)){
685                                 Error_AttributeConstructorMismatch ();
686                                 return null;
687                         }
688
689                         if (pos_args.Count == 2){
690                                 Argument arg2 = (Argument) pos_args [1];
691                                 if (!(arg2.Expr is BoolConstant)){
692                                         Error_AttributeConstructorMismatch ();
693                                         return null;
694                                 }
695                                 is_error = ((BoolConstant) arg2.Expr).Value;
696                         }
697
698                         return ((StringConstant) arg.Expr).Value;
699                 }
700
701                 public string IndexerName_GetIndexerName (EmitContext ec)
702                 {
703                         if (Arguments == null || Arguments [0] == null){
704                                 Error_AttributeConstructorMismatch ();
705                                 return null;
706                         }
707                         ArrayList pos_args = (ArrayList) Arguments [0];
708                         if (pos_args.Count != 1) {
709                                 Error_AttributeConstructorMismatch ();
710                                 return null;
711                         }
712                         
713                         Argument arg = (Argument) pos_args [0];
714                         if (!arg.Resolve (ec, Location))
715                                 return null;
716                         
717                         StringConstant sc = arg.Expr as StringConstant;
718                         if (sc == null){
719                                 Error_AttributeConstructorMismatch ();
720                                 return null;
721                         }
722                         
723                         return sc.Value;
724                 }
725
726                 /// <summary>
727                 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
728                 /// before ApplyAttribute. We need to resolve the arguments.
729                 /// This situation occurs when class deps is differs from Emit order.  
730                 /// </summary>
731                 public bool GetClsCompliantAttributeValue (DeclSpace ds)
732                 {
733                         if (pos_values == null) {
734                                 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
735
736                                 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
737                                 // But because a lot of attribute class code must be rewritten will be better to wait...
738                                 Resolve (ec);
739                         }
740
741                         // Some error occurred
742                         if (pos_values [0] == null)
743                                 return false;
744
745                         return (bool)pos_values [0];
746                 }
747
748                 public object GetPositionalValue (int i)
749                 {
750                         return (pos_values == null) ? null : pos_values[i];
751                 }
752
753                 object GetFieldValue (string name)
754                 {
755                         int i;
756                         if (field_info_arr == null)
757                                 return null;
758                         i = 0;
759                         foreach (FieldInfo fi in field_info_arr) {
760                                 if (fi.Name == name)
761                                         return field_values_arr [i];
762                                 i++;
763                         }
764                         return null;
765                 }
766
767                 public UnmanagedMarshal GetMarshal ()
768                 {
769                         object o = GetFieldValue ("ArraySubType");
770                         UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
771                         
772                         switch (UnmanagedType) {
773                         case UnmanagedType.CustomMarshaler:
774                                 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
775                                                                        BindingFlags.Static | BindingFlags.Public);
776                                 if (define_custom == null)
777                                         return null;
778                                 
779                                 object [] args = new object [4];
780                                 args [0] = GetFieldValue ("MarshalTypeRef");
781                                 args [1] = GetFieldValue ("MarshalCookie");
782                                 args [2] = GetFieldValue ("MarshalType");
783                                 args [3] = Guid.Empty;
784                                 return (UnmanagedMarshal) define_custom.Invoke (null, args);
785                                 
786                         case UnmanagedType.LPArray:                             
787                                 return UnmanagedMarshal.DefineLPArray (array_sub_type);
788                         
789                         case UnmanagedType.SafeArray:
790                                 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
791                         
792                         case UnmanagedType.ByValArray:
793                                 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
794                         
795                         case UnmanagedType.ByValTStr:
796                                 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
797                         
798                         default:
799                                 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
800                         }
801                 }
802
803                 public bool IsInternalCall
804                 {
805                         get { return ImplOptions == MethodImplOptions.InternalCall; }
806                 }
807
808                 /// <summary>
809                 /// Emit attribute for Attributable symbol
810                 /// </summary>
811                 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
812                 {
813                         CustomAttributeBuilder cb = Resolve (ec);
814                         if (cb == null)
815                                 return;
816
817                         AttributeUsageAttribute usage_attr = GetAttributeUsage ();
818                         if ((usage_attr.ValidOn & ias.AttributeTargets) == 0) {
819                                 Error_AttributeNotValidForElement (this, Location);
820                                 return;
821                         }
822
823                         ias.ApplyAttributeBuilder (this, cb);
824
825                         if (!usage_attr.AllowMultiple && emitted_attr.Contains (Target)) {
826                                 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
827                         }
828
829                         emitted_attr [Type] = Target;
830
831                         // Here we are testing attribute arguments for array usage (error 3016)
832                         if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
833                                 if (Arguments == null)
834                                         return;
835
836                                 ArrayList pos_args = (ArrayList) Arguments [0];
837                                 if (pos_args != null) {
838                                         foreach (Argument arg in pos_args) { 
839                                                 // Type is undefined (was error 246)
840                                                 if (arg.Type == null)
841                                                         return;
842
843                                                 if (arg.Type.IsArray) {
844                                                         Report.Error_T (3016, Location);
845                                                         return;
846                                                 }
847                                         }
848                                 }
849                         
850                                 if (Arguments.Count < 2)
851                                         return;
852                         
853                                 ArrayList named_args = (ArrayList) Arguments [1];
854                                 foreach (DictionaryEntry de in named_args) {
855                                         Argument arg  = (Argument) de.Value;
856
857                                         // Type is undefined (was error 246)
858                                         if (arg.Type == null)
859                                                 return;
860
861                                         if (arg.Type.IsArray) {
862                                                 Report.Error_T (3016, Location);
863                                                 return;
864                                         }
865                                 }
866                         }
867                 }
868
869                 public object GetValue (EmitContext ec, Constant c, Type target)
870                 {
871                         if (Convert.ImplicitConversionExists (ec, c, target))
872                                 return c.GetValue ();
873
874                         Convert.Error_CannotImplicitConversion (Location, c.Type, target);
875                         return null;
876                 }
877                 
878                 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
879                                                           MethodAttributes flags, Type ret_type, Type [] param_types)
880                 {
881                         //
882                         // We extract from the attribute the information we need 
883                         //
884
885                         if (Arguments == null) {
886                                 Console.WriteLine ("Internal error : this is not supposed to happen !");
887                                 return null;
888                         }
889
890                         ResolveType (ec, true);
891                         if (Type == null)
892                                 return null;
893                         
894                         ArrayList named_args = new ArrayList ();
895                         
896                         ArrayList pos_args = (ArrayList) Arguments [0];
897                         if (Arguments.Count > 1)
898                                 named_args = (ArrayList) Arguments [1];
899                         
900
901                         string dll_name = null;
902                         
903                         Argument tmp = (Argument) pos_args [0];
904
905                         if (!tmp.Resolve (ec, Location))
906                                 return null;
907                         
908                         if (tmp.Expr is Constant)
909                                 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
910                         else { 
911                                 Error_AttributeArgumentNotValid (Location);
912                                 return null;
913                         }
914
915                         // Now we process the named arguments
916                         CallingConvention cc = CallingConvention.Winapi;
917                         CharSet charset = CharSet.Ansi;
918                         bool preserve_sig = true;
919 #if FIXME
920                         bool exact_spelling = false;
921 #endif
922                         bool set_last_err = false;
923                         string entry_point = null;
924
925                         for (int i = 0; i < named_args.Count; i++) {
926
927                                 DictionaryEntry de = (DictionaryEntry) named_args [i];
928
929                                 string member_name = (string) de.Key;
930                                 Argument a  = (Argument) de.Value;
931
932                                 if (!a.Resolve (ec, Location))
933                                         return null;
934
935                                 Expression member = Expression.MemberLookup (
936                                         ec, Type, member_name, 
937                                         MemberTypes.Field | MemberTypes.Property,
938                                         BindingFlags.Public | BindingFlags.Instance,
939                                         Location);
940
941                                 if (member == null || !(member is FieldExpr)) {
942                                         Error_InvalidNamedArgument (member_name);
943                                         return null;
944                                 }
945
946                                 if (member is FieldExpr) {
947                                         FieldExpr fe = (FieldExpr) member;
948                                         FieldInfo fi = fe.FieldInfo;
949
950                                         if (fi.IsInitOnly) {
951                                                 Error_InvalidNamedArgument (member_name);
952                                                 return null;
953                                         }
954
955                                         if (a.Expr is Constant) {
956                                                 Constant c = (Constant) a.Expr;
957
958                                                 try {
959                                                         if (member_name == "CallingConvention"){
960                                                                 object val = GetValue (ec, c, typeof (CallingConvention));
961                                                                 if (val == null)
962                                                                         return null;
963                                                                 cc = (CallingConvention) val;
964                                                         } else if (member_name == "CharSet"){
965                                                                 charset = (CharSet) c.GetValue ();
966                                                         } else if (member_name == "EntryPoint")
967                                                                 entry_point = (string) c.GetValue ();
968                                                         else if (member_name == "SetLastError")
969                                                                 set_last_err = (bool) c.GetValue ();
970 #if FIXME
971                                                         else if (member_name == "ExactSpelling")
972                                                                 exact_spelling = (bool) c.GetValue ();
973 #endif
974                                                         else if (member_name == "PreserveSig")
975                                                                 preserve_sig = (bool) c.GetValue ();
976                                                 } catch (InvalidCastException){
977                                                         Error_InvalidNamedArgument (member_name);
978                                                         Error_AttributeArgumentNotValid (Location);
979                                                 }
980                                         } else { 
981                                                 Error_AttributeArgumentNotValid (Location);
982                                                 return null;
983                                         }
984                                         
985                                 }
986                         }
987
988                         if (entry_point == null)
989                                 entry_point = name;
990                         if (set_last_err)
991                                 charset = (CharSet)((int)charset | 0x40);
992                         
993                         MethodBuilder mb = builder.DefinePInvokeMethod (
994                                 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
995                                 CallingConventions.Standard,
996                                 ret_type,
997                                 param_types,
998                                 cc,
999                                 charset);
1000
1001                         if (preserve_sig)
1002                                 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1003                         
1004                         return mb;
1005                 }
1006
1007                 private Expression GetValue () 
1008                 {
1009                         if ((Arguments == null) || (Arguments.Count < 1))
1010                                 return null;
1011                         ArrayList al = (ArrayList) Arguments [0];
1012                         if ((al == null) || (al.Count < 1))
1013                                 return null;
1014                         Argument arg = (Argument) al [0];
1015                         if ((arg == null) || (arg.Expr == null))
1016                                 return null;
1017                         return arg.Expr;
1018                 }
1019
1020                 public string GetString () 
1021                 {
1022                         Expression e = GetValue ();
1023                         if (e is StringLiteral)
1024                                 return (e as StringLiteral).Value;
1025                         return null;
1026                 }
1027
1028                 public bool GetBoolean () 
1029                 {
1030                         Expression e = GetValue ();
1031                         if (e is BoolLiteral)
1032                                 return (e as BoolLiteral).Value;
1033                         return false;
1034                 }
1035         }
1036         
1037
1038         /// <summary>
1039         /// For global attributes (assembly, module) we need special handling.
1040         /// Attributes can be located in the several files
1041         /// </summary>
1042         public class GlobalAttribute: Attribute
1043         {
1044                 public readonly NamespaceEntry ns;
1045
1046                 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1047                         base (target, name, args, loc)
1048                 {
1049                         ns = container.NamespaceEntry;
1050                 }
1051
1052                 protected override Type CheckAttributeType (EmitContext ec, bool complain)
1053                 {
1054                         NamespaceEntry old = ec.DeclSpace.NamespaceEntry;
1055                         if (old == null || old.NS == null || old.NS == Namespace.Root) 
1056                                 ec.DeclSpace.NamespaceEntry = ns;
1057                         return base.CheckAttributeType (ec, complain);
1058                 }
1059         }
1060
1061         public class Attributes {
1062                 public ArrayList Attrs;
1063
1064                 public Attributes (Attribute a)
1065                 {
1066                         Attrs = new ArrayList ();
1067                         Attrs.Add (a);
1068                 }
1069
1070                 public Attributes (ArrayList attrs)
1071                 {
1072                         Attrs = attrs;
1073                 }
1074
1075                 public void AddAttributes (ArrayList attrs)
1076                 {
1077                         Attrs.AddRange (attrs);
1078                 }
1079
1080                 /// <summary>
1081                 /// Checks whether attribute target is valid for the current element
1082                 /// </summary>
1083                 public void CheckTargets (string[] possible_targets)
1084                 {
1085                         foreach (Attribute a in Attrs) {
1086                                 if (a.Target == null) {
1087                                         a.Target = possible_targets [0];
1088                                         continue;
1089                                 }
1090
1091                                 if (((IList) possible_targets).Contains (a.Target))
1092                                         continue;
1093
1094                                 StringBuilder sb = new StringBuilder ();
1095                                 foreach (string s in possible_targets) {
1096                                         sb.Append (s);
1097                                         sb.Append (", ");
1098                                 }
1099                                 sb.Remove (sb.Length - 2, 2);
1100                                 Report.Error_T (657, a.Location, a.Target, sb.ToString ());
1101                         }
1102                 }
1103
1104                 private Attribute Search (Type t, EmitContext ec, bool complain)
1105                 {
1106                         foreach (Attribute a in Attrs) {
1107                                 if (a.ResolveType (ec, false) == t)
1108                                         return a;
1109                         }
1110                         return null;
1111                 }
1112
1113                 public Attribute Search (Type t, EmitContext ec)
1114                 {
1115                         return Search (t, ec, true);
1116                 }
1117
1118                 public void Emit (EmitContext ec, Attributable ias)
1119                 {
1120                         ListDictionary ld = new ListDictionary ();
1121
1122                         foreach (Attribute a in Attrs)
1123                                 a.Emit (ec, ias, ld);
1124                 }
1125
1126                 public bool Contains (Type t, EmitContext ec)
1127                 {
1128                         return Search (t, ec) != null;
1129                 }
1130
1131                 public Attribute GetClsCompliantAttribute (EmitContext ec)
1132                 {
1133                         return Search (TypeManager.cls_compliant_attribute_type, ec, false);
1134                 }
1135
1136                 /// <summary>
1137                 /// Pulls the IndexerName attribute from an Indexer if it exists.
1138                 /// </summary>
1139                 public string ScanForIndexerName (EmitContext ec)
1140                 {
1141                         Attribute a = Search (TypeManager.indexer_name_type, ec);
1142                         if (a == null)
1143                                 return null;
1144
1145                         // Remove the attribute from the list
1146                         //TODO: It is very close to hack and it can crash here
1147                         Attrs.Remove (a);
1148
1149                         return a.IndexerName_GetIndexerName (ec);
1150                 }
1151
1152         }
1153
1154         /// <summary>
1155         /// Helper class for attribute verification routine.
1156         /// </summary>
1157         sealed class AttributeTester
1158         {
1159                 static PtrHashtable analyzed_types = 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 }