2008-06-11 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / enum.cs
old mode 100755 (executable)
new mode 100644 (file)
index d7c6819..8bc58c0
 //
 // Author: Miguel de Icaza (miguel@gnu.org)
 //         Ravi Pratap     (ravi@ximian.com)
+//         Marek Safar     (marek.safar@seznam.cz)
 //
-// Licensed under the terms of the GNU GPL
+// Dual licensed under the terms of the MIT X11 or GNU GPL
 //
-// (C) 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2003 Novell, Inc (http://www.novell.com)
 //
 
 using System;
 using System.Collections;
+using System.Collections.Specialized;
 using System.Reflection;
 using System.Reflection.Emit;
+using System.Globalization;
 
 namespace Mono.CSharp {
 
-       /// <summary>
-       ///   Enumeration container
-       /// </summary>
-       public class Enum : DeclSpace {
-
-               ArrayList ordered_enums;
-               public readonly string BaseType;
-               public Attributes  OptAttributes;
-               
-               public Type UnderlyingType;
-
-               Hashtable member_to_location;
-
-               //
-               // This is for members that have been defined
-               //
-               Hashtable member_to_value;
-               
-               ArrayList field_builders;
-               
-               public const int AllowedModifiers =
-                       Modifiers.NEW |
-                       Modifiers.PUBLIC |
-                       Modifiers.PROTECTED |
-                       Modifiers.INTERNAL |
-                       Modifiers.PRIVATE;
+       public class EnumMember : Const {
+               protected readonly Enum ParentEnum;
+               protected readonly Expression ValueExpr;
+               readonly EnumMember prev_member;
 
-               public Enum (TypeContainer parent, string type, int mod_flags, string name, Attributes attrs, Location l)
-                       : base (parent, name, l)
+               public EnumMember (Enum parent, EnumMember prev_member, string name, Expression expr,
+                                  Attributes attrs, Location loc)
+                       : base (parent, new EnumTypeExpr (parent), name, expr, Modifiers.PUBLIC,
+                               attrs, loc)
                {
-                       this.BaseType = type;
-                       ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);
-                       OptAttributes = attrs;
-
-                       ordered_enums = new ArrayList ();
-                       member_to_location = new Hashtable ();
-                       member_to_value = new Hashtable ();
-                       field_builders = new ArrayList ();
+                       this.ParentEnum = parent;
+                       this.ValueExpr = expr;
+                       this.prev_member = prev_member;
                }
 
-               /// <summary>
-               ///   Adds @name to the enumeration space, with @expr
-               ///   being its definition.  
-               /// </summary>
-               public AdditionResult AddEnumMember (string name, Expression expr, Location loc)
+               protected class EnumTypeExpr : TypeExpr
                {
-                       if (defined_names.Contains (name))
-                               return AdditionResult.NameExists;
+                       public readonly Enum Enum;
 
-                       DefineName (name, expr);
-
-                       ordered_enums.Add (name);
-                       member_to_location.Add (name, loc);
-                       
-                       return AdditionResult.Success;
-               }
-
-               public void DefineEnum (object parent_builder)
-               {
-                       TypeAttributes attr = TypeAttributes.Class | TypeAttributes.Sealed;
-
-                       UnderlyingType = RootContext.TypeManager.LookupType (BaseType);
-
-                       if (UnderlyingType != TypeManager.int32_type &&
-                           UnderlyingType != TypeManager.uint32_type &&
-                           UnderlyingType != TypeManager.int64_type &&
-                           UnderlyingType != TypeManager.uint64_type &&
-                           UnderlyingType != TypeManager.short_type &&
-                           UnderlyingType != TypeManager.ushort_type &&
-                           UnderlyingType != TypeManager.byte_type  &&
-                           UnderlyingType != TypeManager.sbyte_type) {
-                               Report.Error (1008, Location,
-                                             "Type byte, sbyte, short, ushort, int, uint, " +
-                                             "long, or ulong expected");
-                               return;
+                       public EnumTypeExpr (Enum e)
+                       {
+                               this.Enum = e;
                        }
 
-                       if (parent_builder is ModuleBuilder) {
-                               ModuleBuilder builder = (ModuleBuilder) parent_builder;
-
-                               if ((ModFlags & Modifiers.PUBLIC) != 0)
-                                       attr |= TypeAttributes.Public;
-                               else
-                                       attr |= TypeAttributes.NotPublic;
-                               
-                               TypeBuilder = builder.DefineType (Name, attr, TypeManager.enum_type);
-                       } else {
-                               TypeBuilder builder = (System.Reflection.Emit.TypeBuilder) parent_builder;
-
-                               if ((ModFlags & Modifiers.PUBLIC) != 0)
-                                       attr |= TypeAttributes.NestedPublic;
-                               else
-                                       attr |= TypeAttributes.NestedPrivate;
-
-                               
-                               TypeBuilder = builder.DefineNestedType (
-                                       Basename, attr, TypeManager.enum_type);
+                       protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
+                       {
+                               type = Enum.CurrentType != null ? Enum.CurrentType : Enum.TypeBuilder;
+                               return this;
                        }
 
-                       TypeBuilder.DefineField ("value__", UnderlyingType,
-                                                FieldAttributes.Public | FieldAttributes.SpecialName
-                                                | FieldAttributes.RTSpecialName);
-
-                       RootContext.TypeManager.AddEnumType (Name, TypeBuilder, this);
-
-                       return;
+                       public override TypeExpr ResolveAsTypeTerminal (IResolveContext ec, bool silent)
+                       {
+                               return DoResolveAsTypeStep (ec);
+                       }
                }
 
-               bool IsValidEnumConstant (Expression e)
+               static bool IsValidEnumType (Type t)
                {
-                       if (!(e is Constant))
-                               return false;
+                       return (t == TypeManager.int32_type || t == TypeManager.uint32_type || t == TypeManager.int64_type ||
+                               t == TypeManager.byte_type || t == TypeManager.sbyte_type || t == TypeManager.short_type ||
+                               t == TypeManager.ushort_type || t == TypeManager.uint64_type || t == TypeManager.char_type ||
+                               t.IsEnum);
+               }
 
-                       if (e is IntConstant || e is UIntConstant || e is LongConstant ||
-                           e is ByteConstant || e is SByteConstant || e is ShortConstant ||
-                           e is UShortConstant || e is ULongConstant || e is EnumConstant)
-                               return true;
-                       else
-                               return false;
+               public object Value {
+                       get { return ResolveValue () ? value.GetValue () : null; }
                }
 
-               object GetNextDefaultValue (object default_value)
+               public override bool Define ()
+               {
+                       const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal;
+                       FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, attr);
+                       Parent.MemberCache.AddMember (FieldBuilder, this);
+                       TypeManager.RegisterConstant (FieldBuilder, this);
+                       return true;
+               }
+       
+               protected override Constant DoResolveValue (EmitContext ec)
                {
-                       if (UnderlyingType == TypeManager.int32_type) {
-                               int i = (int) default_value;
-                               
-                               if (i < System.Int32.MaxValue)
-                                       return ++i;
-                               else
+                       if (ValueExpr != null) {
+                               Constant c = ValueExpr.ResolveAsConstant (ec, this);
+                               if (c == null)
                                        return null;
-                       } else if (UnderlyingType == TypeManager.uint32_type) {
-                               uint i = (uint) default_value;
 
-                               if (i < System.UInt32.MaxValue)
-                                       return ++i;
-                               else
-                                       return null;
-                       } else if (UnderlyingType == TypeManager.int64_type) {
-                               long i = (long) default_value;
+                               if (c is EnumConstant)
+                                       c = ((EnumConstant)c).Child;
 
-                               if (i < System.Int64.MaxValue)
-                                       return ++i;
-                               else
+                               c = c.ImplicitConversionRequired (ParentEnum.UnderlyingType, Location);
+                               if (c == null)
                                        return null;
-                       } else if (UnderlyingType == TypeManager.uint64_type) {
-                               ulong i = (ulong) default_value;
 
-                               if (i < System.UInt64.MaxValue)
-                                       return ++i;
-                               else
+                               if (!IsValidEnumType (c.Type)) {
+                                       Enum.Error_1008 (Location);
                                        return null;
-                       } else if (UnderlyingType == TypeManager.short_type) {
-                               short i = (short) default_value;
+                               }
 
-                               if (i < System.Int16.MaxValue)
-                                       return ++i;
-                               else
-                                       return null;
-                       } else if (UnderlyingType == TypeManager.ushort_type) {
-                               ushort i = (ushort) default_value;
+                               return new EnumConstant (c, MemberType);
+                       }
 
-                               if (i < System.UInt16.MaxValue)
-                                       return ++i;
-                               else
-                                       return null;
-                       } else if (UnderlyingType == TypeManager.byte_type) {
-                               byte i = (byte) default_value;
+                       if (prev_member == null)
+                               return new EnumConstant (
+                                       New.Constantify (ParentEnum.UnderlyingType), MemberType);
 
-                               if (i < System.Byte.MaxValue)
-                                       return ++i;
-                               else
-                                       return null;
-                       } else if (UnderlyingType == TypeManager.sbyte_type) {
-                               sbyte i = (sbyte) default_value;
+                       if (!prev_member.ResolveValue ())
+                               return null;
 
-                               if (i < System.SByte.MaxValue)
-                                       return ++i;
-                               else
-                                       return null;
+                       try {
+                               return (EnumConstant) prev_member.value.Increment ();
+                       } catch (OverflowException) {
+                               Report.Error (543, Location, "The enumerator value `{0}' is too " +
+                                             "large to fit in its type `{1}'", GetSignatureForError (),
+                                             TypeManager.CSharpName (ParentEnum.UnderlyingType));
+                               return null;
                        }
-
-                       return null;
                }
+       }
+
+       /// <summary>
+       ///   Enumeration container
+       /// </summary>
+       public class Enum : TypeContainer
+       {
+               public static readonly string UnderlyingValueField = "value__";
+
+               FullNamedExpression base_type;
 
-               void error31 (object val, Location loc)
+               public Type UnderlyingType;
+
+               public const int AllowedModifiers =
+                       Modifiers.NEW |
+                       Modifiers.PUBLIC |
+                       Modifiers.PROTECTED |
+                       Modifiers.INTERNAL |
+                       Modifiers.PRIVATE;
+
+               public Enum (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
+                            int mod_flags, MemberName name, Attributes attrs)
+                       : base (ns, parent, name, attrs, Kind.Enum)
                {
-                       if (val is Constant)
-                               Report.Error (31, loc, "Constant value '" + ((Constant) val).AsString () +
-                                             "' cannot be converted" +
-                                             " to a " + TypeManager.CSharpName (UnderlyingType));
-                       else 
-                               Report.Error (31, loc, "Constant value '" + val +
-                                             "' cannot be converted" +
-                                             " to a " + TypeManager.CSharpName (UnderlyingType));
-                       return;
+                       this.base_type = type;
+                       int accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+                       ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, accmods, Location);
                }
 
-               /// <summary>
-               ///  This is used to lookup the value of an enum member. If the member is undefined,
-               ///  it attempts to define it and return its value
-               /// </summary>
-               public object LookupEnumValue (EmitContext ec, string name, Location loc)
+               public void AddEnumMember (EnumMember em)
                {
-                       object default_value = null;
-                       Constant c = null;
+                       if (em.Name == UnderlyingValueField) {
+                               Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `{0}'",
+                                       UnderlyingValueField);
+                               return;
+                       }
 
-                       default_value = member_to_value [name];
+                       AddConstant (em);
+               }
 
-                       if (default_value != null)
-                               return default_value;
+               public static void Error_1008 (Location loc)
+               {
+                       Report.Error (1008, loc, "Type byte, sbyte, short, ushort, " +
+                                     "int, uint, long or ulong expected");
+               }
 
-                       if (!defined_names.Contains (name)) {
-                               Report.Error (117, loc, "'"+ Name + "' does not contain a definition for '"
-                                             + name + "'");
-                               return null;
-                       }
+               protected override bool DefineNestedTypes ()
+               {
+                       if (!base.DefineNestedTypes ())
+                               return false;
 
-                       //
-                       // So if the above doesn't happen, we have a member that is undefined
-                       // We now proceed to define it 
-                       //
-                       Expression val = this [name];
-
-                       if (val == null) {
-                               
-                               int idx = ordered_enums.IndexOf (name);
-
-                               if (idx == 0)
-                                       default_value = 0;
-                               else {
-                                       for (int i = 0; i < idx; ++i) {
-                                               string n = (string) ordered_enums [i];
-                                               Location m_loc = (Mono.CSharp.Location)
-                                                       member_to_location [n];
-                                               default_value = LookupEnumValue (ec, n, m_loc);
-                                       }
-                                       
-                                       default_value = GetNextDefaultValue (default_value);
-                               }
-                               
-                       } else {
-                               val = val.Resolve (ec);
-                               
-                               if (val == null) {
-                                       Report.Error (-12, loc, "Definition is circular.");
-                                       return null;
-                               }       
-                               
-                               if (IsValidEnumConstant (val)) {
-                                       c = (Constant) val;
-                                       default_value = c.GetValue ();
-                                       
-                                       if (default_value == null) {
-                                               error31 (c, loc);
-                                               return null;
-                                       }
-                                       
-                               } else {
-                                       Report.Error (
-                                               1008, loc,
-                                               "Type byte, sbyte, short, ushort, int, uint, long, or " +
-                                               "ulong expected");
-                                       return null;
-                               }
+                       if (!(base_type is TypeLookupExpression)) {
+                               Error_1008 (Location);
+                               return false;
                        }
 
-                       FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
-                                       | FieldAttributes.Literal;
-                       
-                       FieldBuilder fb = TypeBuilder.DefineField (name, UnderlyingType, attr);
-                       
-                       try {
-                               default_value = Convert.ChangeType (default_value, UnderlyingType);
-                       } catch {
-                               error31 (c, loc);
-                               return null;
-                       }
+                       TypeExpr ute = base_type.ResolveAsTypeTerminal (this, false);
+                       UnderlyingType = ute.Type;
 
-                       fb.SetConstant (default_value);
-                       field_builders.Add (fb);
-                       member_to_value [name] = default_value;
+                       if (UnderlyingType != TypeManager.int32_type &&
+                           UnderlyingType != TypeManager.uint32_type &&
+                           UnderlyingType != TypeManager.int64_type &&
+                           UnderlyingType != TypeManager.uint64_type &&
+                           UnderlyingType != TypeManager.short_type &&
+                           UnderlyingType != TypeManager.ushort_type &&
+                           UnderlyingType != TypeManager.byte_type  &&
+                           UnderlyingType != TypeManager.sbyte_type) {
+                               Error_1008 (Location);
+                               return false;
+                       }
 
-                       if (!TypeManager.RegisterFieldValue (fb, default_value))
-                               return null;
-                       
-                       return default_value;
-               }
-               
-               public override bool Define (TypeContainer parent)
-               {
                        //
-                       // If there was an error during DefineEnum, return
+                       // Call MapToInternalType for corlib
                        //
-                       if (TypeBuilder == null)
-                               return false;
-                       
-                       EmitContext ec = new EmitContext (parent, Location, null, UnderlyingType, ModFlags);
-                       
-                       object default_value = 0;
-                       
-                       FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static
-                                            | FieldAttributes.Literal;
-
-                       
-                       foreach (string name in ordered_enums) {
-                               //
-                               // Have we already been defined, thanks to some cross-referencing ?
-                               // 
-                               if (member_to_value.Contains (name))
-                                       continue;
-                               
-                               Location loc = (Mono.CSharp.Location) member_to_location [name];
-
-                               if (this [name] != null) {
-                                       default_value = LookupEnumValue (ec, name, loc);
-
-                                       if (default_value == null)
-                                               return true;
-
-                               } else {
-                                       FieldBuilder fb = TypeBuilder.DefineField (
-                                               name, UnderlyingType, attr);
-                                       
-                                       if (default_value == null) {
-                                          Report.Error (543, loc, "Enumerator value for '" + name + "' is too large to " +
-                                                             "fit in its type");
-                                               return false;
-                                       }
-                                       
-                                       try {
-                                               default_value = Convert.ChangeType (default_value, UnderlyingType);
-                                       } catch {
-                                               error31 (default_value, loc);
-                                               return false;
-                                       }
-
-                                       fb.SetConstant (default_value);
-                                       field_builders.Add (fb);
-                                       member_to_value [name] = default_value;
-                                       
-                                       if (!TypeManager.RegisterFieldValue (fb, default_value))
-                                               return false;
-                               }
+                       TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType,
+                                                FieldAttributes.Public | FieldAttributes.SpecialName
+                                                | FieldAttributes.RTSpecialName);
 
-                               default_value = GetNextDefaultValue (default_value);
-                       }
-                       
-                       Attribute.ApplyAttributes (ec, TypeBuilder, this, OptAttributes, Location);
+                       return true;
+               }
 
+               protected override bool DoDefineMembers ()
+               {
+                       member_cache = new MemberCache (TypeManager.enum_type, this);
+                       DefineContainerMembers (constants);
                        return true;
                }
-               
+
                //
-               // Hack around System.Reflection as found everywhere else
+               // Used for error reporting only
                //
-               public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf,
-                                                 MemberFilter filter, object criteria)
+               public EnumMember GetDefinition (object value)
                {
-                       ArrayList members = new ArrayList ();
-
-                       if ((mt & MemberTypes.Field) != 0) {
-                               foreach (FieldBuilder fb in field_builders)
-                                       if (filter (fb, criteria) == true)
-                                               members.Add (fb);
+                       foreach (EnumMember e in defined_names.Values) {
+                               if (value.Equals (e.Value))
+                                       return e;
                        }
 
-                       int count = members.Count;
+                       throw new ArgumentOutOfRangeException (value.ToString ());
+               }
 
-                       if (count > 0) {
-                               MemberInfo [] mi = new MemberInfo [count];
-                               members.CopyTo (mi, 0);
-                               return mi;
+               protected override bool VerifyClsCompliance ()
+               {
+                       if (!base.VerifyClsCompliance ())
+                               return false;
+
+                       if (UnderlyingType == TypeManager.uint32_type ||
+                               UnderlyingType == TypeManager.uint64_type ||
+                               UnderlyingType == TypeManager.ushort_type) {
+                               Report.Error (3009, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
                        }
 
-                       return null;
-               }
+                       return true;
+               }       
 
-               public ArrayList ValueNames {
+               public override AttributeTargets AttributeTargets {
                        get {
-                               return ordered_enums;
+                               return AttributeTargets.Enum;
                        }
                }
 
-               // indexer
-               public Expression this [string name] {
+               protected override TypeAttributes TypeAttr {
                        get {
-                               return (Expression) defined_names [name];
+                               return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
+                                       TypeAttributes.Class | TypeAttributes.Sealed | base.TypeAttr;
                        }
                }
        }