2 // enum.cs: Enum handling.
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Ravi Pratap (ravi@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
13 using System.Collections;
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
18 namespace Mono.CSharp {
20 class EnumMember: Attributable {
25 static string[] attribute_targets = new string [] { "field" };
27 public FieldBuilder builder;
29 public EnumMember (string name, Enum parent, Location loc, Attributes attrs):
37 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
39 if (a.Type == TypeManager.marshal_as_attr_type) {
40 UnmanagedMarshal marshal = a.GetMarshal ();
41 if (marshal != null) {
42 builder.SetMarshal (marshal);
45 Report.Warning_T (-24, a.Location);
49 builder.SetCustomAttribute (cb);
52 public override AttributeTargets AttributeTargets {
54 return AttributeTargets.Field;
58 public override bool IsClsCompliaceRequired(DeclSpace ds)
60 return parent.IsClsCompliaceRequired (ds);
63 public void DefineMember (TypeBuilder tb)
65 FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
66 | FieldAttributes.Literal;
68 builder = tb.DefineField (name, tb, attr);
71 public void Emit (EmitContext ec)
73 if (OptAttributes != null)
74 OptAttributes.Emit (ec, this);
77 protected override string[] ValidAttributeTargets {
79 return attribute_targets;
85 /// Enumeration container
87 public class Enum : DeclSpace {
88 ArrayList ordered_enums;
90 public Expression BaseType;
92 public Type UnderlyingType;
94 Hashtable member_to_location;
95 Hashtable member_to_attributes;
98 // This is for members that have been defined
100 Hashtable member_to_value;
103 // This is used to mark members we're currently defining
105 Hashtable in_transit;
107 ArrayList field_builders;
110 Hashtable name_to_member;
112 public const int AllowedModifiers =
115 Modifiers.PROTECTED |
119 public Enum (NamespaceEntry ns, TypeContainer parent, Expression type, int mod_flags,
120 string name, Attributes attrs, Location l)
121 : base (ns, parent, name, attrs, l)
123 this.BaseType = type;
124 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
125 IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, l);
127 ordered_enums = new ArrayList ();
128 member_to_location = new Hashtable ();
129 member_to_value = new Hashtable ();
130 in_transit = new Hashtable ();
131 field_builders = new ArrayList ();
133 name_to_member = new Hashtable ();
137 /// Adds @name to the enumeration space, with @expr
138 /// being its definition.
140 public AdditionResult AddEnumMember (string name, Expression expr, Location loc,
141 Attributes opt_attrs)
143 if (defined_names.Contains (name))
144 return AdditionResult.NameExists;
146 if (name == "value__") {
147 Report.Error (76, loc, "An item in an enumeration can't have an identifier `value__'");
148 return AdditionResult.Error;
151 DefineName (name, expr);
153 ordered_enums.Add (name);
154 member_to_location.Add (name, loc);
156 if (member_to_attributes == null)
157 member_to_attributes = new Hashtable ();
159 member_to_attributes.Add (name, opt_attrs);
161 name_to_member.Add (name, new EnumMember (name, this, loc, opt_attrs));
163 return AdditionResult.Success;
167 // This is used by corlib compilation: we map from our
168 // type to a type that is consumable by the DefineField
170 Type MapToInternalType (Type t)
172 if (t == TypeManager.int32_type)
174 if (t == TypeManager.int64_type)
175 return typeof (long);
176 if (t == TypeManager.uint32_type)
177 return typeof (uint);
178 if (t == TypeManager.uint64_type)
179 return typeof (ulong);
180 if (t == TypeManager.float_type)
181 return typeof (float);
182 if (t == TypeManager.double_type)
183 return typeof (double);
184 if (t == TypeManager.byte_type)
185 return typeof (byte);
186 if (t == TypeManager.sbyte_type)
187 return typeof (sbyte);
188 if (t == TypeManager.char_type)
189 return typeof (char);
190 if (t == TypeManager.short_type)
191 return typeof (short);
192 if (t == TypeManager.ushort_type)
193 return typeof (ushort);
195 throw new Exception ();
198 public override TypeBuilder DefineType ()
200 if (TypeBuilder != null)
203 TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel);
205 attr |= TypeAttributes.Class | TypeAttributes.Sealed;
207 if (!(BaseType is TypeLookupExpression)) {
208 Report.Error (1008, Location,
209 "Type byte, sbyte, short, ushort, int, uint, " +
210 "long, or ulong expected (got: `{0}')", BaseType);
214 UnderlyingType = ResolveType (BaseType, false, Location);
216 if (UnderlyingType != TypeManager.int32_type &&
217 UnderlyingType != TypeManager.uint32_type &&
218 UnderlyingType != TypeManager.int64_type &&
219 UnderlyingType != TypeManager.uint64_type &&
220 UnderlyingType != TypeManager.short_type &&
221 UnderlyingType != TypeManager.ushort_type &&
222 UnderlyingType != TypeManager.byte_type &&
223 UnderlyingType != TypeManager.sbyte_type) {
224 Report.Error (1008, Location,
225 "Type byte, sbyte, short, ushort, int, uint, " +
226 "long, or ulong expected (got: " +
227 TypeManager.CSharpName (UnderlyingType) + ")");
232 if (TypeManager.NamespaceClash (Name, Location))
235 ModuleBuilder builder = CodeGen.Module.Builder;
237 TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
239 TypeBuilder builder = Parent.TypeBuilder;
241 TypeBuilder = builder.DefineNestedType (
242 Basename, attr, TypeManager.enum_type);
246 // Call MapToInternalType for corlib
248 TypeBuilder.DefineField ("value__", UnderlyingType,
249 FieldAttributes.Public | FieldAttributes.SpecialName
250 | FieldAttributes.RTSpecialName);
252 TypeManager.AddEnumType (Name, TypeBuilder, this);
257 bool IsValidEnumConstant (Expression e)
259 if (!(e is Constant))
262 if (e is IntConstant || e is UIntConstant || e is LongConstant ||
263 e is ByteConstant || e is SByteConstant || e is ShortConstant ||
264 e is UShortConstant || e is ULongConstant || e is EnumConstant ||
271 object GetNextDefaultValue (object default_value)
273 if (UnderlyingType == TypeManager.int32_type) {
274 int i = (int) default_value;
276 if (i < System.Int32.MaxValue)
280 } else if (UnderlyingType == TypeManager.uint32_type) {
281 uint i = (uint) default_value;
283 if (i < System.UInt32.MaxValue)
287 } else if (UnderlyingType == TypeManager.int64_type) {
288 long i = (long) default_value;
290 if (i < System.Int64.MaxValue)
294 } else if (UnderlyingType == TypeManager.uint64_type) {
295 ulong i = (ulong) default_value;
297 if (i < System.UInt64.MaxValue)
301 } else if (UnderlyingType == TypeManager.short_type) {
302 short i = (short) default_value;
304 if (i < System.Int16.MaxValue)
308 } else if (UnderlyingType == TypeManager.ushort_type) {
309 ushort i = (ushort) default_value;
311 if (i < System.UInt16.MaxValue)
315 } else if (UnderlyingType == TypeManager.byte_type) {
316 byte i = (byte) default_value;
318 if (i < System.Byte.MaxValue)
322 } else if (UnderlyingType == TypeManager.sbyte_type) {
323 sbyte i = (sbyte) default_value;
325 if (i < System.SByte.MaxValue)
334 void Error_ConstantValueCannotBeConverted (object val, Location loc)
337 Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
338 "' cannot be converted" +
339 " to a " + TypeManager.CSharpName (UnderlyingType));
341 Report.Error (31, loc, "Constant value '" + val +
342 "' cannot be converted" +
343 " to a " + TypeManager.CSharpName (UnderlyingType));
348 /// Determines if a standard implicit conversion exists from
349 /// expr_type to target_type
351 public static bool ImplicitConversionExists (Type expr_type, Type target_type)
353 expr_type = TypeManager.TypeToCoreType (expr_type);
355 if (expr_type == TypeManager.void_type)
358 if (expr_type == target_type)
361 // First numeric conversions
363 if (expr_type == TypeManager.sbyte_type){
365 // From sbyte to short, int, long, float, double.
367 if ((target_type == TypeManager.int32_type) ||
368 (target_type == TypeManager.int64_type) ||
369 (target_type == TypeManager.double_type) ||
370 (target_type == TypeManager.float_type) ||
371 (target_type == TypeManager.short_type) ||
372 (target_type == TypeManager.decimal_type))
375 } else if (expr_type == TypeManager.byte_type){
377 // From byte to short, ushort, int, uint, long, ulong, float, double
379 if ((target_type == TypeManager.short_type) ||
380 (target_type == TypeManager.ushort_type) ||
381 (target_type == TypeManager.int32_type) ||
382 (target_type == TypeManager.uint32_type) ||
383 (target_type == TypeManager.uint64_type) ||
384 (target_type == TypeManager.int64_type) ||
385 (target_type == TypeManager.float_type) ||
386 (target_type == TypeManager.double_type) ||
387 (target_type == TypeManager.decimal_type))
390 } else if (expr_type == TypeManager.short_type){
392 // From short to int, long, float, double
394 if ((target_type == TypeManager.int32_type) ||
395 (target_type == TypeManager.int64_type) ||
396 (target_type == TypeManager.double_type) ||
397 (target_type == TypeManager.float_type) ||
398 (target_type == TypeManager.decimal_type))
401 } else if (expr_type == TypeManager.ushort_type){
403 // From ushort to int, uint, long, ulong, float, double
405 if ((target_type == TypeManager.uint32_type) ||
406 (target_type == TypeManager.uint64_type) ||
407 (target_type == TypeManager.int32_type) ||
408 (target_type == TypeManager.int64_type) ||
409 (target_type == TypeManager.double_type) ||
410 (target_type == TypeManager.float_type) ||
411 (target_type == TypeManager.decimal_type))
414 } else if (expr_type == TypeManager.int32_type){
416 // From int to long, float, double
418 if ((target_type == TypeManager.int64_type) ||
419 (target_type == TypeManager.double_type) ||
420 (target_type == TypeManager.float_type) ||
421 (target_type == TypeManager.decimal_type))
424 } else if (expr_type == TypeManager.uint32_type){
426 // From uint to long, ulong, float, double
428 if ((target_type == TypeManager.int64_type) ||
429 (target_type == TypeManager.uint64_type) ||
430 (target_type == TypeManager.double_type) ||
431 (target_type == TypeManager.float_type) ||
432 (target_type == TypeManager.decimal_type))
435 } else if ((expr_type == TypeManager.uint64_type) ||
436 (expr_type == TypeManager.int64_type)) {
438 // From long/ulong to float, double
440 if ((target_type == TypeManager.double_type) ||
441 (target_type == TypeManager.float_type) ||
442 (target_type == TypeManager.decimal_type))
445 } else if (expr_type == TypeManager.char_type){
447 // From char to ushort, int, uint, long, ulong, float, double
449 if ((target_type == TypeManager.ushort_type) ||
450 (target_type == TypeManager.int32_type) ||
451 (target_type == TypeManager.uint32_type) ||
452 (target_type == TypeManager.uint64_type) ||
453 (target_type == TypeManager.int64_type) ||
454 (target_type == TypeManager.float_type) ||
455 (target_type == TypeManager.double_type) ||
456 (target_type == TypeManager.decimal_type))
459 } else if (expr_type == TypeManager.float_type){
463 if (target_type == TypeManager.double_type)
471 // Horrible, horrible. But there is no other way we can pass the EmitContext
472 // to the recursive definition triggered by the evaluation of a forward
475 static EmitContext current_ec = null;
478 /// This is used to lookup the value of an enum member. If the member is undefined,
479 /// it attempts to define it and return its value
481 public object LookupEnumValue (EmitContext ec, string name, Location loc)
484 object default_value = null;
487 default_value = member_to_value [name];
489 if (default_value != null)
490 return default_value;
493 // This may happen if we're calling a method in System.Enum, for instance
496 if (!defined_names.Contains (name))
499 if (in_transit.Contains (name)) {
500 Report.Error (110, loc, "The evaluation of the constant value for `" +
501 Name + "." + name + "' involves a circular definition.");
506 // So if the above doesn't happen, we have a member that is undefined
507 // We now proceed to define it
509 Expression val = this [name];
513 int idx = ordered_enums.IndexOf (name);
518 for (int i = 0; i < idx; ++i) {
519 string n = (string) ordered_enums [i];
520 Location m_loc = (Mono.CSharp.Location)
521 member_to_location [n];
522 in_transit.Add (name, true);
524 EmitContext old_ec = current_ec;
527 default_value = LookupEnumValue (ec, n, m_loc);
531 in_transit.Remove (name);
532 if (default_value == null)
536 default_value = GetNextDefaultValue (default_value);
540 bool old = ec.InEnumContext;
541 ec.InEnumContext = true;
542 in_transit.Add (name, true);
544 EmitContext old_ec = current_ec;
546 val = val.Resolve (ec);
549 in_transit.Remove (name);
550 ec.InEnumContext = old;
555 if (!IsValidEnumConstant (val)) {
558 "Type byte, sbyte, short, ushort, int, uint, long, or " +
559 "ulong expected (have: " + val + ")");
564 default_value = c.GetValue ();
566 if (default_value == null) {
567 Error_ConstantValueCannotBeConverted (c, loc);
571 if (val is EnumConstant){
572 Type etype = TypeManager.EnumToUnderlying (c.Type);
574 if (!ImplicitConversionExists (etype, UnderlyingType)){
575 Convert.Error_CannotImplicitConversion (
576 loc, c.Type, UnderlyingType);
582 EnumMember em = name_to_member [name] as EnumMember;
583 em.DefineMember (TypeBuilder);
586 default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
588 Error_ConstantValueCannotBeConverted (c, loc);
592 em.builder.SetConstant (default_value);
593 field_builders.Add (em.builder);
594 member_to_value [name] = default_value;
596 if (!TypeManager.RegisterFieldValue (em.builder, default_value))
599 return default_value;
602 public override bool DefineMembers (TypeContainer parent)
607 public override bool Define (TypeContainer parent)
610 // If there was an error during DefineEnum, return
612 if (TypeBuilder == null)
615 EmitContext ec = new EmitContext (this, this, Location, null,
616 UnderlyingType, ModFlags, false);
619 object default_value = 0;
622 foreach (string name in ordered_enums) {
624 // Have we already been defined, thanks to some cross-referencing ?
626 if (member_to_value.Contains (name))
629 Location loc = (Mono.CSharp.Location) member_to_location [name];
631 if (this [name] != null) {
632 default_value = LookupEnumValue (ec, name, loc);
634 if (default_value == null)
637 if (name == "value__"){
638 Report.Error (76, loc, "The name `value__' is reserved for enumerations");
642 EnumMember em = name_to_member [name] as EnumMember;
644 em.DefineMember (TypeBuilder);
645 FieldBuilder fb = em.builder;
647 if (default_value == null) {
648 Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
654 default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
656 Error_ConstantValueCannotBeConverted (default_value, loc);
660 fb.SetConstant (default_value);
661 field_builders.Add (fb);
662 member_to_value [name] = default_value;
664 if (!TypeManager.RegisterFieldValue (fb, default_value))
668 default_value = GetNextDefaultValue (default_value);
673 public override void Emit (TypeContainer tc)
675 EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
677 if (OptAttributes != null) {
678 OptAttributes.Emit (ec, this);
681 foreach (EnumMember em in name_to_member.Values) {
688 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
690 if (!base.IsIdentifierClsCompliant (ds))
693 for (int i = 1; i < ordered_enums.Count; ++i) {
694 string checked_name = ordered_enums [i] as string;
695 for (int ii = 0; ii < ordered_enums.Count; ++ii) {
699 string enumerator_name = ordered_enums [ii] as string;
700 if (String.Compare (checked_name, enumerator_name, true, CultureInfo.InvariantCulture) == 0) {
701 Report.SymbolRelatedToPreviousError ((Location)member_to_location [enumerator_name], enumerator_name);
702 Report.Error_T (3005, (Location)member_to_location [checked_name], GetEnumeratorName (checked_name));
710 protected override bool VerifyClsCompliance (DeclSpace ds)
712 if (!base.VerifyClsCompliance (ds))
715 if (!AttributeTester.IsClsCompliant (UnderlyingType)) {
716 Report.Error_T (3009, Location, GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
723 /// Returns full enum name.
725 string GetEnumeratorName (string valueName)
727 return String.Concat (Name, ".", valueName);
733 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
734 MemberFilter filter, object criteria)
736 ArrayList members = new ArrayList ();
738 if ((mt & MemberTypes.Field) != 0) {
739 if (criteria is string){
740 if (member_to_value [criteria] == null && current_ec != null){
741 LookupEnumValue (current_ec, (string) criteria, Location.Null);
745 foreach (FieldBuilder fb in field_builders)
746 if (filter (fb, criteria) == true)
750 return new MemberList (members);
753 public override MemberCache MemberCache {
759 public ArrayList ValueNames {
761 return ordered_enums;
766 public Expression this [string name] {
768 return (Expression) defined_names [name];
772 public override AttributeTargets AttributeTargets {
774 return AttributeTargets.Enum;