*** Merged revisions from mcs: 52077, 52086, 52089
[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                 string GetSignatureForError ();
30         }
31
32         public class ReflectionParameters : ParameterData {
33                 ParameterInfo [] pi;
34                 Type[] type_params;
35                 bool last_arg_is_params = false;
36                 bool is_varargs = false;
37                 ParameterData gpd;
38
39                 public ReflectionParameters (MethodBase mb)
40                 {
41                         object [] attrs;
42
43                         ParameterInfo [] pi = mb.GetParameters ();
44                         is_varargs = (mb.CallingConvention & CallingConventions.VarArgs) != 0;
45
46                         this.pi = pi;
47                         int count = pi.Length-1;
48
49                         if (count < 0)
50                                 return;
51
52                         if (mb.Mono_IsInflatedMethod) {
53                                 MethodInfo generic = mb.GetGenericMethodDefinition ();
54                                 gpd = TypeManager.GetParameterData (generic);
55
56                                 last_arg_is_params = gpd.HasParams;
57                                 return;
58                         }
59
60                         if (mb.IsGenericMethodDefinition)
61                                 type_params = mb.GetGenericArguments ();
62
63                         attrs = pi [count].GetCustomAttributes (TypeManager.param_array_type, true);
64                         if (attrs == null)
65                                 return;
66
67                         if (attrs.Length == 0)
68                                 return;
69
70                         last_arg_is_params = true;
71                 }
72                 
73                 public string GetSignatureForError ()
74                 {
75                         StringBuilder sb = new StringBuilder ("(");
76                         for (int i = 0; i < pi.Length; ++i) {
77                                 if (i != 0)
78                                         sb.Append (", ");
79                                 sb.Append (ParameterDesc (i));
80                         }
81                         sb.Append (')');
82                         return sb.ToString ();
83                 }
84
85                 public Type ParameterType (int pos)
86                 {
87                         if (last_arg_is_params && pos >= pi.Length - 1)
88                                 return pi [pi.Length - 1].ParameterType;
89                         else if (is_varargs && pos >= pi.Length)
90                                 return TypeManager.runtime_argument_handle_type;
91                         else {
92                                 Type t = pi [pos].ParameterType;
93
94                                 return t;
95                         }
96                 }
97
98                 public GenericConstraints GenericConstraints (int pos)
99                 {
100                         if (gpd != null)
101                                 return gpd.GenericConstraints (pos);
102
103                         if (type_params == null)
104                                 return null;
105
106                         return new ReflectionConstraints (type_params [pos]);
107                 }
108
109                 public string ParameterName (int pos)
110                 {
111                         if (gpd != null)
112                                 return gpd.ParameterName (pos);
113
114                         if (last_arg_is_params && pos >= pi.Length - 1)
115                                 return pi [pi.Length - 1].Name;
116                         else if (is_varargs && pos >= pi.Length)
117                                 return "__arglist";
118                         else 
119                                 return pi [pos].Name;
120                 }
121
122                 public string ParameterDesc (int pos)
123                 {
124                         if (is_varargs && pos >= pi.Length)
125                                 return "";                      
126
127                         StringBuilder sb = new StringBuilder ();
128
129                         if (pi [pos].IsIn)
130                                 sb.Append ("in ");
131
132                         Type partype = ParameterType (pos);
133                         if (partype.IsByRef){
134                                 partype = TypeManager.GetElementType (partype);
135                                 if (pi [pos].IsOut)
136                                         sb.Append ("out ");
137                                 else
138                                         sb.Append ("ref ");
139                         } 
140
141                         if (pos >= pi.Length - 1 && last_arg_is_params)
142                                 sb.Append ("params ");
143                         
144                         sb.Append (TypeManager.CSharpName (partype).Replace ("&", ""));
145
146                         return sb.ToString ();
147                         
148                 }
149
150                 public Parameter.Modifier ParameterModifier (int pos)
151                 {
152                         if (last_arg_is_params && pos >= pi.Length - 1)
153                                         return Parameter.Modifier.PARAMS;
154                         else if (is_varargs && pos >= pi.Length)
155                                 return Parameter.Modifier.ARGLIST;
156                         
157                         if (gpd != null)
158                                 return gpd.ParameterModifier (pos);
159
160                         Type t = pi [pos].ParameterType;
161                         if (t.IsByRef){
162                                 if ((pi [pos].Attributes & (ParameterAttributes.Out|ParameterAttributes.In)) == ParameterAttributes.Out)
163                                         return Parameter.Modifier.ISBYREF | Parameter.Modifier.OUT;
164                                 else
165                                         return Parameter.Modifier.ISBYREF | Parameter.Modifier.REF;
166                         }
167                         
168                         return Parameter.Modifier.NONE;
169                 }
170
171                 public int Count {
172                         get {
173                                 return is_varargs ? pi.Length + 1 : pi.Length;
174                         }
175                 }
176
177                 public bool HasParams {
178                         get {
179                                 return this.last_arg_is_params;
180                         }
181                 }
182         }
183
184         public class InternalParameters : ParameterData {
185                 Type [] param_types;
186                 bool has_varargs;
187                 int count;
188
189                 public readonly Parameters Parameters;
190                 public readonly TypeParameter[] TypeParameters;
191                 
192                 public InternalParameters (Type [] param_types, Parameters parameters)
193                 {
194                         this.param_types = param_types;
195                         this.Parameters = parameters;
196
197                         has_varargs = parameters.HasArglist;
198
199                         if (param_types == null)
200                                 count = 0;
201                         else
202                                 count = param_types.Length;
203                 }
204
205                 public InternalParameters (Type [] param_types, Parameters parameters,
206                                            TypeParameter [] type_params)
207                         : this (param_types, parameters)
208                 {
209                         this.TypeParameters = type_params;
210                 }
211
212                 public int Count {
213                         get {
214                                 return has_varargs ? count + 1 : count;
215                         }
216                 }
217
218                 public bool HasParams {
219                         get {
220                                 return Parameters.ArrayParameter != null;
221                         }
222                 }
223
224                 Parameter GetParameter (int pos)
225                 {
226                         Parameter [] fixed_pars = Parameters.FixedParameters;
227                         if (fixed_pars != null){
228                                 int len = fixed_pars.Length;
229                                 if (pos < len)
230                                         return Parameters.FixedParameters [pos];
231                         }
232
233                         return Parameters.ArrayParameter;
234                 }
235
236                 public string GetSignatureForError ()
237                 {
238                         StringBuilder sb = new StringBuilder ("(");
239                         for (int i = 0; i < count; ++i) {
240                                 if (i != 0)
241                                         sb.Append (", ");
242                                 sb.Append (ParameterDesc (i));
243                         }
244                         sb.Append (')');
245                         return sb.ToString ();
246                 }
247
248                 public Type ParameterType (int pos)
249                 {
250                         if (has_varargs && pos >= count)
251                                 return TypeManager.runtime_argument_handle_type;
252
253                         if (param_types == null)
254                                 return null;
255
256                         return GetParameter (pos).ExternalType ();
257                 }
258
259                 public GenericConstraints GenericConstraints (int pos)
260                 {
261                         if (TypeParameters == null)
262                                 return null;
263
264                         return TypeParameters [pos].Constraints;
265                 }
266
267                 public string ParameterName (int pos)
268                 {
269                         if (has_varargs && pos >= count)
270                                 return "__arglist";
271
272                         return GetParameter (pos).Name;
273                 }
274
275                 public string ParameterDesc (int pos)
276                 {
277                         if (has_varargs && pos >= count)
278                                 return "__arglist";
279
280                         Type t = ParameterType (pos);
281                         return (ModifierDesc (pos) + " " + TypeManager.CSharpName (t).Replace ("&", "")).TrimStart ();
282                 }
283
284                 public string ModifierDesc (int pos)
285                 {
286                         Parameter p = GetParameter (pos);
287
288                         //
289                         // We need to and for REF/OUT, because if either is set the
290                         // extra flag ISBYREF will be set as well
291                         //
292                         if ((p.ModFlags & Parameter.Modifier.REF) != 0)
293                                 return "ref";
294                         if ((p.ModFlags & Parameter.Modifier.OUT) != 0)
295                                 return "out";
296                         if (p.ModFlags == Parameter.Modifier.PARAMS)
297                                 return "params";
298
299                         return "";
300                 }
301
302                 public Parameter.Modifier ParameterModifier (int pos)
303                 {
304                         if (has_varargs && pos >= count)
305                                 return Parameter.Modifier.ARGLIST;
306
307                         Parameter.Modifier mod = GetParameter (pos).ModFlags;
308
309                         if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
310                                 mod |= Parameter.Modifier.ISBYREF;
311
312                         return mod;
313                 }
314                 
315         }
316
317         public class ReflectionConstraints : GenericConstraints
318         {
319                 GenericParameterAttributes attrs;
320                 Type base_type;
321                 Type class_constraint;
322                 Type[] iface_constraints;
323                 string name;
324
325                 public ReflectionConstraints (Type t)
326                 {
327                         name = t.Name;
328                         Type[] constraints = t.GetGenericParameterConstraints ();
329                         if ((constraints.Length > 0) && !constraints [0].IsInterface) {
330                                 class_constraint = constraints [0];
331                                 iface_constraints = new Type [constraints.Length - 1];
332                                 Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
333                         } else
334                                 iface_constraints = constraints;
335                         attrs = t.GenericParameterAttributes;
336
337                         if (HasValueTypeConstraint)
338                                 base_type = TypeManager.value_type;
339                         else if (class_constraint != null)
340                                 base_type = class_constraint;
341                         else
342                                 base_type = TypeManager.object_type;
343                 }
344
345                 public override string TypeParameter {
346                         get { return name; }
347                 }
348
349                 public override GenericParameterAttributes Attributes {
350                         get { return attrs; }
351                 }
352
353                 public override Type ClassConstraint {
354                         get { return class_constraint; }
355                 }
356
357                 public override Type EffectiveBaseClass {
358                         get { return base_type; }
359                 }
360
361                 public override Type[] InterfaceConstraints {
362                         get { return iface_constraints; }
363                 }
364         }
365
366         class PtrHashtable : Hashtable {
367                 sealed class PtrComparer : IComparer {
368                         private PtrComparer () {}
369                         
370                         public static PtrComparer Instance = new PtrComparer ();
371                         
372                         public int Compare (object x, object y)
373                         {
374                                 if (x == y)
375                                         return 0;
376                                 else
377                                         return 1;
378                         }
379                 }
380                 
381                 public PtrHashtable ()
382                 {
383                         comparer = PtrComparer.Instance;
384                 }
385         }
386
387         /*
388          * Hashtable whose keys are character arrays with the same length
389          */
390         class CharArrayHashtable : Hashtable {
391                 sealed class ArrComparer : IComparer {
392                         private int len;
393
394                         public ArrComparer (int len) {
395                                 this.len = len;
396                         }
397
398                         public int Compare (object x, object y)
399                         {
400                                 char[] a = (char[])x;
401                                 char[] b = (char[])y;
402
403                                 for (int i = 0; i < len; ++i)
404                                         if (a [i] != b [i])
405                                                 return 1;
406                                 return 0;
407                         }
408                 }
409
410                 private int len;
411
412                 protected override int GetHash (Object key)
413                 {
414                         char[] arr = (char[])key;
415                         int h = 0;
416
417                         for (int i = 0; i < len; ++i)
418                                 h = (h << 5) - h + arr [i];
419
420                         return h;
421                 }
422
423                 public CharArrayHashtable (int len)
424                 {
425                         this.len = len;
426                         comparer = new ArrComparer (len);
427                 }
428         }                       
429
430         struct Pair {
431                 public object First;
432                 public object Second;
433                 
434                 public Pair (object f, object s)
435                 {
436                         First = f;
437                         Second = s;
438                 }
439         }
440
441         /// <summary>
442         ///   This is a wrapper around StreamReader which is seekable backwards
443         ///   within a window of around 2048 chars.
444         /// </summary>
445         public class SeekableStreamReader
446         {
447                 public SeekableStreamReader (StreamReader reader)
448                 {
449                         this.reader = reader;
450                         this.buffer = new char [AverageReadLength * 3];
451
452                         // Let the StreamWriter autodetect the encoder
453                         reader.Peek ();
454                 }
455
456                 public SeekableStreamReader (Stream stream, Encoding encoding)
457                         : this (new StreamReader (stream, encoding, true))
458                 { }
459
460                 StreamReader reader;
461
462                 private const int AverageReadLength = 1024;
463
464                 char[] buffer;
465                 int buffer_start;       // in chars
466                 int char_count;         // count buffer[] valid characters
467                 int pos;                // index into buffer[]
468
469                 /// <remarks>
470                 ///   This value corresponds to the current position in a stream of characters.
471                 ///   The StreamReader hides its manipulation of the underlying byte stream and all
472                 ///   character set/decoding issues.  Thus, we cannot use this position to guess at
473                 ///   the corresponding position in the underlying byte stream even though there is
474                 ///   a correlation between them.
475                 /// </remarks>
476                 public int Position {
477                         get { return buffer_start + pos; }
478
479                         set {
480                                 if (value < buffer_start || value > buffer_start + char_count)
481                                         throw new InternalErrorException ("can't seek that far back: " + (pos - value));
482                                 pos = value - buffer_start;
483                         }
484                 }
485
486                 private bool ReadBuffer ()
487                 {
488                         int slack = buffer.Length - char_count;
489                         if (slack <= AverageReadLength / 2) {
490                                 // shift the buffer to make room for AverageReadLength number of characters
491                                 int shift = AverageReadLength - slack;
492                                 Array.Copy (buffer, shift, buffer, 0, char_count - shift);
493                                 pos -= shift;
494                                 char_count -= shift;
495                                 buffer_start += shift;
496                                 slack += shift;         // slack == AverageReadLength
497                         }
498
499                         int chars_read = reader.Read (buffer, char_count, slack);
500                         char_count += chars_read;
501
502                         return pos < char_count;
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 }