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