2007-07-03 Marek Safar <marek.safar@gmail.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                 void 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 void InflateTypes (Type[] genArguments, Type[] argTypes)
142                 {
143                         for (int i = 0; i < types.Length; ++i) {
144                                 if (types[i].IsGenericParameter) {
145                                         for (int ii = 0; ii < genArguments.Length; ++ii) {
146                                                 if (types[i] != genArguments[ii])
147                                                         continue;
148
149                                                 types[i] = argTypes[ii];
150                                                 break;
151                                         }
152                                         continue;
153                                 }
154                                 
155                                 if (types[i].IsGenericType) {
156                                         Type[] gen_arguments_open = types[i].GetGenericTypeDefinition ().GetGenericArguments ();
157                                         Type[] gen_arguments = types[i].GetGenericArguments ();
158                                         for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
159                                                 if (gen_arguments[ii].IsGenericParameter)
160                                                         gen_arguments_open[ii] = argTypes[gen_arguments_open[ii].GenericParameterPosition];
161                                                 else
162                                                         gen_arguments_open[ii] = gen_arguments[ii];
163                                         }
164
165                                         types[i] = types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
166                                 }
167                         }
168                 }
169 #endif
170
171                 public Type ParameterType (int pos)
172                 {
173                         if (is_varargs && pos >= pi.Length)
174                                 return TypeManager.runtime_argument_handle_type;
175
176                         return types [pos];
177                 }
178
179                 public string ParameterName (int pos)
180                 {
181                         if (gpd != null)
182                                 return gpd.ParameterName (pos);
183
184                         if (is_varargs && pos >= pi.Length)
185                                 return "__arglist";
186
187                         return pi [pos].Name;
188                 }
189
190                 public string ParameterDesc (int pos)
191                 {
192                         if (is_varargs && pos >= pi.Length)
193                                 return "";
194
195                         StringBuilder sb = new StringBuilder ();
196
197                         if (pi [pos].IsIn)
198                                 sb.Append ("in ");
199
200                         Type partype = ParameterType (pos);
201                         if (partype.IsByRef){
202                                 partype = TypeManager.GetElementType (partype);
203                                 if (pi [pos].IsOut)
204                                         sb.Append ("out ");
205                                 else
206                                         sb.Append ("ref ");
207                         }
208
209                         if (params_idx == pos)
210                                 sb.Append ("params ");
211
212                         if (pos == 0 && ExtensionMethodType != null)
213                                 sb.Append ("this ");
214
215                         sb.Append (TypeManager.CSharpName (partype).Replace ("&", ""));
216
217                         return sb.ToString ();
218                 }
219
220                 public Parameter.Modifier ParameterModifier (int pos)
221                 {
222                         if (pos == params_idx)
223                                 return Parameter.Modifier.PARAMS;
224                         else if (is_varargs && pos >= pi.Length)
225                                 return Parameter.Modifier.ARGLIST;
226
227                         if (gpd != null)
228                                 return gpd.ParameterModifier (pos);
229
230                         Type t = types [pos];
231                         if (t.IsByRef){
232                                 if ((pi [pos].Attributes & (ParameterAttributes.Out|ParameterAttributes.In)) == ParameterAttributes.Out)
233                                         return Parameter.Modifier.OUT;
234                                 else
235                                         return Parameter.Modifier.REF;
236                         }
237
238                         return Parameter.Modifier.NONE;
239                 }
240
241                 public int Count {
242                         get { return is_varargs ? pi.Length + 1 : pi.Length; }
243                 }
244
245                 public Type ExtensionMethodType {
246                         get {
247                                 if (!is_extension)
248                                         return null;
249
250                                 return types [0];
251                         }
252                 }
253
254                 public bool HasParams {
255                         get { return params_idx != -1; }
256                 }
257
258                 public Type[] Types {
259                         get { return types; }
260                 }
261         }
262
263 #if GMCS_SOURCE
264         public class ReflectionConstraints : GenericConstraints
265         {
266                 GenericParameterAttributes attrs;
267                 Type base_type;
268                 Type class_constraint;
269                 Type[] iface_constraints;
270                 string name;
271
272                 public static GenericConstraints GetConstraints (Type t)
273                 {
274                         Type [] constraints = t.GetGenericParameterConstraints ();
275                         GenericParameterAttributes attrs = t.GenericParameterAttributes;
276                         if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
277                                 return null;
278                         return new ReflectionConstraints (t.Name, constraints, attrs);
279                 }
280
281                 private ReflectionConstraints (string name, Type [] constraints, GenericParameterAttributes attrs)
282                 {
283                         this.name = name;
284                         this.attrs = attrs;
285
286                         if ((constraints.Length > 0) && !constraints [0].IsInterface) {
287                                 class_constraint = constraints [0];
288                                 iface_constraints = new Type [constraints.Length - 1];
289                                 Array.Copy (constraints, 1, iface_constraints, 0, constraints.Length - 1);
290                         } else
291                                 iface_constraints = constraints;
292
293                         if (HasValueTypeConstraint)
294                                 base_type = TypeManager.value_type;
295                         else if (class_constraint != null)
296                                 base_type = class_constraint;
297                         else
298                                 base_type = TypeManager.object_type;
299                 }
300
301                 public override string TypeParameter {
302                         get { return name; }
303                 }
304
305                 public override GenericParameterAttributes Attributes {
306                         get { return attrs; }
307                 }
308
309                 public override Type ClassConstraint {
310                         get { return class_constraint; }
311                 }
312
313                 public override Type EffectiveBaseClass {
314                         get { return base_type; }
315                 }
316
317                 public override Type[] InterfaceConstraints {
318                         get { return iface_constraints; }
319                 }
320         }
321 #endif
322
323         class PtrHashtable : Hashtable {
324                 sealed class PtrComparer : IComparer {
325                         private PtrComparer () {}
326
327                         public static PtrComparer Instance = new PtrComparer ();
328
329                         public int Compare (object x, object y)
330                         {
331                                 if (x == y)
332                                         return 0;
333                                 else
334                                         return 1;
335                         }
336                 }
337
338                 public PtrHashtable ()
339                 {
340                         comparer = PtrComparer.Instance;
341                 }
342         }
343
344         /*
345          * Hashtable whose keys are character arrays with the same length
346          */
347         class CharArrayHashtable : Hashtable {
348                 sealed class ArrComparer : IComparer {
349                         private int len;
350
351                         public ArrComparer (int len) {
352                                 this.len = len;
353                         }
354
355                         public int Compare (object x, object y)
356                         {
357                                 char[] a = (char[])x;
358                                 char[] b = (char[])y;
359
360                                 for (int i = 0; i < len; ++i)
361                                         if (a [i] != b [i])
362                                                 return 1;
363                                 return 0;
364                         }
365                 }
366
367                 private int len;
368
369                 protected override int GetHash (Object key)
370                 {
371                         char[] arr = (char[])key;
372                         int h = 0;
373
374                         for (int i = 0; i < len; ++i)
375                                 h = (h << 5) - h + arr [i];
376
377                         return h;
378                 }
379
380                 public CharArrayHashtable (int len)
381                 {
382                         this.len = len;
383                         comparer = new ArrComparer (len);
384                 }
385         }
386
387         struct Pair {
388                 public object First;
389                 public object Second;
390
391                 public Pair (object f, object s)
392                 {
393                         First = f;
394                         Second = s;
395                 }
396         }
397
398         public class Accessors {
399                 public Accessor get_or_add;
400                 public Accessor set_or_remove;
401
402                 // was 'set' declared before 'get'?  was 'remove' declared before 'add'?
403                 public bool declared_in_reverse;
404
405                 public Accessors (Accessor get_or_add, Accessor set_or_remove)
406                 {
407                         this.get_or_add = get_or_add;
408                         this.set_or_remove = set_or_remove;
409                 }
410         }
411
412         /// <summary>
413         ///   This is a wrapper around StreamReader which is seekable backwards
414         ///   within a window of around 2048 chars.
415         /// </summary>
416         public class SeekableStreamReader
417         {
418                 public SeekableStreamReader (TextReader reader)
419                 {
420                         this.reader = reader;
421                         this.buffer = new char [AverageReadLength * 3];
422
423                         // Let the StreamWriter autodetect the encoder
424                         reader.Peek ();
425                 }
426
427                 public SeekableStreamReader (Stream stream, Encoding encoding)
428                         : this (new StreamReader (stream, encoding, true))
429                 { }
430
431                 TextReader reader;
432
433                 private const int AverageReadLength = 1024;
434
435                 char[] buffer;
436                 int buffer_start;       // in chars
437                 int char_count;         // count buffer[] valid characters
438                 int pos;                // index into buffer[]
439
440                 /// <remarks>
441                 ///   This value corresponds to the current position in a stream of characters.
442                 ///   The StreamReader hides its manipulation of the underlying byte stream and all
443                 ///   character set/decoding issues.  Thus, we cannot use this position to guess at
444                 ///   the corresponding position in the underlying byte stream even though there is
445                 ///   a correlation between them.
446                 /// </remarks>
447                 public int Position {
448                         get { return buffer_start + pos; }
449
450                         set {
451                                 if (value < buffer_start || value > buffer_start + char_count)
452                                         throw new InternalErrorException ("can't seek that far back: " + (pos - value));
453                                 pos = value - buffer_start;
454                         }
455                 }
456
457                 private bool ReadBuffer ()
458                 {
459                         int slack = buffer.Length - char_count;
460                         if (slack <= AverageReadLength / 2) {
461                                 // shift the buffer to make room for AverageReadLength number of characters
462                                 int shift = AverageReadLength - slack;
463                                 Array.Copy (buffer, shift, buffer, 0, char_count - shift);
464                                 pos -= shift;
465                                 char_count -= shift;
466                                 buffer_start += shift;
467                                 slack += shift;         // slack == AverageReadLength
468                         }
469
470                         int chars_read = reader.Read (buffer, char_count, slack);
471                         char_count += chars_read;
472
473                         return pos < char_count;
474                 }
475
476                 public int Peek ()
477                 {
478                         if ((pos >= char_count) && !ReadBuffer ())
479                                 return -1;
480
481                         return buffer [pos];
482                 }
483
484                 public int Read ()
485                 {
486                         if ((pos >= char_count) && !ReadBuffer ())
487                                 return -1;
488
489                         return buffer [pos++];
490                 }
491         }
492
493         public class DoubleHash {
494                 const int DEFAULT_INITIAL_BUCKETS = 100;
495
496                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
497
498                 public DoubleHash (int size)
499                 {
500                         count = size;
501                         buckets = new Entry [size];
502                 }
503
504                 int count;
505                 Entry [] buckets;
506                 int size = 0;
507
508                 class Entry {
509                         public object key1;
510                         public object key2;
511                         public int hash;
512                         public object value;
513                         public Entry next;
514
515                         public Entry (object key1, object key2, int hash, object value, Entry next)
516                         {
517                                 this.key1 = key1;
518                                 this.key2 = key2;
519                                 this.hash = hash;
520                                 this.next = next;
521                                 this.value = value;
522                         }
523                 }
524
525                 public bool Lookup (object a, object b, out object res)
526                 {
527                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
528
529                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
530                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
531                                         res = e.value;
532                                         return true;
533                                 }
534                         }
535                         res = null;
536                         return false;
537                 }
538
539                 public void Insert (object a, object b, object value)
540                 {
541                         // Is it an existing one?
542
543                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
544
545                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
546                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
547                                         e.value = value;
548                         }
549
550                         int bucket = h % count;
551                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
552
553                         // Grow whenever we double in size
554                         if (size++ == count) {
555                                 count <<= 1;
556                                 count ++;
557
558                                 Entry [] newBuckets = new Entry [count];
559                                 foreach (Entry root in buckets) {
560                                         Entry e = root;
561                                         while (e != null) {
562                                                 int newLoc = e.hash % count;
563                                                 Entry n = e.next;
564                                                 e.next = newBuckets [newLoc];
565                                                 newBuckets [newLoc] = e;
566                                                 e = n;
567                                         }
568                                 }
569
570                                 buckets = newBuckets;
571                         }
572                 }
573         }
574 }