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