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