2007-10-19 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / mcs / 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                 Type ExtensionMethodType { get; }
26                 bool HasParams { get; }
27                 string ParameterName (int pos);
28                 string ParameterDesc (int pos);
29
30                 Parameter.Modifier ParameterModifier (int pos);
31                 string GetSignatureForError ();
32
33 #if MS_COMPATIBLE
34                 ParameterData InflateTypes (Type[] genArguments, Type[] argTypes);
35 #endif
36         }
37
38         public class ReflectionParameters : ParameterData {
39                 ParameterInfo [] pi;
40                 Type [] types;
41                 int params_idx = -1;
42                 bool is_varargs;
43                 bool is_extension;
44                 ParameterData gpd;
45
46                 public ReflectionParameters (MethodBase mb)
47                 {
48                         ParameterInfo [] pi = mb.GetParameters ();
49                         is_varargs = (mb.CallingConvention & CallingConventions.VarArgs) != 0;
50
51                         this.pi = pi;
52                         int count = pi.Length;
53
54                         if (count == 0) {
55                                 types = Type.EmptyTypes;
56                                 return;
57                         }
58
59                         types = new Type [count];
60                         for (int i = 0; i < count; i++)
61                                 types [i] = pi [i].ParameterType;
62
63                         // TODO: This (if) should be done one level higher to correctly use
64                         // out caching facilities.
65                         MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
66                         if (generic != mb) {
67                                 gpd = TypeManager.GetParameterData (generic);
68                                 if (gpd.HasParams) {
69                                         for (int i = gpd.Count; i != 0; --i) {
70                                                 if ((gpd.ParameterModifier (i-1) & Parameter.Modifier.PARAMS) != 0) {
71                                                         this.params_idx = i-1;
72                                                         break;
73                                                 }
74                                         }
75                                 }
76                                 return;
77                         }
78
79                         //
80                         // So far, the params attribute can be used in C# for the last
81                         // and next to last method parameters.
82                         // If some other language can place it anywhere we will
83                         // have to analyze all parameters and not just last 2.
84                         //
85                         --count;
86                         for (int i = count; i >= 0 && i > count - 2; --i) {
87                                 if (!pi [i].ParameterType.IsArray)
88                                         continue;
89
90                                 if (pi [i].IsDefined (TypeManager.param_array_type, false)) {
91                                         params_idx = i;
92                                         return;
93                                 }
94                         }
95
96                         if (TypeManager.extension_attribute_type != null && mb.IsStatic &&
97                                 (mb.DeclaringType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
98                                 mb.IsDefined (TypeManager.extension_attribute_type, false))
99                                 is_extension = true;
100                 }
101
102                 public override bool Equals (object obj)
103                 {
104                         ReflectionParameters rp = obj as ReflectionParameters;
105                         if (rp == null)
106                                 return false;
107
108                         if (Count != rp.Count)
109                                 return false;
110
111                         for (int i = 0; i < Count; ++i) {
112                         if (!types [i].Equals (rp.types [i]))
113                                 return false;
114                         }
115                         return true;
116                 }
117
118                 public override int GetHashCode ()
119                 {
120                         return base.GetHashCode ();
121                 }
122
123                 public string GetSignatureForError ()
124                 {
125                         StringBuilder sb = new StringBuilder ("(");
126                         for (int i = 0; i < pi.Length; ++i) {
127                                 if (i != 0)
128                                         sb.Append (", ");
129                                 sb.Append (ParameterDesc (i));
130                         }
131                         if (is_varargs) {
132                                 if (pi.Length > 0)
133                                         sb.Append (", ");
134                                 sb.Append ("__arglist");
135                         }
136                         sb.Append (')');
137                         return sb.ToString ();
138                 }
139
140 #if MS_COMPATIBLE
141                 public ParameterData InflateTypes (Type[] genArguments, Type[] argTypes)
142                 {
143                         ReflectionParameters p = (ReflectionParameters)MemberwiseClone ();
144
145                         for (int i = 0; i < types.Length; ++i) {
146                                 if (types[i].IsGenericParameter) {
147                                         for (int ii = 0; ii < genArguments.Length; ++ii) {
148                                                 if (types[i] != genArguments[ii])
149                                                         continue;
150
151                                                 p.types[i] = argTypes[ii];
152                                                 break;
153                                         }
154                                         continue;
155                                 }
156                                 
157                                 if (types[i].IsGenericType) {
158                                         Type[] gen_arguments_open = types[i].GetGenericTypeDefinition ().GetGenericArguments ();
159                                         Type[] gen_arguments = types[i].GetGenericArguments ();
160                                         for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
161                                                 if (gen_arguments [ii].IsGenericParameter) {
162                                                         for (int iii = 0; iii < genArguments.Length; ++iii) {
163                                                                 if (gen_arguments [ii] != genArguments [iii])
164                                                                         continue;
165
166                                                                 gen_arguments_open [ii] = argTypes [iii];
167                                                                 break;
168                                                         }
169                                                 } else {
170                                                         gen_arguments_open [ii] = gen_arguments [ii];
171                                                 }
172                                         }
173
174                                         p.types[i] = types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
175                                 }
176                         }
177                         return p;
178                 }
179 #endif
180
181                 public Type ParameterType (int pos)
182                 {
183                         if (is_varargs && pos >= pi.Length)
184                                 return TypeManager.runtime_argument_handle_type;
185
186                         return types [pos];
187                 }
188
189                 public string ParameterName (int pos)
190                 {
191                         if (gpd != null)
192                                 return gpd.ParameterName (pos);
193
194                         if (is_varargs && pos >= pi.Length)
195                                 return "__arglist";
196
197                         return pi [pos].Name;
198                 }
199
200                 public string ParameterDesc (int pos)
201                 {
202                         if (is_varargs && pos >= pi.Length)
203                                 return "";
204
205                         StringBuilder sb = new StringBuilder ();
206
207                         if (pi [pos].IsIn)
208                                 sb.Append ("in ");
209
210                         Type partype = ParameterType (pos);
211                         if (partype.IsByRef){
212                                 partype = TypeManager.GetElementType (partype);
213                                 if (pi [pos].IsOut)
214                                         sb.Append ("out ");
215                                 else
216                                         sb.Append ("ref ");
217                         }
218
219                         if (params_idx == pos)
220                                 sb.Append ("params ");
221
222                         if (pos == 0 && ExtensionMethodType != null)
223                                 sb.Append ("this ");
224
225                         sb.Append (TypeManager.CSharpName (partype).Replace ("&", ""));
226
227                         return sb.ToString ();
228                 }
229
230                 public Parameter.Modifier ParameterModifier (int pos)
231                 {
232                         if (pos == params_idx)
233                                 return Parameter.Modifier.PARAMS;
234                         else if (is_varargs && pos >= pi.Length)
235                                 return Parameter.Modifier.ARGLIST;
236
237                         if (gpd != null)
238                                 return gpd.ParameterModifier (pos);
239
240                         Type t = types [pos];
241                         if (t.IsByRef){
242                                 if ((pi [pos].Attributes & (ParameterAttributes.Out|ParameterAttributes.In)) == ParameterAttributes.Out)
243                                         return Parameter.Modifier.OUT;
244                                 else
245                                         return Parameter.Modifier.REF;
246                         }
247
248                         return Parameter.Modifier.NONE;
249                 }
250
251                 public int Count {
252                         get { return is_varargs ? pi.Length + 1 : pi.Length; }
253                 }
254
255                 public Type ExtensionMethodType {
256                         get {
257                                 if (!is_extension)
258                                         return null;
259
260                                 return types [0];
261                         }
262                 }
263
264                 public bool HasParams {
265                         get { return params_idx != -1; }
266                 }
267
268                 public Type[] Types {
269                         get { return types; }
270                 }
271         }
272
273 #if GMCS_SOURCE
274         public class ReflectionConstraints : GenericConstraints
275         {
276                 GenericParameterAttributes attrs;
277                 Type base_type;
278                 Type class_constraint;
279                 Type[] iface_constraints;
280                 string name;
281
282                 public static GenericConstraints GetConstraints (Type t)
283                 {
284                         Type [] constraints = t.GetGenericParameterConstraints ();
285                         GenericParameterAttributes attrs = t.GenericParameterAttributes;
286                         if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
287                                 return null;
288                         return new ReflectionConstraints (t.Name, constraints, attrs);
289                 }
290
291                 private ReflectionConstraints (string name, Type [] constraints, GenericParameterAttributes attrs)
292                 {
293                         this.name = name;
294                         this.attrs = attrs;
295
296                         if ((constraints.Length > 0) && !constraints [0].IsInterface) {
297                                 class_constraint = constraints [0];
298                                 iface_constraints = new Type [constraints.Length - 1];
299                                 Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
300                         } else
301                                 iface_constraints = constraints;
302
303                         if (HasValueTypeConstraint)
304                                 base_type = TypeManager.value_type;
305                         else if (class_constraint != null)
306                                 base_type = class_constraint;
307                         else
308                                 base_type = TypeManager.object_type;
309                 }
310
311                 public override string TypeParameter {
312                         get { return name; }
313                 }
314
315                 public override GenericParameterAttributes Attributes {
316                         get { return attrs; }
317                 }
318
319                 public override Type ClassConstraint {
320                         get { return class_constraint; }
321                 }
322
323                 public override Type EffectiveBaseClass {
324                         get { return base_type; }
325                 }
326
327                 public override Type[] InterfaceConstraints {
328                         get { return iface_constraints; }
329                 }
330         }
331 #endif
332
333         class PtrHashtable : Hashtable {
334                 sealed class PtrComparer : IComparer {
335                         private PtrComparer () {}
336
337                         public static PtrComparer Instance = new PtrComparer ();
338
339                         public int Compare (object x, object y)
340                         {
341                                 if (x == y)
342                                         return 0;
343                                 else
344                                         return 1;
345                         }
346                 }
347
348                 public PtrHashtable ()
349                 {
350                         comparer = PtrComparer.Instance;
351                 }
352         }
353
354         /*
355          * Hashtable whose keys are character arrays with the same length
356          */
357         class CharArrayHashtable : Hashtable {
358                 sealed class ArrComparer : IComparer {
359                         private int len;
360
361                         public ArrComparer (int len) {
362                                 this.len = len;
363                         }
364
365                         public int Compare (object x, object y)
366                         {
367                                 char[] a = (char[])x;
368                                 char[] b = (char[])y;
369
370                                 for (int i = 0; i < len; ++i)
371                                         if (a [i] != b [i])
372                                                 return 1;
373                                 return 0;
374                         }
375                 }
376
377                 private int len;
378
379                 protected override int GetHash (Object key)
380                 {
381                         char[] arr = (char[])key;
382                         int h = 0;
383
384                         for (int i = 0; i < len; ++i)
385                                 h = (h << 5) - h + arr [i];
386
387                         return h;
388                 }
389
390                 public CharArrayHashtable (int len)
391                 {
392                         this.len = len;
393                         comparer = new ArrComparer (len);
394                 }
395         }
396
397         struct Pair {
398                 public object First;
399                 public object Second;
400
401                 public Pair (object f, object s)
402                 {
403                         First = f;
404                         Second = s;
405                 }
406         }
407
408         public class Accessors {
409                 public Accessor get_or_add;
410                 public Accessor set_or_remove;
411
412                 // was 'set' declared before 'get'?  was 'remove' declared before 'add'?
413                 public bool declared_in_reverse;
414
415                 public Accessors (Accessor get_or_add, Accessor set_or_remove)
416                 {
417                         this.get_or_add = get_or_add;
418                         this.set_or_remove = set_or_remove;
419                 }
420         }
421
422         /// <summary>
423         ///   This is a wrapper around StreamReader which is seekable backwards
424         ///   within a window of around 2048 chars.
425         /// </summary>
426         public class SeekableStreamReader
427         {
428                 public SeekableStreamReader (TextReader reader)
429                 {
430                         this.reader = reader;
431                         this.buffer = new char [AverageReadLength * 3];
432
433                         // Let the StreamWriter autodetect the encoder
434                         reader.Peek ();
435                 }
436
437                 public SeekableStreamReader (Stream stream, Encoding encoding)
438                         : this (new StreamReader (stream, encoding, true))
439                 { }
440
441                 TextReader reader;
442
443                 private const int AverageReadLength = 1024;
444
445                 char[] buffer;
446                 int buffer_start;       // in chars
447                 int char_count;         // count buffer[] valid characters
448                 int pos;                // index into buffer[]
449
450                 /// <remarks>
451                 ///   This value corresponds to the current position in a stream of characters.
452                 ///   The StreamReader hides its manipulation of the underlying byte stream and all
453                 ///   character set/decoding issues.  Thus, we cannot use this position to guess at
454                 ///   the corresponding position in the underlying byte stream even though there is
455                 ///   a correlation between them.
456                 /// </remarks>
457                 public int Position {
458                         get { return buffer_start + pos; }
459
460                         set {
461                                 if (value < buffer_start || value > buffer_start + char_count)
462                                         throw new InternalErrorException ("can't seek that far back: " + (pos - value));
463                                 pos = value - buffer_start;
464                         }
465                 }
466
467                 private bool ReadBuffer ()
468                 {
469                         int slack = buffer.Length - char_count;
470                         if (slack <= AverageReadLength / 2) {
471                                 // shift the buffer to make room for AverageReadLength number of characters
472                                 int shift = AverageReadLength - slack;
473                                 Array.Copy (buffer, shift, buffer, 0, char_count - shift);
474                                 pos -= shift;
475                                 char_count -= shift;
476                                 buffer_start += shift;
477                                 slack += shift;         // slack == AverageReadLength
478                         }
479
480                         int chars_read = reader.Read (buffer, char_count, slack);
481                         char_count += chars_read;
482
483                         return pos < char_count;
484                 }
485
486                 public int Peek ()
487                 {
488                         if ((pos >= char_count) && !ReadBuffer ())
489                                 return -1;
490
491                         return buffer [pos];
492                 }
493
494                 public int Read ()
495                 {
496                         if ((pos >= char_count) && !ReadBuffer ())
497                                 return -1;
498
499                         return buffer [pos++];
500                 }
501         }
502
503         public class DoubleHash {
504                 const int DEFAULT_INITIAL_BUCKETS = 100;
505
506                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
507
508                 public DoubleHash (int size)
509                 {
510                         count = size;
511                         buckets = new Entry [size];
512                 }
513
514                 int count;
515                 Entry [] buckets;
516                 int size = 0;
517
518                 class Entry {
519                         public object key1;
520                         public object key2;
521                         public int hash;
522                         public object value;
523                         public Entry next;
524
525                         public Entry (object key1, object key2, int hash, object value, Entry next)
526                         {
527                                 this.key1 = key1;
528                                 this.key2 = key2;
529                                 this.hash = hash;
530                                 this.next = next;
531                                 this.value = value;
532                         }
533                 }
534
535                 public bool Lookup (object a, object b, out object res)
536                 {
537                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
538
539                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
540                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
541                                         res = e.value;
542                                         return true;
543                                 }
544                         }
545                         res = null;
546                         return false;
547                 }
548
549                 public void Insert (object a, object b, object value)
550                 {
551                         // Is it an existing one?
552
553                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
554
555                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
556                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
557                                         e.value = value;
558                         }
559
560                         int bucket = h % count;
561                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
562
563                         // Grow whenever we double in size
564                         if (size++ == count) {
565                                 count <<= 1;
566                                 count ++;
567
568                                 Entry [] newBuckets = new Entry [count];
569                                 foreach (Entry root in buckets) {
570                                         Entry e = root;
571                                         while (e != null) {
572                                                 int newLoc = e.hash % count;
573                                                 Entry n = e.next;
574                                                 e.next = newBuckets [newLoc];
575                                                 newBuckets [newLoc] = e;
576                                                 e = n;
577                                         }
578                                 }
579
580                                 buckets = newBuckets;
581                         }
582                 }
583         }
584 }