2004-12-08 Miguel de Icaza <miguel@ximian.com>
[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                 int  Count { get; }
24                 bool HasParams { get; }
25                 string ParameterName (int pos);
26                 string ParameterDesc (int pos);
27                 Parameter.Modifier ParameterModifier (int pos);
28         }
29
30         public class ReflectionParameters : ParameterData {
31                 ParameterInfo [] pi;
32                 bool last_arg_is_params = false;
33                 bool is_varargs = false;
34                 
35                 public ReflectionParameters (MethodBase mb)
36                 {
37                         object [] attrs;
38
39                         ParameterInfo [] pi = mb.GetParameters ();
40                         is_varargs = (mb.CallingConvention & CallingConventions.VarArgs) != 0;
41                         
42                         this.pi = pi;
43                         int count = pi.Length-1;
44
45                         if (count >= 0) {
46                                 attrs = pi [count].GetCustomAttributes (TypeManager.param_array_type, true);
47
48                                 if (attrs == null)
49                                         return;
50                                 
51                                 if (attrs.Length == 0)
52                                         return;
53
54                                 last_arg_is_params = true;
55                         }
56                 }
57                        
58                 public Type ParameterType (int pos)
59                 {
60                         if (last_arg_is_params && pos >= pi.Length - 1)
61                                 return pi [pi.Length - 1].ParameterType;
62                         else if (is_varargs && pos >= pi.Length)
63                                 return TypeManager.runtime_argument_handle_type;
64                         else {
65                                 Type t = pi [pos].ParameterType;
66
67                                 return t;
68                         }
69                 }
70
71                 public string ParameterName (int pos)
72                 {
73                         if (last_arg_is_params && pos >= pi.Length - 1)
74                                 return pi [pi.Length - 1].Name;
75                         else if (is_varargs && pos >= pi.Length)
76                                 return "__arglist";
77                         else 
78                                 return pi [pos].Name;
79                 }
80
81                 public string ParameterDesc (int pos)
82                 {
83                         if (is_varargs && pos >= pi.Length)
84                                 return "";                      
85
86                         StringBuilder sb = new StringBuilder ();
87
88                         if (pi [pos].IsIn)
89                                 sb.Append ("in ");
90
91                         Type partype = ParameterType (pos);
92                         if (partype.IsByRef){
93                                 partype = TypeManager.GetElementType (partype);
94                                 if (pi [pos].IsOut)
95                                         sb.Append ("out ");
96                                 else
97                                         sb.Append ("ref ");
98                         } 
99
100                         if (pos >= pi.Length - 1 && last_arg_is_params)
101                                 sb.Append ("params ");
102                         
103                         sb.Append (TypeManager.CSharpName (partype));
104
105                         return sb.ToString ();
106                         
107                 }
108
109                 public Parameter.Modifier ParameterModifier (int pos)
110                 {
111                         int len = pi.Length;
112
113                         if (last_arg_is_params && pos >= pi.Length - 1)
114                                 return Parameter.Modifier.PARAMS;
115                         else if (is_varargs && pos >= pi.Length)
116                                 return Parameter.Modifier.ARGLIST;
117                         
118                         Type t = pi [pos].ParameterType;
119                         if (t.IsByRef){
120                                 if ((pi [pos].Attributes & ParameterAttributes.Out) != 0)
121                                         return Parameter.Modifier.ISBYREF | Parameter.Modifier.OUT;
122                                 else
123                                         return Parameter.Modifier.ISBYREF | Parameter.Modifier.REF;
124                         }
125                         
126                         return Parameter.Modifier.NONE;
127                 }
128
129                 public int Count {
130                         get {
131                                 return is_varargs ? pi.Length + 1 : pi.Length;
132                         }
133                 }
134
135                 public bool HasParams {
136                         get {
137                                 return this.last_arg_is_params;
138                         }
139                 }
140                 
141         }
142
143         public class InternalParameters : ParameterData {
144                 Type [] param_types;
145                 bool has_varargs;
146                 int count;
147
148                 public readonly Parameters Parameters;
149                 
150                 public InternalParameters (Type [] param_types, Parameters parameters)
151                 {
152                         this.param_types = param_types;
153                         this.Parameters = parameters;
154
155                         has_varargs = parameters.HasArglist;
156
157                         if (param_types == null)
158                                 count = 0;
159                         else
160                                 count = param_types.Length;
161                 }
162
163                 public int Count {
164                         get {
165                                 return has_varargs ? count + 1 : count;
166                         }
167                 }
168
169                 public bool HasParams {
170                         get {
171                                 return Parameters.ArrayParameter != null;
172                         }
173                 }
174
175                 Parameter GetParameter (int pos)
176                 {
177                         Parameter [] fixed_pars = Parameters.FixedParameters;
178                         if (fixed_pars != null){
179                                 int len = fixed_pars.Length;
180                                 if (pos < len)
181                                         return Parameters.FixedParameters [pos];
182                         }
183
184                         return Parameters.ArrayParameter;
185                 }
186
187                 public Type ParameterType (int pos)
188                 {
189                         if (has_varargs && pos >= count)
190                                 return TypeManager.runtime_argument_handle_type;
191
192                         if (param_types == null)
193                                 return null;
194
195                         return GetParameter (pos).ExternalType ();
196                 }
197
198
199                 public string ParameterName (int pos)
200                 {
201                         if (has_varargs && pos >= count)
202                                 return "__arglist";
203
204                         return GetParameter (pos).Name;
205                 }
206
207                 public string ParameterDesc (int pos)
208                 {
209                         if (has_varargs && pos >= count)
210                                 return "__arglist";
211
212                         string tmp = String.Empty;
213                         Parameter p = GetParameter (pos);
214
215                         //
216                         // We need to and for REF/OUT, because if either is set the
217                         // extra flag ISBYREF will be set as well
218                         //
219                         if ((p.ModFlags & Parameter.Modifier.REF) != 0)
220                                 tmp = "ref ";
221                         else if ((p.ModFlags & Parameter.Modifier.OUT) != 0)
222                                 tmp = "out ";
223                         else if (p.ModFlags == Parameter.Modifier.PARAMS)
224                                 tmp = "params ";
225
226                         Type t = ParameterType (pos);
227
228                         return tmp + TypeManager.CSharpName (t);
229                 }
230
231                 public Parameter.Modifier ParameterModifier (int pos)
232                 {
233                         if (has_varargs && pos >= count)
234                                 return Parameter.Modifier.ARGLIST;
235
236                         Parameter.Modifier mod = GetParameter (pos).ModFlags;
237
238                         if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
239                                 mod |= Parameter.Modifier.ISBYREF;
240
241                         return mod;
242                 }
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.
323         /// </summary>
324         public class SeekableStreamReader
325         {
326                 public SeekableStreamReader (StreamReader reader)
327                 {
328                         this.reader = reader;
329                         this.buffer = new char [DefaultCacheSize];
330                         
331                         // Compute the preamble size
332                         
333                         // Let the StreamWriter autodetect the encoder
334                         reader.Peek ();
335                         
336                         reader.BaseStream.Position = 0;
337                         Encoding enc = reader.CurrentEncoding;
338                         // First of all, get at least a char
339                         
340                         byte[] auxb = new byte [50];
341                         int num_bytes = 0;
342                         int num_chars = 0;
343                         int br = 0;
344                         do {
345                                 br = reader.BaseStream.Read (auxb, num_bytes, auxb.Length - num_bytes);
346                                 num_bytes += br;
347                                 num_chars = enc.GetCharCount (auxb, 0, num_bytes);
348                         }
349                         while (num_chars == 0 && br > 0);
350                         
351                         if (num_chars != 0)
352                         {
353                                 // Now, check which bytes at the beginning have no effect in the
354                                 // char count
355                                 
356                                 int p = 0;
357                                 while (enc.GetCharCount (auxb, p, num_bytes-p) >= num_chars)
358                                         p++;
359                                 
360                                 preamble_size = p - 1;
361                                 reader.BaseStream.Position = 0;
362                                 reader.DiscardBufferedData ();
363                                 
364                                 buffer_start = preamble_size;
365                         }
366                 }
367
368                 public SeekableStreamReader (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
369                         : this (new StreamReader (stream, encoding, detect_encoding_from_bytemarks))
370                 { }
371
372                 StreamReader reader;
373
374                 private const int DefaultCacheSize = 1024;
375
376                 char[] buffer;
377                 int buffer_start;       // in bytes
378                 int buffer_size;        // in bytes
379                 int char_count;         // count buffer[] valid characters
380                 int pos;                // index into buffer[]
381                 int preamble_size;
382
383                 /// <remarks>
384                 ///   The difference to the StreamReader's BaseStream.Position is that this one is reliable; ie. it
385                 //    always reports the correct position and if it's modified, it also takes care of the buffered data.
386                 /// </remarks>
387                 public int Position {
388                         get {
389                                 return buffer_start + reader.CurrentEncoding.GetByteCount (buffer, 0, pos);
390                         }
391
392                         set {
393                                 // This one is easy: we're modifying the position within our current
394                                 // buffer.
395                                 if ((value >= buffer_start) && (value < buffer_start + buffer_size)) {
396                                         int byte_offset = value - buffer_start;
397                                         pos = byte_offset;
398                                         // encoded characters can take more than 1 byte length
399                                         while (reader.CurrentEncoding.GetByteCount (buffer, 0, pos) > byte_offset)
400                                                 pos--;
401                                         
402                                         return;
403                                 }
404                                 
405                                 if (value == 0) // Skip preamble
406                                         value = preamble_size;
407
408                                 // Ok, now we need to seek.
409                                 reader.DiscardBufferedData ();
410                                 reader.BaseStream.Position = buffer_start = value;
411                                 char_count = buffer_size = pos = 0;
412                         }
413                 }
414
415                 private bool ReadBuffer ()
416                 {
417                         pos = 0;
418                         buffer_start += buffer_size;
419                         char_count = reader.Read (buffer, 0, buffer.Length);
420                         buffer_size = reader.CurrentEncoding.GetByteCount (buffer, 0, char_count);
421                         return buffer_size > 0;
422                 }
423
424                 public int Peek ()
425                 {
426                         if ((pos >= char_count) && !ReadBuffer ())
427                                 return -1;
428
429                         return buffer [pos];
430                 }
431
432                 public int Read ()
433                 {
434                         if ((pos >= char_count) && !ReadBuffer ())
435                                 return -1;
436
437                         return buffer [pos++];
438                 }
439         }
440
441         public class DoubleHash {
442                 const int DEFAULT_INITIAL_BUCKETS = 100;
443                 
444                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
445                 
446                 public DoubleHash (int size)
447                 {
448                         count = size;
449                         buckets = new Entry [size];
450                 }
451                 
452                 int count;
453                 Entry [] buckets;
454                 int size = 0;
455                 
456                 class Entry {
457                         public object key1;
458                         public object key2;
459                         public int hash;
460                         public object value;
461                         public Entry next;
462         
463                         public Entry (object key1, object key2, int hash, object value, Entry next)
464                         {
465                                 this.key1 = key1;
466                                 this.key2 = key2;
467                                 this.hash = hash;
468                                 this.next = next;
469                                 this.value = value;
470                         }
471                 }
472
473                 public bool Lookup (object a, object b, out object res)
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                                         res = e.value;
480                                         return true;
481                                 }
482                         }
483                         res = null;
484                         return false;
485                 }
486
487                 public void Insert (object a, object b, object value)
488                 {
489                         // Is it an existing one?
490                 
491                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
492                         
493                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
494                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
495                                         e.value = value;
496                         }
497                         
498                         int bucket = h % count;
499                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
500                         
501                         // Grow whenever we double in size
502                         if (size++ == count) {
503                                 count <<= 1;
504                                 count ++;
505                                 
506                                 Entry [] newBuckets = new Entry [count];
507                                 foreach (Entry root in buckets) {
508                                         Entry e = root;
509                                         while (e != null) {
510                                                 int newLoc = e.hash % count;
511                                                 Entry n = e.next;
512                                                 e.next = newBuckets [newLoc];
513                                                 newBuckets [newLoc] = e;
514                                                 e = n;
515                                         }
516                                 }
517
518                                 buckets = newBuckets;
519                         }
520                 }
521         }
522 }