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: MemberCore {
21 static string[] attribute_targets = new string [] { "field" };
24 public FieldBuilder builder;
25 internal readonly Expression Type;
27 public EnumMember (Enum parent_enum, Expression expr, string name,
28 Location loc, Attributes attrs):
29 base (null, new MemberName (name), attrs, loc)
31 this.parent_enum = parent_enum;
32 this.ModFlags = parent_enum.ModFlags;
36 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
38 if (a.Type == TypeManager.marshal_as_attr_type) {
39 UnmanagedMarshal marshal = a.GetMarshal (this);
40 if (marshal != null) {
41 builder.SetMarshal (marshal);
46 if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
47 a.Error_InvalidSecurityParent ();
51 builder.SetCustomAttribute (cb);
54 public override AttributeTargets AttributeTargets {
56 return AttributeTargets.Field;
60 public void DefineMember (TypeBuilder tb)
62 FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
63 | FieldAttributes.Literal;
65 builder = tb.DefineField (Name, tb, attr);
68 public override bool Define ()
70 throw new NotImplementedException ();
73 public void Emit (EmitContext ec)
75 if (OptAttributes != null)
76 OptAttributes.Emit (ec, this);
81 public override string GetSignatureForError()
83 return String.Concat (parent_enum.GetSignatureForError (), '.', base.GetSignatureForError ());
86 public override string[] ValidAttributeTargets {
88 return attribute_targets;
92 protected override bool VerifyClsCompliance(DeclSpace ds)
94 // Because parent is TypeContainer and we have only DeclSpace parent.
95 // Parameter replacing is required
96 return base.VerifyClsCompliance (parent_enum);
99 // There is no base type
100 protected override void VerifyObsoleteAttribute()
106 /// Enumeration container
108 public class Enum : DeclSpace {
109 ArrayList ordered_enums;
111 public Expression BaseType;
113 public Type UnderlyingType;
115 Hashtable member_to_location;
118 // This is for members that have been defined
120 Hashtable member_to_value;
123 // This is used to mark members we're currently defining
125 Hashtable in_transit;
127 ArrayList field_builders;
129 public const int AllowedModifiers =
132 Modifiers.PROTECTED |
136 public Enum (NamespaceEntry ns, TypeContainer parent, Expression type,
137 int mod_flags, MemberName name, Attributes attrs, Location l)
138 : base (ns, parent, name, attrs, l)
140 this.BaseType = type;
141 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
142 IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, l);
144 ordered_enums = new ArrayList ();
145 member_to_location = new Hashtable ();
146 member_to_value = new Hashtable ();
147 in_transit = new Hashtable ();
148 field_builders = new ArrayList ();
152 /// Adds @name to the enumeration space, with @expr
153 /// being its definition.
155 public void AddEnumMember (string name, Expression expr, Location loc, Attributes opt_attrs)
157 if (name == "value__") {
158 Report.Error (76, loc, "An item in an enumeration can't have an identifier `value__'");
162 EnumMember em = new EnumMember (this, expr, name, loc, opt_attrs);
163 if (!AddToContainer (em, false, name, ""))
167 // TODO: can be almost deleted
168 ordered_enums.Add (name);
169 member_to_location.Add (name, loc);
173 // This is used by corlib compilation: we map from our
174 // type to a type that is consumable by the DefineField
176 Type MapToInternalType (Type t)
178 if (t == TypeManager.int32_type)
180 if (t == TypeManager.int64_type)
181 return typeof (long);
182 if (t == TypeManager.uint32_type)
183 return typeof (uint);
184 if (t == TypeManager.uint64_type)
185 return typeof (ulong);
186 if (t == TypeManager.float_type)
187 return typeof (float);
188 if (t == TypeManager.double_type)
189 return typeof (double);
190 if (t == TypeManager.byte_type)
191 return typeof (byte);
192 if (t == TypeManager.sbyte_type)
193 return typeof (sbyte);
194 if (t == TypeManager.char_type)
195 return typeof (char);
196 if (t == TypeManager.short_type)
197 return typeof (short);
198 if (t == TypeManager.ushort_type)
199 return typeof (ushort);
201 throw new Exception ();
204 public override TypeBuilder DefineType ()
206 if (TypeBuilder != null)
209 TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel);
211 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
213 attr |= TypeAttributes.Class | TypeAttributes.Sealed;
215 if (!(BaseType is TypeLookupExpression)) {
216 Report.Error (1008, Location,
217 "Type byte, sbyte, short, ushort, int, uint, " +
218 "long, or ulong expected (got: `{0}')", BaseType);
222 TypeExpr texpr = ResolveTypeExpr (BaseType, Location);
226 UnderlyingType = texpr.Type;
228 if (UnderlyingType != TypeManager.int32_type &&
229 UnderlyingType != TypeManager.uint32_type &&
230 UnderlyingType != TypeManager.int64_type &&
231 UnderlyingType != TypeManager.uint64_type &&
232 UnderlyingType != TypeManager.short_type &&
233 UnderlyingType != TypeManager.ushort_type &&
234 UnderlyingType != TypeManager.byte_type &&
235 UnderlyingType != TypeManager.sbyte_type) {
236 Report.Error (1008, Location,
237 "Type byte, sbyte, short, ushort, int, uint, " +
238 "long, or ulong expected (got: " +
239 TypeManager.CSharpName (UnderlyingType) + ")");
244 if (TypeManager.NamespaceClash (Name, Location))
247 ModuleBuilder builder = CodeGen.Module.Builder;
249 TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
251 TypeBuilder builder = Parent.TypeBuilder;
253 TypeBuilder = builder.DefineNestedType (
254 Basename, attr, TypeManager.enum_type);
258 // Call MapToInternalType for corlib
260 TypeBuilder.DefineField ("value__", UnderlyingType,
261 FieldAttributes.Public | FieldAttributes.SpecialName
262 | FieldAttributes.RTSpecialName);
264 TypeManager.AddEnumType (Name, TypeBuilder, this);
269 bool IsValidEnumConstant (Expression e)
271 if (!(e is Constant))
274 if (e is IntConstant || e is UIntConstant || e is LongConstant ||
275 e is ByteConstant || e is SByteConstant || e is ShortConstant ||
276 e is UShortConstant || e is ULongConstant || e is EnumConstant ||
283 object GetNextDefaultValue (object default_value)
285 if (UnderlyingType == TypeManager.int32_type) {
286 int i = (int) default_value;
288 if (i < System.Int32.MaxValue)
292 } else if (UnderlyingType == TypeManager.uint32_type) {
293 uint i = (uint) default_value;
295 if (i < System.UInt32.MaxValue)
299 } else if (UnderlyingType == TypeManager.int64_type) {
300 long i = (long) default_value;
302 if (i < System.Int64.MaxValue)
306 } else if (UnderlyingType == TypeManager.uint64_type) {
307 ulong i = (ulong) default_value;
309 if (i < System.UInt64.MaxValue)
313 } else if (UnderlyingType == TypeManager.short_type) {
314 short i = (short) default_value;
316 if (i < System.Int16.MaxValue)
320 } else if (UnderlyingType == TypeManager.ushort_type) {
321 ushort i = (ushort) default_value;
323 if (i < System.UInt16.MaxValue)
327 } else if (UnderlyingType == TypeManager.byte_type) {
328 byte i = (byte) default_value;
330 if (i < System.Byte.MaxValue)
334 } else if (UnderlyingType == TypeManager.sbyte_type) {
335 sbyte i = (sbyte) default_value;
337 if (i < System.SByte.MaxValue)
346 void Error_ConstantValueCannotBeConverted (object val, Location loc)
349 Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
350 "' cannot be converted" +
351 " to a " + TypeManager.CSharpName (UnderlyingType));
353 Report.Error (31, loc, "Constant value '" + val +
354 "' cannot be converted" +
355 " to a " + TypeManager.CSharpName (UnderlyingType));
360 /// Determines if a standard implicit conversion exists from
361 /// expr_type to target_type
363 public static bool ImplicitConversionExists (Type expr_type, Type target_type)
365 expr_type = TypeManager.TypeToCoreType (expr_type);
367 if (expr_type == TypeManager.void_type)
370 if (expr_type == target_type)
373 // First numeric conversions
375 if (expr_type == TypeManager.sbyte_type){
377 // From sbyte to short, int, long, float, double.
379 if ((target_type == TypeManager.int32_type) ||
380 (target_type == TypeManager.int64_type) ||
381 (target_type == TypeManager.double_type) ||
382 (target_type == TypeManager.float_type) ||
383 (target_type == TypeManager.short_type) ||
384 (target_type == TypeManager.decimal_type))
387 } else if (expr_type == TypeManager.byte_type){
389 // From byte to short, ushort, int, uint, long, ulong, float, double
391 if ((target_type == TypeManager.short_type) ||
392 (target_type == TypeManager.ushort_type) ||
393 (target_type == TypeManager.int32_type) ||
394 (target_type == TypeManager.uint32_type) ||
395 (target_type == TypeManager.uint64_type) ||
396 (target_type == TypeManager.int64_type) ||
397 (target_type == TypeManager.float_type) ||
398 (target_type == TypeManager.double_type) ||
399 (target_type == TypeManager.decimal_type))
402 } else if (expr_type == TypeManager.short_type){
404 // From short to int, long, float, double
406 if ((target_type == TypeManager.int32_type) ||
407 (target_type == TypeManager.int64_type) ||
408 (target_type == TypeManager.double_type) ||
409 (target_type == TypeManager.float_type) ||
410 (target_type == TypeManager.decimal_type))
413 } else if (expr_type == TypeManager.ushort_type){
415 // From ushort to int, uint, long, ulong, float, double
417 if ((target_type == TypeManager.uint32_type) ||
418 (target_type == TypeManager.uint64_type) ||
419 (target_type == TypeManager.int32_type) ||
420 (target_type == TypeManager.int64_type) ||
421 (target_type == TypeManager.double_type) ||
422 (target_type == TypeManager.float_type) ||
423 (target_type == TypeManager.decimal_type))
426 } else if (expr_type == TypeManager.int32_type){
428 // From int to long, float, double
430 if ((target_type == TypeManager.int64_type) ||
431 (target_type == TypeManager.double_type) ||
432 (target_type == TypeManager.float_type) ||
433 (target_type == TypeManager.decimal_type))
436 } else if (expr_type == TypeManager.uint32_type){
438 // From uint to long, ulong, float, double
440 if ((target_type == TypeManager.int64_type) ||
441 (target_type == TypeManager.uint64_type) ||
442 (target_type == TypeManager.double_type) ||
443 (target_type == TypeManager.float_type) ||
444 (target_type == TypeManager.decimal_type))
447 } else if ((expr_type == TypeManager.uint64_type) ||
448 (expr_type == TypeManager.int64_type)) {
450 // From long/ulong to float, double
452 if ((target_type == TypeManager.double_type) ||
453 (target_type == TypeManager.float_type) ||
454 (target_type == TypeManager.decimal_type))
457 } else if (expr_type == TypeManager.char_type){
459 // From char to ushort, int, uint, long, ulong, float, double
461 if ((target_type == TypeManager.ushort_type) ||
462 (target_type == TypeManager.int32_type) ||
463 (target_type == TypeManager.uint32_type) ||
464 (target_type == TypeManager.uint64_type) ||
465 (target_type == TypeManager.int64_type) ||
466 (target_type == TypeManager.float_type) ||
467 (target_type == TypeManager.double_type) ||
468 (target_type == TypeManager.decimal_type))
471 } else if (expr_type == TypeManager.float_type){
475 if (target_type == TypeManager.double_type)
483 // Horrible, horrible. But there is no other way we can pass the EmitContext
484 // to the recursive definition triggered by the evaluation of a forward
487 static EmitContext current_ec = null;
490 /// This is used to lookup the value of an enum member. If the member is undefined,
491 /// it attempts to define it and return its value
493 public object LookupEnumValue (EmitContext ec, string name, Location loc)
496 object default_value = null;
499 default_value = member_to_value [name];
501 if (default_value != null)
502 return default_value;
505 // This may happen if we're calling a method in System.Enum, for instance
508 if (!defined_names.Contains (name))
511 if (in_transit.Contains (name)) {
512 Report.Error (110, loc, "The evaluation of the constant value for `" +
513 Name + "." + name + "' involves a circular definition.");
518 // So if the above doesn't happen, we have a member that is undefined
519 // We now proceed to define it
521 Expression val = this [name];
525 int idx = ordered_enums.IndexOf (name);
530 for (int i = 0; i < idx; ++i) {
531 string n = (string) ordered_enums [i];
532 Location m_loc = (Mono.CSharp.Location)
533 member_to_location [n];
534 in_transit.Add (name, true);
536 EmitContext old_ec = current_ec;
539 default_value = LookupEnumValue (ec, n, m_loc);
543 in_transit.Remove (name);
544 if (default_value == null)
548 default_value = GetNextDefaultValue (default_value);
552 bool old = ec.InEnumContext;
553 ec.InEnumContext = true;
554 in_transit.Add (name, true);
556 EmitContext old_ec = current_ec;
558 val = val.Resolve (ec);
561 in_transit.Remove (name);
562 ec.InEnumContext = old;
567 if (!IsValidEnumConstant (val)) {
570 "Type byte, sbyte, short, ushort, int, uint, long, or " +
571 "ulong expected (have: " + val + ")");
576 default_value = c.GetValue ();
578 if (default_value == null) {
579 Error_ConstantValueCannotBeConverted (c, loc);
583 if (val is EnumConstant){
584 Type etype = TypeManager.EnumToUnderlying (c.Type);
586 if (!ImplicitConversionExists (etype, UnderlyingType)){
587 Convert.Error_CannotImplicitConversion (
588 loc, c.Type, UnderlyingType);
594 EnumMember em = (EnumMember) defined_names [name];
595 em.DefineMember (TypeBuilder);
598 default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
600 Error_ConstantValueCannotBeConverted (c, loc);
604 em.builder.SetConstant (default_value);
605 field_builders.Add (em.builder);
606 member_to_value [name] = default_value;
608 if (!TypeManager.RegisterFieldValue (em.builder, default_value))
611 return default_value;
614 public override bool DefineMembers (TypeContainer parent)
619 public override bool Define ()
622 // If there was an error during DefineEnum, return
624 if (TypeBuilder == null)
627 ec = new EmitContext (this, this, Location, null, UnderlyingType, ModFlags, false);
629 object default_value = 0;
632 foreach (string name in ordered_enums) {
634 // Have we already been defined, thanks to some cross-referencing ?
636 if (member_to_value.Contains (name))
639 Location loc = (Mono.CSharp.Location) member_to_location [name];
641 if (this [name] != null) {
642 default_value = LookupEnumValue (ec, name, loc);
644 if (default_value == null)
647 if (name == "value__"){
648 Report.Error (76, loc, "The name `value__' is reserved for enumerations");
652 EnumMember em = (EnumMember) defined_names [name];
654 em.DefineMember (TypeBuilder);
655 FieldBuilder fb = em.builder;
657 if (default_value == null) {
658 Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
664 default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
666 Error_ConstantValueCannotBeConverted (default_value, loc);
670 fb.SetConstant (default_value);
671 field_builders.Add (fb);
672 member_to_value [name] = default_value;
674 if (!TypeManager.RegisterFieldValue (fb, default_value))
678 default_value = GetNextDefaultValue (default_value);
684 public override void Emit ()
686 if (OptAttributes != null) {
687 OptAttributes.Emit (ec, this);
690 foreach (EnumMember em in defined_names.Values) {
697 void VerifyClsName ()
699 Hashtable ht = new Hashtable ();
700 foreach (string name in ordered_enums) {
701 string locase = name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
702 if (!ht.Contains (locase)) {
703 ht.Add (locase, defined_names [name]);
707 MemberCore conflict = (MemberCore)ht [locase];
708 Report.SymbolRelatedToPreviousError (conflict);
709 conflict = GetDefinition (name);
710 Report.Error (3005, conflict.Location, "Identifier '{0}' differing only in case is not CLS-compliant", conflict.GetSignatureForError ());
714 protected override bool VerifyClsCompliance (DeclSpace ds)
716 if (!base.VerifyClsCompliance (ds))
721 if (!AttributeTester.IsClsCompliant (UnderlyingType)) {
722 Report.Error (3009, Location, "'{0}': base type '{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
729 /// Returns full enum name.
731 string GetEnumeratorName (string valueName)
733 return String.Concat (Name, ".", valueName);
739 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
740 MemberFilter filter, object criteria)
742 ArrayList members = new ArrayList ();
744 if ((mt & MemberTypes.Field) != 0) {
745 if (criteria is string){
746 if (member_to_value [criteria] == null && current_ec != null){
747 LookupEnumValue (current_ec, (string) criteria, Location.Null);
751 foreach (FieldBuilder fb in field_builders)
752 if (filter (fb, criteria) == true)
756 return new MemberList (members);
759 public override MemberCache MemberCache {
765 public ArrayList ValueNames {
767 return ordered_enums;
772 public Expression this [string name] {
774 return ((EnumMember) defined_names [name]).Type;
778 public override AttributeTargets AttributeTargets {
780 return AttributeTargets.Enum;
784 protected override void VerifyObsoleteAttribute()
786 // UnderlyingType is never obsolete