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