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