2008-03-11 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                 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 = int.MaxValue;
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] = TypeManager.TypeToCoreType (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                                         break;
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                         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 != int.MaxValue; }
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                 const int AverageReadLength = 1024;
429                 TextReader reader;
430                 Stream stream;
431                 Encoding encoding;
432
433                 char[] buffer;
434                 int buffer_start;       // in chars
435                 int char_count;         // count buffer[] valid characters
436                 int pos;                // index into buffer[]
437
438                 public SeekableStreamReader (Stream stream, Encoding encoding)
439                 {
440                         this.stream = stream;
441                         this.encoding = encoding;
442                         
443                         this.reader = new StreamReader (stream, encoding, true);
444                         this.buffer = new char [AverageReadLength * 3];
445
446                         // Let the StreamWriter autodetect the encoder
447                         reader.Peek ();
448                 }
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 + char_count)
462                                         throw new InternalErrorException ("can't seek that far forward: " + (pos - value));
463                                 
464                                 if (value < buffer_start){
465                                         // Reinitialize.
466                                         stream.Position = 0;
467                                         reader = new StreamReader (stream, encoding, true);
468                                         buffer_start = 0;
469                                         char_count = 0;
470                                         pos = 0;
471                                         Peek ();
472
473                                         while (value > buffer_start + char_count){
474                                                 pos = char_count+1;
475                                                 Peek ();
476                                         }
477                                         pos = value - buffer_start;
478                                 }
479
480                                 pos = value - buffer_start;
481                         }
482                 }
483
484                 private bool ReadBuffer ()
485                 {
486                         int slack = buffer.Length - char_count;
487                         if (slack <= AverageReadLength / 2) {
488                                 // shift the buffer to make room for AverageReadLength number of characters
489                                 int shift = AverageReadLength - slack;
490                                 Array.Copy (buffer, shift, buffer, 0, char_count - shift);
491                                 pos -= shift;
492                                 char_count -= shift;
493                                 buffer_start += shift;
494                                 slack += shift;         // slack == AverageReadLength
495                         }
496
497                         int chars_read = reader.Read (buffer, char_count, slack);
498                         char_count += chars_read;
499
500                         return pos < char_count;
501                 }
502
503                 public int Peek ()
504                 {
505                         if ((pos >= char_count) && !ReadBuffer ())
506                                 return -1;
507
508                         return buffer [pos];
509                 }
510
511                 public int Read ()
512                 {
513                         if ((pos >= char_count) && !ReadBuffer ())
514                                 return -1;
515
516                         return buffer [pos++];
517                 }
518         }
519
520         public class DoubleHash {
521                 const int DEFAULT_INITIAL_BUCKETS = 100;
522
523                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
524
525                 public DoubleHash (int size)
526                 {
527                         count = size;
528                         buckets = new Entry [size];
529                 }
530
531                 int count;
532                 Entry [] buckets;
533                 int size = 0;
534
535                 class Entry {
536                         public object key1;
537                         public object key2;
538                         public int hash;
539                         public object value;
540                         public Entry next;
541
542                         public Entry (object key1, object key2, int hash, object value, Entry next)
543                         {
544                                 this.key1 = key1;
545                                 this.key2 = key2;
546                                 this.hash = hash;
547                                 this.next = next;
548                                 this.value = value;
549                         }
550                 }
551
552                 public bool Lookup (object a, object b, out object res)
553                 {
554                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
555
556                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
557                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b)) {
558                                         res = e.value;
559                                         return true;
560                                 }
561                         }
562                         res = null;
563                         return false;
564                 }
565
566                 public void Insert (object a, object b, object value)
567                 {
568                         // Is it an existing one?
569
570                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
571
572                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
573                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
574                                         e.value = value;
575                         }
576
577                         int bucket = h % count;
578                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
579
580                         // Grow whenever we double in size
581                         if (size++ == count) {
582                                 count <<= 1;
583                                 count ++;
584
585                                 Entry [] newBuckets = new Entry [count];
586                                 foreach (Entry root in buckets) {
587                                         Entry e = root;
588                                         while (e != null) {
589                                                 int newLoc = e.hash % count;
590                                                 Entry n = e.next;
591                                                 e.next = newBuckets [newLoc];
592                                                 newBuckets [newLoc] = e;
593                                                 e = n;
594                                         }
595                                 }
596
597                                 buckets = newBuckets;
598                         }
599                 }
600         }
601
602         class PartialMethodDefinitionInfo : MethodInfo
603         {
604                 MethodOrOperator mc;
605                 MethodAttributes attrs;
606
607                 public PartialMethodDefinitionInfo (MethodOrOperator mc)
608                 {
609                         this.mc = mc;
610                         if ((mc.ModFlags & Modifiers.STATIC) != 0)
611                                 attrs = MethodAttributes.Static;
612                 }
613
614                 public override MethodInfo GetBaseDefinition ()
615                 {
616                         throw new NotImplementedException ();
617                 }
618
619                 public override ICustomAttributeProvider ReturnTypeCustomAttributes
620                 {
621                         get { throw new NotImplementedException (); }
622                 }
623
624                 public override MethodAttributes Attributes
625                 {
626                         get { return attrs; }
627                 }
628
629                 public override MethodImplAttributes GetMethodImplementationFlags ()
630                 {
631                         throw new NotImplementedException ();
632                 }
633
634                 public override ParameterInfo [] GetParameters ()
635                 {
636                         throw new NotImplementedException ();
637                 }
638
639                 public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object [] parameters, CultureInfo culture)
640                 {
641                         throw new NotImplementedException ();
642                 }
643
644                 public override RuntimeMethodHandle MethodHandle
645                 {
646                         get { throw new NotImplementedException (); }
647                 }
648
649                 public override Type DeclaringType
650                 {
651                         get { return mc.Parent.TypeBuilder; }
652                 }
653
654                 public override object [] GetCustomAttributes (Type attributeType, bool inherit)
655                 {
656                         throw new NotImplementedException ();
657                 }
658
659                 public override object [] GetCustomAttributes (bool inherit)
660                 {
661                         throw new NotImplementedException ();
662                 }
663
664                 public override Type ReturnType {
665                         get {
666                                 return mc.MemberType;
667                         }
668                 }
669
670                 public override bool IsDefined (Type attributeType, bool inherit)
671                 {
672                         throw new NotImplementedException ();
673                 }
674
675                 public override string Name
676                 {
677                         get { return mc.Name; }
678                 }
679
680                 public override Type ReflectedType
681                 {
682                         get { throw new NotImplementedException (); }
683                 }
684         }
685
686 }