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;
17 namespace Mono.CSharp {
19 class EnumMember: Attributable {
24 static string[] attribute_targets = new string [] { "field" };
26 public FieldBuilder builder;
28 public EnumMember (string name, Enum parent, Location loc, Attributes attrs):
36 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
38 if (a.Type == TypeManager.marshal_as_attr_type) {
39 UnmanagedMarshal marshal = a.GetMarshal ();
40 if (marshal != null) {
41 builder.SetMarshal (marshal);
44 Report.Warning_T (-24, a.Location);
48 builder.SetCustomAttribute (cb);
51 public override AttributeTargets AttributeTargets {
53 return AttributeTargets.Field;
57 public override bool IsClsCompliaceRequired(DeclSpace ds)
59 return parent.IsClsCompliaceRequired (ds);
62 public void DefineMember (TypeBuilder tb)
64 FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
65 | FieldAttributes.Literal;
67 builder = tb.DefineField (name, tb, attr);
70 public void Emit (EmitContext ec)
72 if (OptAttributes != null)
73 OptAttributes.Emit (ec, this);
76 protected override string[] ValidAttributeTargets {
78 return attribute_targets;
84 /// Enumeration container
86 public class Enum : DeclSpace {
87 ArrayList ordered_enums;
89 public Expression BaseType;
91 public Type UnderlyingType;
93 Hashtable member_to_location;
94 Hashtable member_to_attributes;
97 // This is for members that have been defined
99 Hashtable member_to_value;
102 // This is used to mark members we're currently defining
104 Hashtable in_transit;
106 ArrayList field_builders;
109 Hashtable name_to_member;
111 public const int AllowedModifiers =
114 Modifiers.PROTECTED |
118 public Enum (NamespaceEntry ns, TypeContainer parent, Expression type,
119 int mod_flags, MemberName name, Attributes attrs, Location l)
120 : base (ns, parent, name, attrs, l)
122 this.BaseType = type;
123 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
124 IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, l);
126 ordered_enums = new ArrayList ();
127 member_to_location = new Hashtable ();
128 member_to_value = new Hashtable ();
129 in_transit = new Hashtable ();
130 field_builders = new ArrayList ();
132 name_to_member = new Hashtable ();
136 /// Adds @name to the enumeration space, with @expr
137 /// being its definition.
139 public AdditionResult AddEnumMember (string name, Expression expr, Location loc,
140 Attributes opt_attrs)
142 if (defined_names.Contains (name))
143 return AdditionResult.NameExists;
145 if (name == "value__") {
146 Report.Error (76, loc, "An item in an enumeration can't have an identifier `value__'");
147 return AdditionResult.Error;
150 DefineName (name, expr);
152 ordered_enums.Add (name);
153 member_to_location.Add (name, loc);
155 if (member_to_attributes == null)
156 member_to_attributes = new Hashtable ();
158 member_to_attributes.Add (name, opt_attrs);
160 name_to_member.Add (name, new EnumMember (name, this, loc, opt_attrs));
162 return AdditionResult.Success;
166 // This is used by corlib compilation: we map from our
167 // type to a type that is consumable by the DefineField
169 Type MapToInternalType (Type t)
171 if (t == TypeManager.int32_type)
173 if (t == TypeManager.int64_type)
174 return typeof (long);
175 if (t == TypeManager.uint32_type)
176 return typeof (uint);
177 if (t == TypeManager.uint64_type)
178 return typeof (ulong);
179 if (t == TypeManager.float_type)
180 return typeof (float);
181 if (t == TypeManager.double_type)
182 return typeof (double);
183 if (t == TypeManager.byte_type)
184 return typeof (byte);
185 if (t == TypeManager.sbyte_type)
186 return typeof (sbyte);
187 if (t == TypeManager.char_type)
188 return typeof (char);
189 if (t == TypeManager.short_type)
190 return typeof (short);
191 if (t == TypeManager.ushort_type)
192 return typeof (ushort);
194 throw new Exception ();
197 public override TypeBuilder DefineType ()
199 if (TypeBuilder != null)
202 TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel);
204 attr |= TypeAttributes.Class | TypeAttributes.Sealed;
206 UnderlyingType = ResolveType (BaseType, false, Location);
208 if (UnderlyingType != TypeManager.int32_type &&
209 UnderlyingType != TypeManager.uint32_type &&
210 UnderlyingType != TypeManager.int64_type &&
211 UnderlyingType != TypeManager.uint64_type &&
212 UnderlyingType != TypeManager.short_type &&
213 UnderlyingType != TypeManager.ushort_type &&
214 UnderlyingType != TypeManager.byte_type &&
215 UnderlyingType != TypeManager.sbyte_type) {
216 Report.Error (1008, Location,
217 "Type byte, sbyte, short, ushort, int, uint, " +
218 "long, or ulong expected (got: " +
219 TypeManager.CSharpName (UnderlyingType) + ")");
224 if (TypeManager.NamespaceClash (Name, Location))
227 ModuleBuilder builder = CodeGen.Module.Builder;
229 TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
231 TypeBuilder builder = Parent.TypeBuilder;
233 TypeBuilder = builder.DefineNestedType (
234 Basename, attr, TypeManager.enum_type);
238 // Call MapToInternalType for corlib
240 TypeBuilder.DefineField ("value__", UnderlyingType,
241 FieldAttributes.Public | FieldAttributes.SpecialName
242 | FieldAttributes.RTSpecialName);
244 TypeManager.AddEnumType (Name, TypeBuilder, this);
249 bool IsValidEnumConstant (Expression e)
251 if (!(e is Constant))
254 if (e is IntConstant || e is UIntConstant || e is LongConstant ||
255 e is ByteConstant || e is SByteConstant || e is ShortConstant ||
256 e is UShortConstant || e is ULongConstant || e is EnumConstant ||
263 object GetNextDefaultValue (object default_value)
265 if (UnderlyingType == TypeManager.int32_type) {
266 int i = (int) default_value;
268 if (i < System.Int32.MaxValue)
272 } else if (UnderlyingType == TypeManager.uint32_type) {
273 uint i = (uint) default_value;
275 if (i < System.UInt32.MaxValue)
279 } else if (UnderlyingType == TypeManager.int64_type) {
280 long i = (long) default_value;
282 if (i < System.Int64.MaxValue)
286 } else if (UnderlyingType == TypeManager.uint64_type) {
287 ulong i = (ulong) default_value;
289 if (i < System.UInt64.MaxValue)
293 } else if (UnderlyingType == TypeManager.short_type) {
294 short i = (short) default_value;
296 if (i < System.Int16.MaxValue)
300 } else if (UnderlyingType == TypeManager.ushort_type) {
301 ushort i = (ushort) default_value;
303 if (i < System.UInt16.MaxValue)
307 } else if (UnderlyingType == TypeManager.byte_type) {
308 byte i = (byte) default_value;
310 if (i < System.Byte.MaxValue)
314 } else if (UnderlyingType == TypeManager.sbyte_type) {
315 sbyte i = (sbyte) default_value;
317 if (i < System.SByte.MaxValue)
326 void Error_ConstantValueCannotBeConverted (object val, Location loc)
329 Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
330 "' cannot be converted" +
331 " to a " + TypeManager.CSharpName (UnderlyingType));
333 Report.Error (31, loc, "Constant value '" + val +
334 "' cannot be converted" +
335 " to a " + TypeManager.CSharpName (UnderlyingType));
340 /// Determines if a standard implicit conversion exists from
341 /// expr_type to target_type
343 public static bool ImplicitConversionExists (Type expr_type, Type target_type)
345 expr_type = TypeManager.TypeToCoreType (expr_type);
347 if (expr_type == TypeManager.void_type)
350 if (expr_type == target_type)
353 // First numeric conversions
355 if (expr_type == TypeManager.sbyte_type){
357 // From sbyte to short, int, long, float, double.
359 if ((target_type == TypeManager.int32_type) ||
360 (target_type == TypeManager.int64_type) ||
361 (target_type == TypeManager.double_type) ||
362 (target_type == TypeManager.float_type) ||
363 (target_type == TypeManager.short_type) ||
364 (target_type == TypeManager.decimal_type))
367 } else if (expr_type == TypeManager.byte_type){
369 // From byte to short, ushort, int, uint, long, ulong, float, double
371 if ((target_type == TypeManager.short_type) ||
372 (target_type == TypeManager.ushort_type) ||
373 (target_type == TypeManager.int32_type) ||
374 (target_type == TypeManager.uint32_type) ||
375 (target_type == TypeManager.uint64_type) ||
376 (target_type == TypeManager.int64_type) ||
377 (target_type == TypeManager.float_type) ||
378 (target_type == TypeManager.double_type) ||
379 (target_type == TypeManager.decimal_type))
382 } else if (expr_type == TypeManager.short_type){
384 // From short to int, long, float, double
386 if ((target_type == TypeManager.int32_type) ||
387 (target_type == TypeManager.int64_type) ||
388 (target_type == TypeManager.double_type) ||
389 (target_type == TypeManager.float_type) ||
390 (target_type == TypeManager.decimal_type))
393 } else if (expr_type == TypeManager.ushort_type){
395 // From ushort to int, uint, long, ulong, float, double
397 if ((target_type == TypeManager.uint32_type) ||
398 (target_type == TypeManager.uint64_type) ||
399 (target_type == TypeManager.int32_type) ||
400 (target_type == TypeManager.int64_type) ||
401 (target_type == TypeManager.double_type) ||
402 (target_type == TypeManager.float_type) ||
403 (target_type == TypeManager.decimal_type))
406 } else if (expr_type == TypeManager.int32_type){
408 // From int to long, float, double
410 if ((target_type == TypeManager.int64_type) ||
411 (target_type == TypeManager.double_type) ||
412 (target_type == TypeManager.float_type) ||
413 (target_type == TypeManager.decimal_type))
416 } else if (expr_type == TypeManager.uint32_type){
418 // From uint to long, ulong, float, double
420 if ((target_type == TypeManager.int64_type) ||
421 (target_type == TypeManager.uint64_type) ||
422 (target_type == TypeManager.double_type) ||
423 (target_type == TypeManager.float_type) ||
424 (target_type == TypeManager.decimal_type))
427 } else if ((expr_type == TypeManager.uint64_type) ||
428 (expr_type == TypeManager.int64_type)) {
430 // From long/ulong to float, double
432 if ((target_type == TypeManager.double_type) ||
433 (target_type == TypeManager.float_type) ||
434 (target_type == TypeManager.decimal_type))
437 } else if (expr_type == TypeManager.char_type){
439 // From char to ushort, int, uint, long, ulong, float, double
441 if ((target_type == TypeManager.ushort_type) ||
442 (target_type == TypeManager.int32_type) ||
443 (target_type == TypeManager.uint32_type) ||
444 (target_type == TypeManager.uint64_type) ||
445 (target_type == TypeManager.int64_type) ||
446 (target_type == TypeManager.float_type) ||
447 (target_type == TypeManager.double_type) ||
448 (target_type == TypeManager.decimal_type))
451 } else if (expr_type == TypeManager.float_type){
455 if (target_type == TypeManager.double_type)
463 // Horrible, horrible. But there is no other way we can pass the EmitContext
464 // to the recursive definition triggered by the evaluation of a forward
467 static EmitContext current_ec = null;
470 /// This is used to lookup the value of an enum member. If the member is undefined,
471 /// it attempts to define it and return its value
473 public object LookupEnumValue (EmitContext ec, string name, Location loc)
476 object default_value = null;
479 default_value = member_to_value [name];
481 if (default_value != null)
482 return default_value;
485 // This may happen if we're calling a method in System.Enum, for instance
488 if (!defined_names.Contains (name))
491 if (in_transit.Contains (name)) {
492 Report.Error (110, loc, "The evaluation of the constant value for `" +
493 Name + "." + name + "' involves a circular definition.");
498 // So if the above doesn't happen, we have a member that is undefined
499 // We now proceed to define it
501 Expression val = this [name];
505 int idx = ordered_enums.IndexOf (name);
510 for (int i = 0; i < idx; ++i) {
511 string n = (string) ordered_enums [i];
512 Location m_loc = (Mono.CSharp.Location)
513 member_to_location [n];
514 in_transit.Add (name, true);
516 EmitContext old_ec = current_ec;
519 default_value = LookupEnumValue (ec, n, m_loc);
523 in_transit.Remove (name);
524 if (default_value == null)
528 default_value = GetNextDefaultValue (default_value);
532 bool old = ec.InEnumContext;
533 ec.InEnumContext = true;
534 in_transit.Add (name, true);
536 EmitContext old_ec = current_ec;
538 val = val.Resolve (ec);
541 in_transit.Remove (name);
542 ec.InEnumContext = old;
547 if (!IsValidEnumConstant (val)) {
550 "Type byte, sbyte, short, ushort, int, uint, long, or " +
551 "ulong expected (have: " + val + ")");
556 default_value = c.GetValue ();
558 if (default_value == null) {
559 Error_ConstantValueCannotBeConverted (c, loc);
563 if (val is EnumConstant){
564 Type etype = TypeManager.EnumToUnderlying (c.Type);
566 if (!ImplicitConversionExists (etype, UnderlyingType)){
567 Convert.Error_CannotImplicitConversion (
568 loc, c.Type, UnderlyingType);
574 EnumMember em = name_to_member [name] as EnumMember;
575 em.DefineMember (TypeBuilder);
578 default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
580 Error_ConstantValueCannotBeConverted (c, loc);
584 em.builder.SetConstant (default_value);
585 field_builders.Add (em.builder);
586 member_to_value [name] = default_value;
588 if (!TypeManager.RegisterFieldValue (em.builder, default_value))
591 return default_value;
594 public override bool DefineMembers (TypeContainer parent)
599 public override bool Define (TypeContainer parent)
602 // If there was an error during DefineEnum, return
604 if (TypeBuilder == null)
607 EmitContext ec = new EmitContext (this, this, Location, null,
608 UnderlyingType, ModFlags, false);
611 object default_value = 0;
614 foreach (string name in ordered_enums) {
616 // Have we already been defined, thanks to some cross-referencing ?
618 if (member_to_value.Contains (name))
621 Location loc = (Mono.CSharp.Location) member_to_location [name];
623 if (this [name] != null) {
624 default_value = LookupEnumValue (ec, name, loc);
626 if (default_value == null)
629 if (name == "value__"){
630 Report.Error (76, loc, "The name `value__' is reserved for enumerations");
634 EnumMember em = name_to_member [name] as EnumMember;
636 em.DefineMember (TypeBuilder);
637 FieldBuilder fb = em.builder;
639 if (default_value == null) {
640 Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
646 default_value = TypeManager.ChangeType (default_value, UnderlyingType, out fail);
648 Error_ConstantValueCannotBeConverted (default_value, loc);
652 fb.SetConstant (default_value);
653 field_builders.Add (fb);
654 member_to_value [name] = default_value;
656 if (!TypeManager.RegisterFieldValue (fb, default_value))
660 default_value = GetNextDefaultValue (default_value);
665 public override void Emit (TypeContainer tc)
667 EmitContext ec = new EmitContext (tc, this, Location, null, null, ModFlags, false);
669 if (OptAttributes != null) {
670 OptAttributes.Emit (ec, this);
673 foreach (EnumMember em in name_to_member.Values) {
680 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
682 if (!base.IsIdentifierClsCompliant (ds))
685 for (int i = 1; i < ordered_enums.Count; ++i) {
686 string checked_name = ordered_enums [i] as string;
687 for (int ii = 0; ii < ordered_enums.Count; ++ii) {
691 string enumerator_name = ordered_enums [ii] as string;
692 if (String.Compare (checked_name, enumerator_name, true) == 0) {
693 Report.SymbolRelatedToPreviousError ((Location)member_to_location [enumerator_name], enumerator_name);
694 Report.Error_T (3005, (Location)member_to_location [checked_name], GetEnumeratorName (checked_name));
702 protected override bool VerifyClsCompliance (DeclSpace ds)
704 if (!base.VerifyClsCompliance (ds))
707 if (!AttributeTester.IsClsCompliant (UnderlyingType)) {
708 Report.Error_T (3009, Location, GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
715 /// Returns full enum name.
717 string GetEnumeratorName (string valueName)
719 return String.Concat (Name, ".", valueName);
725 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
726 MemberFilter filter, object criteria)
728 ArrayList members = new ArrayList ();
730 if ((mt & MemberTypes.Field) != 0) {
731 if (criteria is string){
732 if (member_to_value [criteria] == null && current_ec != null){
733 LookupEnumValue (current_ec, (string) criteria, Location.Null);
737 foreach (FieldBuilder fb in field_builders)
738 if (filter (fb, criteria) == true)
742 return new MemberList (members);
745 public override MemberCache MemberCache {
751 public ArrayList ValueNames {
753 return ordered_enums;
758 public Expression this [string name] {
760 return (Expression) defined_names [name];
764 public override AttributeTargets AttributeTargets {
766 return AttributeTargets.Enum;