In mcs:
[mono.git] / mcs / gmcs / 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
148                 public Parameter.Modifier ParameterModifier (int pos)
149                 {
150                         if (last_arg_is_params && pos >= pi.Length - 1)
151                                         return Parameter.Modifier.PARAMS;
152                         else if (is_varargs && pos >= pi.Length)
153                                 return Parameter.Modifier.ARGLIST;
154                         
155                         if (gpd != null)
156                                 return gpd.ParameterModifier (pos);
157
158                         Type t = pi [pos].ParameterType;
159                         if (t.IsByRef){
160                                 if ((pi [pos].Attributes & (ParameterAttributes.Out|ParameterAttributes.In)) == ParameterAttributes.Out)
161                                         return Parameter.Modifier.OUT;
162                                 else
163                                         return Parameter.Modifier.REF;
164                         }
165                         
166                         return Parameter.Modifier.NONE;
167                 }
168
169                 public int Count {
170                         get {
171                                 return is_varargs ? pi.Length + 1 : pi.Length;
172                         }
173                 }
174
175                 public bool HasParams {
176                         get {
177                                 return this.last_arg_is_params;
178                         }
179                 }
180
181                 public Type[] Types {
182                         get {
183                                 return types;
184                         }
185                 }               
186         }
187
188         public class ReflectionConstraints : GenericConstraints
189         {
190                 GenericParameterAttributes attrs;
191                 Type base_type;
192                 Type class_constraint;
193                 Type[] iface_constraints;
194                 string name;
195
196                 public static GenericConstraints GetConstraints (Type t)
197                 {
198                         Type [] constraints = t.GetGenericParameterConstraints ();
199                         GenericParameterAttributes attrs = t.GenericParameterAttributes;
200                         if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
201                                 return null;
202                         return new ReflectionConstraints (t.Name, constraints, attrs);
203                 }
204
205                 private ReflectionConstraints (string name, Type [] constraints, GenericParameterAttributes attrs)
206                 {
207                         this.name = name;
208                         this.attrs = attrs;
209
210                         if ((constraints.Length > 0) && !constraints [0].IsInterface) {
211                                 class_constraint = constraints [0];
212                                 iface_constraints = new Type [constraints.Length - 1];
213                                 Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
214                         } else
215                                 iface_constraints = constraints;
216
217                         if (HasValueTypeConstraint)
218                                 base_type = TypeManager.value_type;
219                         else if (class_constraint != null)
220                                 base_type = class_constraint;
221                         else
222                                 base_type = TypeManager.object_type;
223                 }
224
225                 public override string TypeParameter {
226                         get { return name; }
227                 }
228
229                 public override GenericParameterAttributes Attributes {
230                         get { return attrs; }
231                 }
232
233                 public override Type ClassConstraint {
234                         get { return class_constraint; }
235                 }
236
237                 public override Type EffectiveBaseClass {
238                         get { return base_type; }
239                 }
240
241                 public override Type[] InterfaceConstraints {
242                         get { return iface_constraints; }
243                 }
244         }
245
246         class PtrHashtable : Hashtable {
247                 sealed class PtrComparer : IComparer {
248                         private PtrComparer () {}
249                         
250                         public static PtrComparer Instance = new PtrComparer ();
251                         
252                         public int Compare (object x, object y)
253                         {
254                                 if (x == y)
255                                         return 0;
256                                 else
257                                         return 1;
258                         }
259                 }
260                 
261                 public PtrHashtable ()
262                 {
263                         comparer = PtrComparer.Instance;
264                 }
265         }
266
267         /*
268          * Hashtable whose keys are character arrays with the same length
269          */
270         class CharArrayHashtable : Hashtable {
271                 sealed class ArrComparer : IComparer {
272                         private int len;
273
274                         public ArrComparer (int len) {
275                                 this.len = len;
276                         }
277
278                         public int Compare (object x, object y)
279                         {
280                                 char[] a = (char[])x;
281                                 char[] b = (char[])y;
282
283                                 for (int i = 0; i < len; ++i)
284                                         if (a [i] != b [i])
285                                                 return 1;
286                                 return 0;
287                         }
288                 }
289
290                 private int len;
291
292                 protected override int GetHash (Object key)
293                 {
294                         char[] arr = (char[])key;
295                         int h = 0;
296
297                         for (int i = 0; i < len; ++i)
298                                 h = (h << 5) - h + arr [i];
299
300                         return h;
301                 }
302
303                 public CharArrayHashtable (int len)
304                 {
305                         this.len = len;
306                         comparer = new ArrComparer (len);
307                 }
308         }                       
309
310         struct Pair {
311                 public object First;
312                 public object Second;
313                 
314                 public Pair (object f, object s)
315                 {
316                         First = f;
317                         Second = s;
318                 }
319         }
320
321         /// <summary>
322         ///   This is a wrapper around StreamReader which is seekable backwards
323         ///   within a window of around 2048 chars.
324         /// </summary>
325         public class SeekableStreamReader
326         {
327                 public SeekableStreamReader (StreamReader reader)
328                 {
329                         this.reader = reader;
330                         this.buffer = new char [AverageReadLength * 3];
331
332                         // Let the StreamWriter autodetect the encoder
333                         reader.Peek ();
334                 }
335
336                 public SeekableStreamReader (Stream stream, Encoding encoding)
337                         : this (new StreamReader (stream, encoding, true))
338                 { }
339
340                 StreamReader reader;
341
342                 private const int AverageReadLength = 1024;
343
344                 char[] buffer;
345                 int buffer_start;       // in chars
346                 int char_count;         // count buffer[] valid characters
347                 int pos;                // index into buffer[]
348
349                 /// <remarks>
350                 ///   This value corresponds to the current position in a stream of characters.
351                 ///   The StreamReader hides its manipulation of the underlying byte stream and all
352                 ///   character set/decoding issues.  Thus, we cannot use this position to guess at
353                 ///   the corresponding position in the underlying byte stream even though there is
354                 ///   a correlation between them.
355                 /// </remarks>
356                 public int Position {
357                         get { return buffer_start + pos; }
358
359                         set {
360                                 if (value < buffer_start || value > buffer_start + char_count)
361                                         throw new InternalErrorException ("can't seek that far back: " + (pos - value));
362                                 pos = value - buffer_start;
363                         }
364                 }
365
366                 private bool ReadBuffer ()
367                 {
368                         int slack = buffer.Length - char_count;
369                         if (slack <= AverageReadLength / 2) {
370                                 // shift the buffer to make room for AverageReadLength number of characters
371                                 int shift = AverageReadLength - slack;
372                                 Array.Copy (buffer, shift, buffer, 0, char_count - shift);
373                                 pos -= shift;
374                                 char_count -= shift;
375                                 buffer_start += shift;
376                                 slack += shift;         // slack == AverageReadLength
377                         }
378
379                         int chars_read = reader.Read (buffer, char_count, slack);
380                         char_count += chars_read;
381
382                         return pos < char_count;
383                 }
384
385                 public int Peek ()
386                 {
387                         if ((pos >= char_count) && !ReadBuffer ())
388                                 return -1;
389
390                         return buffer [pos];
391                 }
392
393                 public int Read ()
394                 {
395                         if ((pos >= char_count) && !ReadBuffer ())
396                                 return -1;
397
398                         return buffer [pos++];
399                 }
400         }
401
402         public class DoubleHash {
403                 const int DEFAULT_INITIAL_BUCKETS = 100;
404                 
405                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
406                 
407                 public DoubleHash (int size)
408                 {
409                         count = size;
410                         buckets = new Entry [size];
411                 }
412                 
413                 int count;
414                 Entry [] buckets;
415                 int size = 0;
416                 
417                 class Entry {
418                         public object key1;
419                         public object key2;
420                         public int hash;
421                         public object value;
422                         public Entry next;
423         
424                         public Entry (object key1, object key2, int hash, object value, Entry next)
425                         {
426                                 this.key1 = key1;
427                                 this.key2 = key2;
428                                 this.hash = hash;
429                                 this.next = next;
430                                 this.value = value;
431                         }
432                 }
433
434                 public bool Lookup (object a, object b, out object res)
435                 {
436                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
437                         
438                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
439                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
440                                         res = e.value;
441                                         return true;
442                                 }
443                         }
444                         res = null;
445                         return false;
446                 }
447
448                 public void Insert (object a, object b, object value)
449                 {
450                         // Is it an existing one?
451                 
452                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
453                         
454                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
455                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
456                                         e.value = value;
457                         }
458                         
459                         int bucket = h % count;
460                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
461                         
462                         // Grow whenever we double in size
463                         if (size++ == count) {
464                                 count <<= 1;
465                                 count ++;
466                                 
467                                 Entry [] newBuckets = new Entry [count];
468                                 foreach (Entry root in buckets) {
469                                         Entry e = root;
470                                         while (e != null) {
471                                                 int newLoc = e.hash % count;
472                                                 Entry n = e.next;
473                                                 e.next = newBuckets [newLoc];
474                                                 newBuckets [newLoc] = e;
475                                                 e = n;
476                                         }
477                                 }
478
479                                 buckets = newBuckets;
480                         }
481                 }
482         }
483 }