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