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