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