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