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