new error test
[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                 int  Count { get; }
24                 string ParameterName (int pos);
25                 string ParameterDesc (int pos);
26                 Parameter.Modifier ParameterModifier (int pos);
27         }
28
29         public class ReflectionParameters : ParameterData {
30                 ParameterInfo [] pi;
31                 bool last_arg_is_params = false;
32                 bool is_varargs = false;
33                 
34                 public ReflectionParameters (MethodBase mb)
35                 {
36                         object [] attrs;
37
38                         ParameterInfo [] pi = mb.GetParameters ();
39                         is_varargs = mb.CallingConvention == CallingConventions.VarArgs;
40                         
41                         this.pi = pi;
42                         int count = pi.Length-1;
43
44                         if (count >= 0) {
45                                 attrs = pi [count].GetCustomAttributes (TypeManager.param_array_type, true);
46
47                                 if (attrs == null)
48                                         return;
49                                 
50                                 if (attrs.Length == 0)
51                                         return;
52
53                                 last_arg_is_params = true;
54                         }
55                 }
56                        
57                 public Type ParameterType (int pos)
58                 {
59                         if (last_arg_is_params && pos >= pi.Length - 1)
60                                 return pi [pi.Length - 1].ParameterType;
61                         else if (is_varargs && pos >= pi.Length)
62                                 return TypeManager.runtime_argument_handle_type;
63                         else {
64                                 Type t = pi [pos].ParameterType;
65
66                                 return t;
67                         }
68                 }
69
70                 public string ParameterName (int pos)
71                 {
72                         if (last_arg_is_params && pos >= pi.Length - 1)
73                                 return pi [pi.Length - 1].Name;
74                         else if (is_varargs && pos >= pi.Length)
75                                 return "__arglist";
76                         else 
77                                 return pi [pos].Name;
78                 }
79
80                 public string ParameterDesc (int pos)
81                 {
82                         if (is_varargs && pos >= pi.Length)
83                                 return "";                      
84
85                         StringBuilder sb = new StringBuilder ();
86
87                         if (pi [pos].IsIn)
88                                 sb.Append ("in ");
89
90                         Type partype = ParameterType (pos);
91                         if (partype.IsByRef){
92                                 partype = TypeManager.GetElementType (partype);
93                                 if (pi [pos].IsOut)
94                                         sb.Append ("out ");
95                                 else
96                                         sb.Append ("ref ");
97                         } 
98
99                         if (pos >= pi.Length - 1 && last_arg_is_params)
100                                 sb.Append ("params ");
101                         
102                         sb.Append (TypeManager.CSharpName (partype));
103
104                         return sb.ToString ();
105                         
106                 }
107
108                 public Parameter.Modifier ParameterModifier (int pos)
109                 {
110                         int len = pi.Length;
111
112                         if (last_arg_is_params && pos >= pi.Length - 1)
113                                 return Parameter.Modifier.PARAMS;
114                         else if (is_varargs && pos >= pi.Length)
115                                 return Parameter.Modifier.ARGLIST;
116                         
117                         Type t = pi [pos].ParameterType;
118                         if (t.IsByRef){
119                                 if ((pi [pos].Attributes & ParameterAttributes.Out) != 0)
120                                         return Parameter.Modifier.ISBYREF | Parameter.Modifier.OUT;
121                                 else
122                                         return Parameter.Modifier.ISBYREF | Parameter.Modifier.REF;
123                         }
124                         
125                         return Parameter.Modifier.NONE;
126                 }
127
128                 public int Count {
129                         get {
130                                 return is_varargs ? pi.Length + 1 : pi.Length;
131                         }
132                 }
133                 
134         }
135
136         public class InternalParameters : ParameterData {
137                 Type [] param_types;
138                 bool has_varargs;
139                 int count;
140
141                 public readonly Parameters Parameters;
142                 
143                 public InternalParameters (Type [] param_types, Parameters parameters)
144                 {
145                         this.param_types = param_types;
146                         this.Parameters = parameters;
147                 }
148
149                 public InternalParameters (DeclSpace ds, Parameters parameters)
150                         : this (parameters.GetParameterInfo (ds), parameters)
151                 {
152                         has_varargs = parameters.HasArglist;
153
154                         if (param_types == null)
155                                 count = 0;
156                         else
157                                 count = param_types.Length;
158                 }
159
160                 public int Count {
161                         get {
162                                 return has_varargs ? count + 1 : count;
163                         }
164                 }
165
166                 Parameter GetParameter (int pos)
167                 {
168                         Parameter [] fixed_pars = Parameters.FixedParameters;
169                         if (fixed_pars != null){
170                                 int len = fixed_pars.Length;
171                                 if (pos < len)
172                                         return Parameters.FixedParameters [pos];
173                         }
174
175                         return Parameters.ArrayParameter;
176                 }
177
178                 public Type ParameterType (int pos)
179                 {
180                         if (has_varargs && pos >= count)
181                                 return TypeManager.runtime_argument_handle_type;
182
183                         if (param_types == null)
184                                 return null;
185
186                         return GetParameter (pos).ExternalType ();
187                 }
188
189
190                 public string ParameterName (int pos)
191                 {
192                         if (has_varargs && pos >= count)
193                                 return "__arglist";
194
195                         return GetParameter (pos).Name;
196                 }
197
198                 public string ParameterDesc (int pos)
199                 {
200                         if (has_varargs && pos >= count)
201                                 return "__arglist";
202
203                         string tmp = String.Empty;
204                         Parameter p = GetParameter (pos);
205
206                         //
207                         // We need to and for REF/OUT, because if either is set the
208                         // extra flag ISBYREF will be set as well
209                         //
210                         if ((p.ModFlags & Parameter.Modifier.REF) != 0)
211                                 tmp = "ref ";
212                         else if ((p.ModFlags & Parameter.Modifier.OUT) != 0)
213                                 tmp = "out ";
214                         else if (p.ModFlags == Parameter.Modifier.PARAMS)
215                                 tmp = "params ";
216
217                         Type t = ParameterType (pos);
218
219                         return tmp + TypeManager.CSharpName (t);
220                 }
221
222                 public Parameter.Modifier ParameterModifier (int pos)
223                 {
224                         if (has_varargs && pos >= count)
225                                 return Parameter.Modifier.ARGLIST;
226
227                         Parameter.Modifier mod = GetParameter (pos).ModFlags;
228
229                         if ((mod & (Parameter.Modifier.REF | Parameter.Modifier.OUT)) != 0)
230                                 mod |= Parameter.Modifier.ISBYREF;
231
232                         return mod;
233                 }
234                 
235         }
236
237         class PtrHashtable : Hashtable {
238                 sealed class PtrComparer : IComparer {
239                         private PtrComparer () {}
240                         
241                         public static PtrComparer Instance = new PtrComparer ();
242                         
243                         public int Compare (object x, object y)
244                         {
245                                 if (x == y)
246                                         return 0;
247                                 else
248                                         return 1;
249                         }
250                 }
251                 
252                 public PtrHashtable ()
253                 {
254                         comparer = PtrComparer.Instance;
255                 }
256         }
257
258         /*
259          * Hashtable whose keys are character arrays with the same length
260          */
261         class CharArrayHashtable : Hashtable {
262                 sealed class ArrComparer : IComparer {
263                         private int len;
264
265                         public ArrComparer (int len) {
266                                 this.len = len;
267                         }
268
269                         public int Compare (object x, object y)
270                         {
271                                 char[] a = (char[])x;
272                                 char[] b = (char[])y;
273
274                                 for (int i = 0; i < len; ++i)
275                                         if (a [i] != b [i])
276                                                 return 1;
277                                 return 0;
278                         }
279                 }
280
281                 private int len;
282
283                 protected override int GetHash (Object key)
284                 {
285                         char[] arr = (char[])key;
286                         int h = 0;
287
288                         for (int i = 0; i < len; ++i)
289                                 h = (h << 5) - h + arr [i];
290
291                         return h;
292                 }
293
294                 public CharArrayHashtable (int len)
295                 {
296                         this.len = len;
297                         comparer = new ArrComparer (len);
298                 }
299         }                       
300
301         //
302         // Compares member infos based on their name and
303         // also allows one argument to be a string
304         //
305         class MemberInfoCompare : IComparer {
306
307                 public int Compare (object a, object b)
308                 {
309                         if (a == null || b == null){
310                                 Console.WriteLine ("Invalid information passed");
311                                 throw new Exception ();
312                         }
313                         
314                         if (a is string)
315                                 return String.Compare ((string) a, ((MemberInfo)b).Name, false, CultureInfo.InvariantCulture);
316
317                         if (b is string)
318                                 return String.Compare (((MemberInfo)a).Name, (string) b, false, CultureInfo.InvariantCulture);
319
320                         return String.Compare (((MemberInfo)a).Name, ((MemberInfo)b).Name, false, CultureInfo.InvariantCulture);
321                 }
322         }
323
324         struct Pair {
325                 public object First;
326                 public object Second;
327                 
328                 public Pair (object f, object s)
329                 {
330                         First = f;
331                         Second = s;
332                 }
333         }
334
335         /// <summary>
336         ///   This is a wrapper around StreamReader which is seekable.
337         /// </summary>
338         public class SeekableStreamReader
339         {
340                 public SeekableStreamReader (StreamReader reader)
341                 {
342                         this.reader = reader;
343                         this.buffer = new char [DefaultCacheSize];
344                         
345                         // Compute the preamble size
346                         
347                         // Let the StreamWriter autodetect the encoder
348                         reader.Peek ();
349                         
350                         reader.BaseStream.Position = 0;
351                         Encoding enc = reader.CurrentEncoding;
352                         // First of all, get at least a char
353                         
354                         byte[] auxb = new byte [50];
355                         int num_bytes = 0;
356                         int num_chars = 0;
357                         int br = 0;
358                         do {
359                                 br = reader.BaseStream.Read (auxb, num_bytes, auxb.Length - num_bytes);
360                                 num_bytes += br;
361                                 num_chars = enc.GetCharCount (auxb, 0, num_bytes);
362                         }
363                         while (num_chars == 0 && br > 0);
364                         
365                         if (num_chars != 0)
366                         {
367                                 // Now, check which bytes at the beginning have no effect in the
368                                 // char count
369                                 
370                                 int p = 0;
371                                 while (enc.GetCharCount (auxb, p, num_bytes-p) >= num_chars)
372                                         p++;
373                                 
374                                 preamble_size = p - 1;
375                                 reader.BaseStream.Position = 0;
376                                 reader.DiscardBufferedData ();
377                                 
378                                 buffer_start = preamble_size;
379                         }
380                 }
381
382                 public SeekableStreamReader (Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
383                         : this (new StreamReader (stream, encoding, detect_encoding_from_bytemarks))
384                 { }
385
386                 StreamReader reader;
387
388                 private const int DefaultCacheSize = 1024;
389
390                 char[] buffer;
391                 int buffer_start;       // in bytes
392                 int buffer_size;        // in bytes
393                 int char_count;         // count buffer[] valid characters
394                 int pos;                // index into buffer[]
395                 int preamble_size;
396
397                 /// <remarks>
398                 ///   The difference to the StreamReader's BaseStream.Position is that this one is reliable; ie. it
399                 //    always reports the correct position and if it's modified, it also takes care of the buffered data.
400                 /// </remarks>
401                 public int Position {
402                         get {
403                                 return buffer_start + reader.CurrentEncoding.GetByteCount (buffer, 0, pos);
404                         }
405
406                         set {
407                                 // This one is easy: we're modifying the position within our current
408                                 // buffer.
409                                 if ((value >= buffer_start) && (value < buffer_start + buffer_size)) {
410                                         int byte_offset = value - buffer_start;
411                                         pos = byte_offset;
412                                         // encoded characters can take more than 1 byte length
413                                         while (reader.CurrentEncoding.GetByteCount (buffer, 0, pos) > byte_offset)
414                                                 pos--;
415                                         
416                                         return;
417                                 }
418                                 
419                                 if (value == 0) // Skip preamble
420                                         value = preamble_size;
421
422                                 // Ok, now we need to seek.
423                                 reader.DiscardBufferedData ();
424                                 reader.BaseStream.Position = buffer_start = value;
425                                 char_count = buffer_size = pos = 0;
426                         }
427                 }
428
429                 private bool ReadBuffer ()
430                 {
431                         pos = 0;
432                         buffer_start += buffer_size;
433                         char_count = reader.Read (buffer, 0, buffer.Length);
434                         buffer_size = reader.CurrentEncoding.GetByteCount (buffer, 0, char_count);
435                         return buffer_size > 0;
436                 }
437
438                 public int Peek ()
439                 {
440                         if ((pos >= char_count) && !ReadBuffer ())
441                                 return -1;
442
443                         return buffer [pos];
444                 }
445
446                 public int Read ()
447                 {
448                         if ((pos >= char_count) && !ReadBuffer ())
449                                 return -1;
450
451                         return buffer [pos++];
452                 }
453         }
454
455         public class DoubleHash {
456                 const int DEFAULT_INITIAL_BUCKETS = 100;
457                 
458                 public DoubleHash () : this (DEFAULT_INITIAL_BUCKETS) {}
459                 
460                 public DoubleHash (int size)
461                 {
462                         count = size;
463                         buckets = new Entry [size];
464                 }
465                 
466                 int count;
467                 Entry [] buckets;
468                 int size = 0;
469                 
470                 class Entry {
471                         public object key1;
472                         public object key2;
473                         public int hash;
474                         public object value;
475                         public Entry next;
476         
477                         public Entry (object key1, object key2, int hash, object value, Entry next)
478                         {
479                                 this.key1 = key1;
480                                 this.key2 = key2;
481                                 this.hash = hash;
482                                 this.next = next;
483                                 this.value = value;
484                         }
485                 }
486
487                 public bool Lookup (object a, object b, out object res)
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                                         res = e.value;
494                                         return true;
495                                 }
496                         }
497                         res = null;
498                         return false;
499                 }
500
501                 public void Insert (object a, object b, object value)
502                 {
503                         // Is it an existing one?
504                 
505                         int h = (a.GetHashCode () ^ b.GetHashCode ()) & 0x7FFFFFFF;
506                         
507                         for (Entry e = buckets [h % count]; e != null; e = e.next) {
508                                 if (e.hash == h && e.key1.Equals (a) && e.key2.Equals (b))
509                                         e.value = value;
510                         }
511                         
512                         int bucket = h % count;
513                         buckets [bucket] = new Entry (a, b, h, value, buckets [bucket]);
514                         
515                         // Grow whenever we double in size
516                         if (size++ == count) {
517                                 count <<= 1;
518                                 count ++;
519                                 
520                                 Entry [] newBuckets = new Entry [count];
521                                 foreach (Entry root in buckets) {
522                                         Entry e = root;
523                                         while (e != null) {
524                                                 int newLoc = e.hash % count;
525                                                 Entry n = e.next;
526                                                 e.next = newBuckets [newLoc];
527                                                 newBuckets [newLoc] = e;
528                                                 e = n;
529                                         }
530                                 }
531
532                                 buckets = newBuckets;
533                         }
534                 }
535         }
536 }