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