2002-06-07 Rafael Teixeira <rafaelteixeirabr@hotmail.com>
[mono.git] / mcs / mbas / enum.cs
1 //
2 // enum.cs: Enum handling.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11
12 using System;
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16
17 namespace Mono.CSharp {
18
19         /// <summary>
20         ///   Enumeration container
21         /// </summary>
22         public class Enum : DeclSpace {
23
24                 ArrayList ordered_enums;
25                 public readonly string BaseType;
26                 public Attributes  OptAttributes;
27                 
28                 public Type UnderlyingType;
29
30                 Hashtable member_to_location;
31
32                 //
33                 // This is for members that have been defined
34                 //
35                 Hashtable member_to_value;
36                 
37                 ArrayList field_builders;
38                 
39                 public const int AllowedModifiers =
40                         Modifiers.NEW |
41                         Modifiers.PUBLIC |
42                         Modifiers.PROTECTED |
43                         Modifiers.INTERNAL |
44                         Modifiers.PRIVATE;
45
46                 public Enum (TypeContainer parent, string type, int mod_flags, string name, Attributes attrs, Location l)
47                         : base (parent, name, l)
48                 {
49                         this.BaseType = type;
50                         ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC, l);
51                         OptAttributes = attrs;
52
53                         ordered_enums = new ArrayList ();
54                         member_to_location = new Hashtable ();
55                         member_to_value = new Hashtable ();
56                         field_builders = new ArrayList ();
57                 }
58
59                 /// <summary>
60                 ///   Adds @name to the enumeration space, with @expr
61                 ///   being its definition.  
62                 /// </summary>
63                 public AdditionResult AddEnumMember (string name, Expression expr, Location loc)
64                 {
65                         if (defined_names.Contains (name))
66                                 return AdditionResult.NameExists;
67
68                         DefineName (name, expr);
69
70                         ordered_enums.Add (name);
71                         member_to_location.Add (name, loc);
72                         
73                         return AdditionResult.Success;
74                 }
75
76                 //
77                 // This is used by corlib compilation: we map from our
78                 // type to a type that is consumable by the DefineField
79                 //
80                 Type MapToInternalType (Type t)
81                 {
82                         if (t == TypeManager.int32_type)
83                                 return typeof (int);
84                         if (t == TypeManager.int64_type)
85                                 return typeof (long);
86                         if (t == TypeManager.uint32_type)
87                                 return typeof (uint);
88                         if (t == TypeManager.uint64_type)
89                                 return typeof (ulong);
90                         if (t == TypeManager.float_type)
91                                 return typeof (float);
92                         if (t == TypeManager.double_type)
93                                 return typeof (double);
94                         if (t == TypeManager.byte_type)
95                                 return typeof (byte);
96                         if (t == TypeManager.sbyte_type)
97                                 return typeof (sbyte);
98                         if (t == TypeManager.char_type)
99                                 return typeof (char);
100                         if (t == TypeManager.short_type)
101                                 return typeof (short);
102                         if (t == TypeManager.ushort_type)
103                                 return typeof (ushort);
104
105                         throw new Exception ();
106                 }
107                 
108                 public override TypeBuilder DefineType ()
109                 {
110                         if (TypeBuilder != null)
111                                 return TypeBuilder;
112
113                         TypeAttributes attr = TypeAttributes.Class | TypeAttributes.Sealed;
114
115                         UnderlyingType = TypeManager.LookupType (BaseType);
116
117                         if (UnderlyingType != TypeManager.int32_type &&
118                             UnderlyingType != TypeManager.uint32_type &&
119                             UnderlyingType != TypeManager.int64_type &&
120                             UnderlyingType != TypeManager.uint64_type &&
121                             UnderlyingType != TypeManager.short_type &&
122                             UnderlyingType != TypeManager.ushort_type &&
123                             UnderlyingType != TypeManager.byte_type  &&
124                             UnderlyingType != TypeManager.sbyte_type) {
125                                 Report.Error (1008, Location,
126                                               "Type byte, sbyte, short, ushort, int, uint, " +
127                                               "long, or ulong expected (got: " +
128                                               TypeManager.CSharpName (UnderlyingType) + ")");
129                                 return null;
130                         }
131
132                         if (IsTopLevel) {
133                                 ModuleBuilder builder = CodeGen.ModuleBuilder;
134
135                                 if ((ModFlags & Modifiers.PUBLIC) != 0)
136                                         attr |= TypeAttributes.Public;
137                                 else
138                                         attr |= TypeAttributes.NotPublic;
139                                 
140                                 TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
141                         } else {
142                                 TypeBuilder builder = Parent.TypeBuilder;
143
144                                 if ((ModFlags & Modifiers.PUBLIC) != 0)
145                                         attr |= TypeAttributes.NestedPublic;
146                                 else
147                                         attr |= TypeAttributes.NestedPrivate;
148
149                                 
150                                 TypeBuilder = builder.DefineNestedType (
151                                         Basename, attr, TypeManager.enum_type);
152                         }
153
154                         //
155                         // Call MapToInternalType for corlib
156                         //
157                         TypeBuilder.DefineField ("value__", UnderlyingType,
158                                                  FieldAttributes.Public | FieldAttributes.SpecialName
159                                                  | FieldAttributes.RTSpecialName);
160
161                         TypeManager.AddEnumType (Name, TypeBuilder, this);
162
163                         return TypeBuilder;
164                 }
165
166                 bool IsValidEnumConstant (Expression e)
167                 {
168                         if (!(e is Constant))
169                                 return false;
170
171                         if (e is IntConstant || e is UIntConstant || e is LongConstant ||
172                             e is ByteConstant || e is SByteConstant || e is ShortConstant ||
173                             e is UShortConstant || e is ULongConstant || e is EnumConstant)
174                                 return true;
175                         else
176                                 return false;
177                 }
178
179                 object GetNextDefaultValue (object default_value)
180                 {
181                         if (UnderlyingType == TypeManager.int32_type) {
182                                 int i = (int) default_value;
183                                 
184                                 if (i < System.Int32.MaxValue)
185                                         return ++i;
186                                 else
187                                         return null;
188                         } else if (UnderlyingType == TypeManager.uint32_type) {
189                                 uint i = (uint) default_value;
190
191                                 if (i < System.UInt32.MaxValue)
192                                         return ++i;
193                                 else
194                                         return null;
195                         } else if (UnderlyingType == TypeManager.int64_type) {
196                                 long i = (long) default_value;
197
198                                 if (i < System.Int64.MaxValue)
199                                         return ++i;
200                                 else
201                                         return null;
202                         } else if (UnderlyingType == TypeManager.uint64_type) {
203                                 ulong i = (ulong) default_value;
204
205                                 if (i < System.UInt64.MaxValue)
206                                         return ++i;
207                                 else
208                                         return null;
209                         } else if (UnderlyingType == TypeManager.short_type) {
210                                 short i = (short) default_value;
211
212                                 if (i < System.Int16.MaxValue)
213                                         return ++i;
214                                 else
215                                         return null;
216                         } else if (UnderlyingType == TypeManager.ushort_type) {
217                                 ushort i = (ushort) default_value;
218
219                                 if (i < System.UInt16.MaxValue)
220                                         return ++i;
221                                 else
222                                         return null;
223                         } else if (UnderlyingType == TypeManager.byte_type) {
224                                 byte i = (byte) default_value;
225
226                                 if (i < System.Byte.MaxValue)
227                                         return ++i;
228                                 else
229                                         return null;
230                         } else if (UnderlyingType == TypeManager.sbyte_type) {
231                                 sbyte i = (sbyte) default_value;
232
233                                 if (i < System.SByte.MaxValue)
234                                         return ++i;
235                                 else
236                                         return null;
237                         }
238
239                         return null;
240                 }
241
242                 void Error_ConstantValueCannotBeConverted (object val, Location loc)
243                 {
244                         if (val is Constant)
245                                 Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
246                                               "' cannot be converted" +
247                                               " to a " + TypeManager.CSharpName (UnderlyingType));
248                         else 
249                                 Report.Error (31, loc, "Constant value '" + val +
250                                               "' cannot be converted" +
251                                               " to a " + TypeManager.CSharpName (UnderlyingType));
252                         return;
253                 }
254
255                 /// <summary>
256                 ///  This is used to lookup the value of an enum member. If the member is undefined,
257                 ///  it attempts to define it and return its value
258                 /// </summary>
259                 public object LookupEnumValue (EmitContext ec, string name, Location loc)
260                 {
261                         object default_value = null;
262                         Constant c = null;
263
264                         default_value = member_to_value [name];
265
266                         if (default_value != null)
267                                 return default_value;
268
269                         //
270                         // This may happen if we're calling a method in System.Enum, for instance
271                         // Enum.IsDefined().
272                         //
273                         if (!defined_names.Contains (name))
274                                 return null;
275
276                         //
277                         // So if the above doesn't happen, we have a member that is undefined
278                         // We now proceed to define it 
279                         //
280                         Expression val = this [name];
281
282                         if (val == null) {
283                                 
284                                 int idx = ordered_enums.IndexOf (name);
285
286                                 if (idx == 0)
287                                         default_value = 0;
288                                 else {
289                                         for (int i = 0; i < idx; ++i) {
290                                                 string n = (string) ordered_enums [i];
291                                                 Location m_loc = (Mono.CSharp.Location)
292                                                         member_to_location [n];
293                                                 default_value = LookupEnumValue (ec, n, m_loc);
294                                         }
295                                         
296                                         default_value = GetNextDefaultValue (default_value);
297                                 }
298                                 
299                         } else {
300                                 bool old = ec.InEnumContext;
301                                 ec.InEnumContext = true;
302                                 val = val.Resolve (ec);
303                                 ec.InEnumContext = old;
304                                 
305                                 if (val == null) {
306                                         Report.Error (-12, loc, "Definition is circular.");
307                                         return null;
308                                 }
309
310                                 if (IsValidEnumConstant (val)) {
311                                         c = (Constant) val;
312                                         default_value = c.GetValue ();
313                                         
314                                         if (default_value == null) {
315                                                 Error_ConstantValueCannotBeConverted (c, loc);
316                                                 return null;
317                                         }
318                                         
319                                 } else {
320                                         Report.Error (
321                                                 1008, loc,
322                                                 "Type byte, sbyte, short, ushort, int, uint, long, or " +
323                                                 "ulong expected (have: " + val + ")");
324                                         return null;
325                                 }
326                         }
327
328                         FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
329                                         | FieldAttributes.Literal;
330                         
331                         FieldBuilder fb = TypeBuilder.DefineField (name, UnderlyingType, attr);
332
333                         try {
334                                 default_value = TypeManager.ChangeType (default_value, UnderlyingType);
335                         } catch {
336                                 Error_ConstantValueCannotBeConverted (c, loc);
337                                 return null;
338                         }
339
340                         fb.SetConstant (default_value);
341                         field_builders.Add (fb);
342                         member_to_value [name] = default_value;
343
344                         if (!TypeManager.RegisterFieldValue (fb, default_value))
345                                 return null;
346                         
347                         return default_value;
348                 }
349                 
350                 public override bool Define (TypeContainer parent)
351                 {
352                         //
353                         // If there was an error during DefineEnum, return
354                         //
355                         if (TypeBuilder == null)
356                                 return false;
357                         
358                         EmitContext ec = new EmitContext (parent, this, Location, null,
359                                                           UnderlyingType, ModFlags, false);
360                         
361                         object default_value = 0;
362                         
363                         FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
364                                              | FieldAttributes.Literal;
365
366                         
367                         foreach (string name in ordered_enums) {
368                                 //
369                                 // Have we already been defined, thanks to some cross-referencing ?
370                                 // 
371                                 if (member_to_value.Contains (name))
372                                         continue;
373                                 
374                                 Location loc = (Mono.CSharp.Location) member_to_location [name];
375
376                                 if (this [name] != null) {
377                                         default_value = LookupEnumValue (ec, name, loc);
378
379                                         if (default_value == null)
380                                                 return true;
381
382                                 } else {
383                                         FieldBuilder fb = TypeBuilder.DefineField (
384                                                 name, UnderlyingType, attr);
385                                         
386                                         if (default_value == null) {
387                                            Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
388                                                               "fit in its type");
389                                                 return false;
390                                         }
391                                         
392                                         try {
393                                                 default_value = TypeManager.ChangeType (default_value, UnderlyingType);
394                                         } catch {
395                                                 Error_ConstantValueCannotBeConverted (default_value, loc);
396                                                 return false;
397                                         }
398
399                                         fb.SetConstant (default_value);
400                                         field_builders.Add (fb);
401                                         member_to_value [name] = default_value;
402                                         
403                                         if (!TypeManager.RegisterFieldValue (fb, default_value))
404                                                 return false;
405                                 }
406
407                                 default_value = GetNextDefaultValue (default_value);
408                         }
409                         
410                         Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes, Location);
411
412                         return true;
413                 }
414                 
415                 //
416                 // Hack around System.Reflection as found everywhere else
417                 //
418                 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf,
419                                                   MemberFilter filter, object criteria)
420                 {
421                         ArrayList members = new ArrayList ();
422
423                         if ((mt & MemberTypes.Field) != 0) {
424                                 foreach (FieldBuilder fb in field_builders)
425                                         if (filter (fb, criteria) == true)
426                                                 members.Add (fb);
427                         }
428
429                         int count = members.Count;
430
431                         if (count > 0) {
432                                 MemberInfo [] mi = new MemberInfo [count];
433                                 members.CopyTo (mi, 0);
434                                 return mi;
435                         }
436
437                         return null;
438                 }
439
440                 public ArrayList ValueNames {
441                         get {
442                                 return ordered_enums;
443                         }
444                 }
445
446                 // indexer
447                 public Expression this [string name] {
448                         get {
449                                 return (Expression) defined_names [name];
450                         }
451                 }
452         }
453 }