New test.
[mono.git] / mcs / mcs / support.cs
1 //
2 // support.cs: Support routines to work around the fact that System.Reflection.Emit
3 // can not introspect types that are being constructed
4 //
5 // Author:
6 //   Miguel de Icaza (miguel@ximian.com)
7 //
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
9 //
10
11 using System;
12 using System.IO;
13 using System.Text;
14 using System.Reflection;
15 using System.Collections;
16 using System.Reflection.Emit;
17 using System.Globalization;
18
19 namespace Mono.CSharp {
20
21         public interface ParameterData {
22                 Type ParameterType (int pos);
23                 Type [] Types { get; }
24                 int  Count { get; }
25                 bool HasParams { get; }
26                 string ParameterName (int pos);
27                 string ParameterDesc (int pos);
28                 Parameter.Modifier ParameterModifier (int pos);
29                 string GetSignatureForError ();
30         }
31
32         public class ReflectionParameters : ParameterData {
33                 ParameterInfo [] pi;
34                 Type [] types;
35                 bool last_arg_is_params = false;
36                 bool is_varargs = false;
37                 ParameterData gpd;
38
39                 public ReflectionParameters (MethodBase mb)
40                 {
41                         object [] attrs;
42
43                         ParameterInfo [] pi = mb.GetParameters ();
44                         is_varargs = (mb.CallingConvention & CallingConventions.VarArgs) != 0;
45
46                         this.pi = pi;
47                         int count = pi.Length-1;
48
49                         if (pi.Length == 0) {
50                                 types = Type.EmptyTypes;
51                         } else {
52                                 types = new Type [pi.Length];
53                                 for (int i = 0; i < pi.Length; i++)
54                                         types [i] = pi [i].ParameterType;
55                         }
56
57                         if (count < 0)
58                                 return;
59
60                         MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
61                         if (generic != mb) {
62                                 gpd = TypeManager.GetParameterData (generic);
63                                 last_arg_is_params = gpd.HasParams;
64                                 return;
65                         }
66
67                         attrs = pi [count].GetCustomAttributes (TypeManager.param_array_type, true);
68                         if (attrs == null)
69                                 return;
70
71                         if (attrs.Length == 0)
72                                 return;
73
74                         last_arg_is_params = true;
75                 }
76
77                 public string GetSignatureForError ()
78                 {
79                         StringBuilder sb = new StringBuilder ("(");
80                         for (int i = 0; i < pi.Length; ++i) {
81                                 if (i != 0)
82                                         sb.Append (", ");
83                                 sb.Append (ParameterDesc (i));
84                         }
85                         if (is_varargs) {
86                                 if (pi.Length > 0)
87                                         sb.Append (", ");
88                                 sb.Append ("__arglist");
89                         }
90                         sb.Append (')');
91                         return sb.ToString ();
92                 }
93
94                 public Type ParameterType (int pos)
95                 {
96                         if (last_arg_is_params && pos >= pi.Length - 1)
97                                 return pi [pi.Length - 1].ParameterType;
98                         else if (is_varargs && pos >= pi.Length)
99                                 return TypeManager.runtime_argument_handle_type;
100                         else {
101                                 Type t = pi [pos].ParameterType;
102
103                                 return t;
104                         }
105                 }
106
107                 public string ParameterName (int pos)
108                 {
109                         if (gpd != null)
110                                 return gpd.ParameterName (pos);
111
112                         if (last_arg_is_params && pos >= pi.Length - 1)
113                                 return pi [pi.Length - 1].Name;
114                         else if (is_varargs && pos >= pi.Length)
115                                 return "__arglist";
116                         else
117                                 return pi [pos].Name;
118                 }
119
120                 public string ParameterDesc (int pos)
121                 {
122                         if (is_varargs && pos >= pi.Length)
123                                 return "";
124
125                         StringBuilder sb = new StringBuilder ();
126
127                         if (pi [pos].IsIn)
128                                 sb.Append ("in ");
129
130                         Type partype = ParameterType (pos);
131                         if (partype.IsByRef){
132                                 partype = TypeManager.GetElementType (partype);
133                                 if (pi [pos].IsOut)
134                                         sb.Append ("out ");
135                                 else
136                                         sb.Append ("ref ");
137                         }
138
139                         if (pos >= pi.Length - 1 && last_arg_is_params)
140                                 sb.Append ("params ");
141
142                         sb.Append (TypeManager.CSharpName (partype).Replace ("&", ""));
143
144                         return sb.ToString ();
145                 }
146
147                 public Parameter.Modifier ParameterModifier (int pos)
148                 {
149                         if (last_arg_is_params && pos >= pi.Length - 1)
150                                 return Parameter.Modifier.PARAMS;
151                         else if (is_varargs && pos >= pi.Length)
152                                 return Parameter.Modifier.ARGLIST;
153
154                         if (gpd != null)
155                                 return gpd.ParameterModifier (pos);
156
157                         Type t = pi [pos].ParameterType;
158                         if (t.IsByRef){
159                                 if ((pi [pos].Attributes & (ParameterAttributes.Out|ParameterAttributes.In)) == ParameterAttributes.Out)
160                                         return Parameter.Modifier.OUT;
161                                 else
162                                         return Parameter.Modifier.REF;
163                         }
164
165                         return Parameter.Modifier.NONE;
166                 }
167
168                 public int Count {
169                         get { return is_varargs ? pi.Length + 1 : pi.Length; }
170                 }
171
172                 public bool HasParams {
173                         get { return last_arg_is_params; }
174                 }
175
176                 public Type[] Types {
177                         get { return types; }
178                 }
179         }
180
181 #if GMCS_SOURCE
182         public class ReflectionConstraints : GenericConstraints
183         {
184                 GenericParameterAttributes attrs;
185                 Type base_type;
186                 Type class_constraint;
187                 Type[] iface_constraints;
188                 string name;
189
190                 public static GenericConstraints GetConstraints (Type t)
191                 {
192                         Type [] constraints = t.GetGenericParameterConstraints ();
193                         GenericParameterAttributes attrs = t.GenericParameterAttributes;
194                         if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
195                                 return null;
196                         return new ReflectionConstraints (t.Name, constraints, attrs);
197                 }
198
199                 private ReflectionConstraints (string name, Type [] constraints, GenericParameterAttributes attrs)
200                 {
201                         this.name = name;
202                         this.attrs = attrs;
203
204                         if ((constraints.Length > 0) && !constraints [0].IsInterface) {
205                                 class_constraint = constraints [0];
206                                 iface_constraints = new Type [constraints.Length - 1];
207                                 Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
208                         } else
209                                 iface_constraints = constraints;
210
211                         if (HasValueTypeConstraint)
212                                 base_type = TypeManager.value_type;
213                         else if (class_constraint != null)
214                                 base_type = class_constraint;
215                         else
216                                 base_type = TypeManager.object_type;
217                 }
218
219                 public override string TypeParameter {
220                         get { return name; }
221                 }
222
223                 public override GenericParameterAttributes Attributes {
224                         get { return attrs; }
225                 }
226
227                 public override Type ClassConstraint {
228                         get { return class_constraint; }
229                 }
230
231                 public override Type EffectiveBaseClass {
232                         get { return base_type; }
233                 }
234
235                 public override Type[] InterfaceConstraints {
236                         get { return iface_constraints; }
237                 }
238         }
239 #endif
240
241         class PtrHashtable : Hashtable {
242                 sealed class PtrComparer : IComparer {
243                         private PtrComparer () {}
244
245                         public static PtrComparer Instance = new PtrComparer ();
246
247                         public int Compare (object x, object y)
248                         {
249                                 if (x == y)
250                                         return 0;
251                                 else
252                                         return 1;
253                         }
254                 }
255
256                 public PtrHashtable ()
257                 {
258                         comparer = PtrComparer.Instance;
259                 }
260         }
261
262         /*
263          * Hashtable whose keys are character arrays with the same length
264          */
265         class CharArrayHashtable : Hashtable {
266                 sealed class ArrComparer : IComparer {
267                         private int len;
268
269                         public ArrComparer (int len) {
270                                 this.len = len;
271                         }
272
273                         public int Compare (object x, object y)
274                         {
275                                 char[] a = (char[])x;
276                                 char[] b = (char[])y;
277
278                                 for (int i = 0; i < len; ++i)
279                                         if (a [i] != b [i])
280                                                 return 1;
281                                 return 0;
282                         }
283                 }
284
285                 private int len;
286
287                 protected override int GetHash (Object key)
288                 {
289                         char[] arr = (char[])key;
290                         int h = 0;
291
292                         for (int i = 0; i < len; ++i)
293                                 h = (h << 5) - h + arr [i];
294
295                         return h;
296                 }
297
298                 public CharArrayHashtable (int len)
299                 {
300                         this.len = len;
301                         comparer = new ArrComparer (len);
302                 }
303         }
304
305         struct Pair {
306                 public object First;
307                 public object Second;
308
309                 public Pair (object f, object s)
310                 {
311                         First = f;
312                         Second = s;
313                 }
314         }
315
316         /// <summary>
317         ///   This is a wrapper around StreamReader which is seekable backwards
318         ///   within a window of around 2048 chars.
319         /// </summary>
320         public class SeekableStreamReader
321         {
322                 public SeekableStreamReader (StreamReader reader)
323                 {
324                         this.reader = reader;
325                         this.buffer = new char [AverageReadLength * 3];
326
327                         // Let the StreamWriter autodetect the encoder
328                         reader.Peek ();
329                 }
330
331                 public SeekableStreamReader (Stream stream, Encoding encoding)
332                         : this (new StreamReader (stream, encoding, true))
333                 { }
334
335                 StreamReader reader;
336
337                 private const int AverageReadLength = 1024;
338
339                 char[] buffer;
340                 int buffer_start;       // in chars
341                 int char_count;         // count buffer[] valid characters
342                 int pos;                // index into buffer[]
343
344                 /// <remarks>
345                 ///   This value corresponds to the current position in a stream of characters.
346                 ///   The StreamReader hides its manipulation of the underlying byte stream and all
347                 ///   character set/decoding issues.  Thus, we cannot use this position to guess at
348                 ///   the corresponding position in the underlying byte stream even though there is
349                 ///   a correlation between them.
350                 /// </remarks>
351                 public int Position {
352                         get { return buffer_start + pos; }
353
354                         set {
355                                 if (value < buffer_start || value > buffer_start + char_count)
356                                         throw new InternalErrorException ("can't seek that far back: " + (pos - value));
357                                 pos = value - buffer_start;
358                         }
359                 }
360
361                 private bool ReadBuffer ()
362                 {
363                         int slack = buffer.Length - char_count;
364                         if (slack <= AverageReadLength / 2) {
365                                 // shift the buffer to make room for AverageReadLength number of characters
366                                 int shift = AverageReadLength - slack;
367                                 Array.Copy (buffer, shift, buffer, 0, char_count - shift);
368                                 pos -= shift;
369                                 char_count -= shift;
370                                 buffer_start += shift;
371                                 slack += shift;         // slack == AverageReadLength
372                         }
373
374                         int chars_read = reader.Read (buffer, char_count, slack);
375                         char_count += chars_read;
376
377                         return pos < char_count;
378                 }
379
380                 public int Peek ()
381                 {
382                         if ((pos >= char_count) && !ReadBuffer ())
383                                 return -1;
384
385                         return buffer [pos];
386                 }
387
388                 public int Read ()
389                 {
390                         if ((pos >= char_count) && !ReadBuffer ())
391                                 return -1;
392
393                         return buffer [pos++];
394                 }
395         }
396
397         public class DoubleHash {
398                 const int DEFAULT_INITIAL_BUCKETS = 100;
399
400                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
401
402                 public DoubleHash (int size)
403                 {
404                         count = size;
405                         buckets = new Entry [size];
406                 }
407
408                 int count;
409                 Entry [] buckets;
410                 int size = 0;
411
412                 class Entry {
413                         public object key1;
414                         public object key2;
415                         public int hash;
416                         public object value;
417                         public Entry next;
418
419                         public Entry (object key1, object key2, int hash, object value, Entry next)
420                         {
421                                 this.key1 = key1;
422                                 this.key2 = key2;
423                                 this.hash = hash;
424                                 this.next = next;
425                                 this.value = value;
426                         }
427                 }
428
429                 public bool Lookup (object a, object b, out object res)
430                 {
431                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
432
433                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
434                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
435                                         res = e.value;
436                                         return true;
437                                 }
438                         }
439                         res = null;
440                         return false;
441                 }
442
443                 public void Insert (object a, object b, object value)
444                 {
445                         // Is it an existing one?
446
447                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
448
449                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
450                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
451                                         e.value = value;
452                         }
453
454                         int bucket = h % count;
455                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
456
457                         // Grow whenever we double in size
458                         if (size++ == count) {
459                                 count <<= 1;
460                                 count ++;
461
462                                 Entry [] newBuckets = new Entry [count];
463                                 foreach (Entry root in buckets) {
464                                         Entry e = root;
465                                         while (e != null) {
466                                                 int newLoc = e.hash % count;
467                                                 Entry n = e.next;
468                                                 e.next = newBuckets [newLoc];
469                                                 newBuckets [newLoc] = e;
470                                                 e = n;
471                                         }
472                                 }
473
474                                 buckets = newBuckets;
475                         }
476                 }
477         }
478 }