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