Revert my patch to constants, they broke corlib and System
[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
149                 public InternalParameters (DeclSpace ds, Parameters parameters)
150                         : this (parameters.GetParameterInfo (ds), parameters)
151                 {
152                         has_varargs = parameters.HasArglist;
153
154                         if (param_types == null)
155                                 count = 0;
156                         else
157                                 count = param_types.Length;
158                 }
159
160                 public int Count {
161                         get {
162                                 return has_varargs ? count + 1 : count;
163                         }
164                 }
165
166                 Parameter GetParameter (int pos)
167                 {
168                         Parameter [] fixed_pars = Parameters.FixedParameters;
169                         if (fixed_pars != null){
170                                 int len = fixed_pars.Length;
171                                 if (pos < len)
172                                         return Parameters.FixedParameters [pos];
173                         }
174
175                         return Parameters.ArrayParameter;
176                 }
177
178                 public Type ParameterType (int pos)
179                 {
180                         if (has_varargs && pos >= count)
181                                 return TypeManager.runtime_argument_handle_type;
182
183                         if (param_types == null)
184                                 return null;
185
186                         return GetParameter (pos).ExternalType ();
187                 }
188
189
190                 public string ParameterName (int pos)
191                 {
192                         if (has_varargs && pos >= count)
193                                 return "__arglist";
194
195                         return GetParameter (pos).Name;
196                 }
197
198                 public string ParameterDesc (int pos)
199                 {
200                         if (has_varargs && pos >= count)
201                                 return "__arglist";
202
203                         string tmp = String.Empty;
204                         Parameter p = GetParameter (pos);
205
206                         //
207                         // We need to and for REF/OUT, because if either is set the
208                         // extra flag ISBYREF will be set as well
209                         //
210                         if ((p.ModFlags & Parameter.Modifier.REF) != 0)
211                                 tmp = "ref ";
212                         else if ((p.ModFlags & Parameter.Modifier.OUT) != 0)
213                                 tmp = "out ";
214                         else if (p.ModFlags == Parameter.Modifier.PARAMS)
215                                 tmp = "params ";
216
217                         Type t = ParameterType (pos);
218
219                         return tmp + TypeManager.CSharpName (t);
220                 }
221
222                 public Parameter.Modifier ParameterModifier (int pos)
223                 {
224                         if (has_varargs && pos >= count)
225                                 return Parameter.Modifier.ARGLIST;
226
227                         Parameter.Modifier mod = GetParameter (pos).ModFlags;
228
229                         if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
230                                 mod |= Parameter.Modifier.ISBYREF;
231
232                         return mod;
233                 }
234                 
235         }
236
237         class PtrHashtable : Hashtable {
238                 sealed class PtrComparer : IComparer {
239                         private PtrComparer () {}
240                         
241                         public static PtrComparer Instance = new PtrComparer ();
242                         
243                         public int Compare (object x, object y)
244                         {
245                                 if (x == y)
246                                         return 0;
247                                 else
248                                         return 1;
249                         }
250                 }
251                 
252                 public PtrHashtable ()
253                 {
254                         comparer = PtrComparer.Instance;
255                 }
256         }
257
258         /*
259          * Hashtable whose keys are character arrays with the same length
260          */
261         class CharArrayHashtable : Hashtable {
262                 sealed class ArrComparer : IComparer {
263                         private int len;
264
265                         public ArrComparer (int len) {
266                                 this.len = len;
267                         }
268
269                         public int Compare (object x, object y)
270                         {
271                                 char[] a = (char[])x;
272                                 char[] b = (char[])y;
273
274                                 for (int i = 0; i < len; ++i)
275                                         if (a [i] != b [i])
276                                                 return 1;
277                                 return 0;
278                         }
279                 }
280
281                 private int len;
282
283                 protected override int GetHash (Object key)
284                 {
285                         char[] arr = (char[])key;
286                         int h = 0;
287
288                         for (int i = 0; i < len; ++i)
289                                 h = (h << 5) - h + arr [i];
290
291                         return h;
292                 }
293
294                 public CharArrayHashtable (int len)
295                 {
296                         this.len = len;
297                         comparer = new ArrComparer (len);
298                 }
299         }                       
300
301         struct Pair {
302                 public object First;
303                 public object Second;
304                 
305                 public Pair (object f, object s)
306                 {
307                         First = f;
308                         Second = s;
309                 }
310         }
311
312         /// <summary>
313         ///   This is a wrapper around StreamReader which is seekable.
314         /// </summary>
315         public class SeekableStreamReader
316         {
317                 public SeekableStreamReader (StreamReader reader)
318                 {
319                         this.reader = reader;
320                         this.buffer = new char [DefaultCacheSize];
321                         
322                         // Compute the preamble size
323                         
324                         // Let the StreamWriter autodetect the encoder
325                         reader.Peek ();
326                         
327                         reader.BaseStream.Position = 0;
328                         Encoding enc = reader.CurrentEncoding;
329                         // First of all, get at least a char
330                         
331                         byte[] auxb = new byte [50];
332                         int num_bytes = 0;
333                         int num_chars = 0;
334                         int br = 0;
335                         do {
336                                 br = reader.BaseStream.Read (auxb, num_bytes, auxb.Length - num_bytes);
337                                 num_bytes += br;
338                                 num_chars = enc.GetCharCount (auxb, 0, num_bytes);
339                         }
340                         while (num_chars == 0 && br > 0);
341                         
342                         if (num_chars != 0)
343                         {
344                                 // Now, check which bytes at the beginning have no effect in the
345                                 // char count
346                                 
347                                 int p = 0;
348                                 while (enc.GetCharCount (auxb, p, num_bytes-p) >= num_chars)
349                                         p++;
350                                 
351                                 preamble_size = p - 1;
352                                 reader.BaseStream.Position = 0;
353                                 reader.DiscardBufferedData ();
354                                 
355                                 buffer_start = preamble_size;
356                         }
357                 }
358
359                 public SeekableStreamReader (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
360                         : this (new StreamReader (stream, encoding, detect_encoding_from_bytemarks))
361                 { }
362
363                 StreamReader reader;
364
365                 private const int DefaultCacheSize = 1024;
366
367                 char[] buffer;
368                 int buffer_start;       // in bytes
369                 int buffer_size;        // in bytes
370                 int char_count;         // count buffer[] valid characters
371                 int pos;                // index into buffer[]
372                 int preamble_size;
373
374                 /// <remarks>
375                 ///   The difference to the StreamReader's BaseStream.Position is that this one is reliable; ie. it
376                 //    always reports the correct position and if it's modified, it also takes care of the buffered data.
377                 /// </remarks>
378                 public int Position {
379                         get {
380                                 return buffer_start + reader.CurrentEncoding.GetByteCount (buffer, 0, pos);
381                         }
382
383                         set {
384                                 // This one is easy: we're modifying the position within our current
385                                 // buffer.
386                                 if ((value >= buffer_start) && (value < buffer_start + buffer_size)) {
387                                         int byte_offset = value - buffer_start;
388                                         pos = byte_offset;
389                                         // encoded characters can take more than 1 byte length
390                                         while (reader.CurrentEncoding.GetByteCount (buffer, 0, pos) > byte_offset)
391                                                 pos--;
392                                         
393                                         return;
394                                 }
395                                 
396                                 if (value == 0) // Skip preamble
397                                         value = preamble_size;
398
399                                 // Ok, now we need to seek.
400                                 reader.DiscardBufferedData ();
401                                 reader.BaseStream.Position = buffer_start = value;
402                                 char_count = buffer_size = pos = 0;
403                         }
404                 }
405
406                 private bool ReadBuffer ()
407                 {
408                         pos = 0;
409                         buffer_start += buffer_size;
410                         char_count = reader.Read (buffer, 0, buffer.Length);
411                         buffer_size = reader.CurrentEncoding.GetByteCount (buffer, 0, char_count);
412                         return buffer_size > 0;
413                 }
414
415                 public int Peek ()
416                 {
417                         if ((pos >= char_count) && !ReadBuffer ())
418                                 return -1;
419
420                         return buffer [pos];
421                 }
422
423                 public int Read ()
424                 {
425                         if ((pos >= char_count) && !ReadBuffer ())
426                                 return -1;
427
428                         return buffer [pos++];
429                 }
430         }
431
432         public class DoubleHash {
433                 const int DEFAULT_INITIAL_BUCKETS = 100;
434                 
435                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
436                 
437                 public DoubleHash (int size)
438                 {
439                         count = size;
440                         buckets = new Entry [size];
441                 }
442                 
443                 int count;
444                 Entry [] buckets;
445                 int size = 0;
446                 
447                 class Entry {
448                         public object key1;
449                         public object key2;
450                         public int hash;
451                         public object value;
452                         public Entry next;
453         
454                         public Entry (object key1, object key2, int hash, object value, Entry next)
455                         {
456                                 this.key1 = key1;
457                                 this.key2 = key2;
458                                 this.hash = hash;
459                                 this.next = next;
460                                 this.value = value;
461                         }
462                 }
463
464                 public bool Lookup (object a, object b, out object res)
465                 {
466                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
467                         
468                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
469                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
470                                         res = e.value;
471                                         return true;
472                                 }
473                         }
474                         res = null;
475                         return false;
476                 }
477
478                 public void Insert (object a, object b, object value)
479                 {
480                         // Is it an existing one?
481                 
482                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
483                         
484                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
485                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
486                                         e.value = value;
487                         }
488                         
489                         int bucket = h % count;
490                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
491                         
492                         // Grow whenever we double in size
493                         if (size++ == count) {
494                                 count <<= 1;
495                                 count ++;
496                                 
497                                 Entry [] newBuckets = new Entry [count];
498                                 foreach (Entry root in buckets) {
499                                         Entry e = root;
500                                         while (e != null) {
501                                                 int newLoc = e.hash % count;
502                                                 Entry n = e.next;
503                                                 e.next = newBuckets [newLoc];
504                                                 newBuckets [newLoc] = e;
505                                                 e = n;
506                                         }
507                                 }
508
509                                 buckets = newBuckets;
510                         }
511                 }
512         }
513 }