Fix unmanaged type check for nested generic types
[mono.git] / mcs / mcs / enum.cs
index f01f2654b8c16b8256d15c04dc7989cb80eba611..4b0f4a020432e8691595e31a69658726ba7def7b 100644 (file)
 //         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;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+#else
+using MetaType = System.Type;
 using System.Reflection;
-using System.Reflection.Emit;
-using System.Globalization;
+#endif
 
 namespace Mono.CSharp {
 
-       public class EnumMember : MemberCore, IConstant {
-               static string[] attribute_targets = new string [] { "field" };
-
-               public FieldBuilder builder;
-
-               readonly Enum parent_enum;
-               readonly Expression ValueExpr;
-               readonly EnumMember prev_member;
-
-               EnumConstant value;
-               bool in_transit;
-
-               // TODO: remove or simplify
-               EmitContext ec;
+       public class EnumMember : Const
+       {
+               class EnumTypeExpr : TypeExpr
+               {
+                       public override TypeSpec ResolveAsType (IMemberContext ec)
+                       {
+                               type = ec.CurrentType;
+                               eclass = ExprClass.Type;
+                               return type;
+                       }
+               }
 
-               public EnumMember (Enum parent_enum, EnumMember prev_member, Expression expr,
-                               MemberName name, Attributes attrs):
-                       base (parent_enum, name, attrs)
+               public EnumMember (Enum parent, MemberName name, Attributes attrs)
+                       : base (parent, new EnumTypeExpr (), Modifiers.PUBLIC, name, attrs)
                {
-                       this.parent_enum = parent_enum;
-                       this.ModFlags = parent_enum.ModFlags;
-                       this.ValueExpr = expr;
-                       this.prev_member = prev_member;
+               }
 
-                       ec = new EmitContext (this, parent_enum, parent_enum, Location, null, null, ModFlags, false);
-                       ec.InEnumContext = true;
+               static bool IsValidEnumType (TypeSpec t)
+               {
+                       switch (t.BuiltinType) {
+                       case BuiltinTypeSpec.Type.Int:
+                       case BuiltinTypeSpec.Type.UInt:
+                       case BuiltinTypeSpec.Type.Long:
+                       case BuiltinTypeSpec.Type.Byte:
+                       case BuiltinTypeSpec.Type.SByte:
+                       case BuiltinTypeSpec.Type.Short:
+                       case BuiltinTypeSpec.Type.UShort:
+                       case BuiltinTypeSpec.Type.ULong:
+                       case BuiltinTypeSpec.Type.Char:
+                               return true;
+                       default:
+                               return t.IsEnum;
+                       }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
+               public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
                {
-                       if (a.Type == TypeManager.marshal_as_attr_type) {
-                               UnmanagedMarshal marshal = a.GetMarshal (this);
-                               if (marshal != null) {
-                                       builder.SetMarshal (marshal);
+                       if (expr is EnumConstant)
+                               expr = ((EnumConstant) expr).Child;
+
+                       var underlying = ((Enum) Parent).UnderlyingType;
+                       if (expr != null) {
+                               expr = expr.ImplicitConversionRequired (rc, underlying, Location);
+                               if (expr != null && !IsValidEnumType (expr.Type)) {
+                                       Enum.Error_1008 (Location, Report);
+                                       expr = null;
                                }
-                               return;
                        }
 
-                       if (a.Type.IsSubclassOf (TypeManager.security_attr_type)) {
-                               a.Error_InvalidSecurityParent ();
-                               return;
-                       }
+                       if (expr == null)
+                               expr = New.Constantify (underlying, Location);
 
-                       builder.SetCustomAttribute (cb);
+                       return new EnumConstant (expr, MemberType);
                }
 
-               public override AttributeTargets AttributeTargets {
-                       get {
-                               return AttributeTargets.Field;
-                       }
-               }
-
-               static bool IsValidEnumType (Type t)
-               {
-                       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);
-               }
-       
                public override bool Define ()
                {
+                       if (!ResolveMemberType ())
+                               return false;
+
                        const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal;
-                       TypeBuilder tb = parent_enum.TypeBuilder;
-                       builder = tb.DefineField (Name, tb, attr);
-                       ec.ContainerType = tb;
+                       FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), attr);
+                       spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer);
 
-                       TypeManager.RegisterConstant (builder, this);
+                       Parent.MemberCache.AddMember (spec);
                        return true;
                }
+       }
 
-               // Because parent is TypeContainer and we have DeclSpace only
-               public override void CheckObsoleteness (Location loc)
+       /// <summary>
+       ///   Enumeration container
+       /// </summary>
+       public class Enum : TypeContainer
+       {
+               //
+               // Implicit enum member initializer, used when no constant value is provided
+               //
+               sealed class ImplicitInitializer : Expression
                {
-                       parent_enum.CheckObsoleteness (loc);
+                       readonly EnumMember prev;
+                       readonly EnumMember current;
 
-                       ObsoleteAttribute oa = GetObsoleteAttribute ();
-                       if (oa == null) {
-                               return;
+                       public ImplicitInitializer (EnumMember current, EnumMember prev)
+                       {
+                               this.current = current;
+                               this.prev = prev;
                        }
 
-                       AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
-               }
-
-               public bool ResolveValue ()
-               {
-                       if (value != null)
-                               return true;
-
-                       if (in_transit) {
-                               Const.Error_CyclicDeclaration (this);
+                       public override bool ContainsEmitWithAwait ()
+                       {
                                return false;
                        }
 
-                       if (ValueExpr != null) {
-                               in_transit = true;
-                               Constant c = ValueExpr.ResolveAsConstant (ec, this);
-                               in_transit = false;
+                       public override Expression CreateExpressionTree (ResolveContext ec)
+                       {
+                               throw new NotSupportedException ("Missing Resolve call");
+                       }
 
-                               if (c == null)
-                                       return false;
+                       protected override Expression DoResolve (ResolveContext rc)
+                       {
+                               // We are the first member
+                               if (prev == null) {
+                                       return New.Constantify (current.Parent.Definition, Location);
+                               }
 
-                               if (c is EnumConstant)
-                                       c = ((EnumConstant)c).Child;
-                                       
-                               c = c.ImplicitConversionRequired (parent_enum.UnderlyingType, Location);
-                               if (c == null)
-                                       return false;
+                               var c = ((ConstSpec) prev.Spec).GetConstant (rc) as EnumConstant;
+                               try {
+                                       return c.Increment ();
+                               } catch (OverflowException) {
+                                       rc.Report.Error (543, current.Location,
+                                               "The enumerator value `{0}' is outside the range of enumerator underlying type `{1}'",
+                                               current.GetSignatureForError (), ((Enum) current.Parent).UnderlyingType.GetSignatureForError ());
 
-                               if (!IsValidEnumType (c.Type)) {
-                                       Report.Error (1008, Location, "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
-                                       return false;
+                                       return New.Constantify (current.Parent.Definition, current.Location);
                                }
-
-                               in_transit = false;
-                               value = new EnumConstant (c, parent_enum.TypeBuilder);
-                               return true;
                        }
 
-                       if (prev_member == null) {
-                               value = new EnumConstant (New.Constantify (parent_enum.UnderlyingType), parent_enum.TypeBuilder);
-                               return true;
+                       public override void Emit (EmitContext ec)
+                       {
+                               throw new NotSupportedException ("Missing Resolve call");
                        }
+               }
 
-                       if (!prev_member.ResolveValue ()) {
-                               // Suppress cyclic error
-                               prev_member.value = new EnumConstant (New.Constantify (parent_enum.UnderlyingType), parent_enum.TypeBuilder);
-                               return false;
-                       }
+               public static readonly string UnderlyingValueField = "value__";
 
-                       in_transit = true;
+               const Modifiers AllowedModifiers =
+                       Modifiers.NEW |
+                       Modifiers.PUBLIC |
+                       Modifiers.PROTECTED |
+                       Modifiers.INTERNAL |
+                       Modifiers.PRIVATE;
 
-                       try {
-                               value = (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 (parent_enum.UnderlyingType));
-                               return false;
-                       }
-                       in_transit = false;
+               readonly TypeExpr underlying_type_expr;
 
-                       return true;
+               public Enum (NamespaceContainer ns, DeclSpace parent, TypeExpression type,
+                            Modifiers mod_flags, MemberName name, Attributes attrs)
+                       : base (ns, parent, name, attrs, MemberKind.Enum)
+               {
+                       underlying_type_expr = type;
+                       var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+                       ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags, accmods, Location, Report);
+                       spec = new EnumSpec (null, this, null, null, ModFlags);
                }
 
-               public override void Emit ()
-               {
-                       if (OptAttributes != null)
-                               OptAttributes.Emit (); 
+               #region Properties
 
-                       if (!ResolveValue ()) {
-                               // Suppress cyclic errors
-                               value = new EnumConstant(New.Constantify(parent_enum.UnderlyingType), parent_enum.TypeBuilder);
-                               return;
+               public override AttributeTargets AttributeTargets {
+                       get {
+                               return AttributeTargets.Enum;
                        }
-
-                       builder.SetConstant (value.GetValue ());
-                       base.Emit ();
-               }
-
-               public override string GetSignatureForError()
-               {
-                       return String.Concat (parent_enum.GetSignatureForError (), '.', Name);
                }
 
-               public override string[] ValidAttributeTargets {
+               public TypeExpr BaseTypeExpression {
                        get {
-                               return attribute_targets;
+                               return underlying_type_expr;
                        }
                }
 
-               public override string DocCommentHeader {
-                       get { return "F:"; }
+               protected override TypeAttributes TypeAttr {
+                       get {
+                               return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
+                                       TypeAttributes.Class | TypeAttributes.Sealed | base.TypeAttr;
+                       }
                }
 
-               #region IConstant Members
-
-               public Constant CreateConstantReference (Location loc)
-               {
-                       if (value == null)
-                               return null;
-
-                       return new EnumConstant (Constant.CreateConstant (value.Child.Type, value.Child.GetValue(), loc),
-                               value.Type);
+               public TypeSpec UnderlyingType {
+                       get {
+                               return ((EnumSpec) spec).UnderlyingType;
+                       }
                }
 
                #endregion
-       }
-
-       /// <summary>
-       ///   Enumeration container
-       /// </summary>
-       public class Enum : DeclSpace {
-               Expression BaseType;
-               public Type UnderlyingType;
 
-               static MemberList no_list = new MemberList (new object[0]);
-               
-               public const int AllowedModifiers =
-                       Modifiers.NEW |
-                       Modifiers.PUBLIC |
-                       Modifiers.PROTECTED |
-                       Modifiers.INTERNAL |
-                       Modifiers.PRIVATE;
-
-               public Enum (NamespaceEntry ns, DeclSpace parent, Expression type,
-                            int mod_flags, MemberName name, Attributes attrs)
-                       : base (ns, parent, name, attrs)
+               public override void Accept (StructuralVisitor visitor)
                {
-                       this.BaseType = type;
-                       ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
-                                                   IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE, name.Location);
+                       visitor.Visit (this);
                }
 
                public void AddEnumMember (EnumMember em)
                {
-                       if (em.Name == "value__") {
-                               Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `value__'");
+                       if (em.Name == UnderlyingValueField) {
+                               Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `{0}'",
+                                       UnderlyingValueField);
                                return;
                        }
 
-                       if (!AddToContainer (em, em.Name))
-                               return;
+                       AddConstant (em);
                }
-               
-               public override TypeBuilder DefineType ()
-               {
-                       if (TypeBuilder != null)
-                               return TypeBuilder;
 
-                       if (!(BaseType is TypeLookupExpression)) {
-                               Report.Error (1008, Location,
-                                       "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
-                               return null;
-                       }
-
-                       TypeExpr ute = BaseType.ResolveAsTypeTerminal (this, false);
-                       UnderlyingType = ute.Type;
-
-                       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 null;
-                       }
-
-                       if (IsTopLevel) {
-                               if (TypeManager.NamespaceClash (Name, Location))
-                                       return null;
-                               
-                               ModuleBuilder builder = CodeGen.Module.Builder;
-
-                               TypeBuilder = builder.DefineType (Name, TypeAttr, TypeManager.enum_type);
-                       } else {
-                               TypeBuilder builder = Parent.TypeBuilder;
-
-                               TypeBuilder = builder.DefineNestedType (
-                                       Basename, TypeAttr, TypeManager.enum_type);
-                       }
-
-                       //
-                       // Call MapToInternalType for corlib
-                       //
-                       TypeBuilder.DefineField ("value__", UnderlyingType,
-                                                FieldAttributes.Public | FieldAttributes.SpecialName
-                                                | FieldAttributes.RTSpecialName);
+               public static void Error_1008 (Location loc, Report Report)
+               {
+                       Report.Error (1008, loc,
+                               "Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
+               }
 
-                       TypeManager.AddUserType (this);
+               protected override bool DefineNestedTypes ()
+               {
+                       ((EnumSpec) spec).UnderlyingType = underlying_type_expr == null ? Compiler.BuiltinTypes.Int : underlying_type_expr.Type;
 
-                       foreach (EnumMember em in defined_names.Values) {
-                               if (!em.Define ())
-                                       return null;
-                       }
+                       TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType.GetMetaInfo (),
+                               FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
 
-                       return TypeBuilder;
-               }
-               
-               public override bool Define ()
-               {
                        return true;
                }
 
-               public override void Emit ()
+               protected override bool DoDefineMembers ()
                {
-                       if (OptAttributes != null) {
-                               OptAttributes.Emit ();
-                       }
-
-                       foreach (EnumMember em in defined_names.Values) {
-                               em.Emit ();
+                       if (constants != null) {
+                               for (int i = 0; i < constants.Count; ++i) {
+                                       EnumMember em = (EnumMember) constants [i];
+                                       if (em.Initializer == null) {
+                                               em.Initializer = new ImplicitInitializer (em, i == 0 ? null : (EnumMember) constants[i - 1]);
+                                       }
+
+                                       em.Define ();
+                               }
                        }
 
-                       base.Emit ();
+                       return true;
                }
 
-               //
-               // IMemberFinder
-               //
-               public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                       MemberFilter filter, object criteria)
+               public override bool IsUnmanagedType ()
                {
-                       if ((mt & MemberTypes.Field) == 0)
-                               return no_list;
-
-                       EnumMember em = defined_names [criteria] as EnumMember;
-                       if (em == null)
-                               return no_list;
-
-                       FieldBuilder[] fb = new FieldBuilder[] { em.builder };
-                       return new MemberList (fb);
+                       return true;
                }
 
-               void VerifyClsName ()
-               {
-                       HybridDictionary dict = new HybridDictionary (defined_names.Count, true);
-                       foreach (EnumMember em in defined_names.Values) {
-                               if (!em.IsClsComplianceRequired ())
-                                       continue;
-
-                               try {
-                                       dict.Add (em.Name, em);
-                               }
-                               catch (ArgumentException) {
-                                       Report.SymbolRelatedToPreviousError (em);
-                                       MemberCore col = (MemberCore)dict [em.Name];
-#if GMCS_SOURCE
-                                       Report.Warning (3005, 1, col.Location, "Identifier `{0}' differing only in case is not CLS-compliant", col.GetSignatureForError ());
-#else
-                                       Report.Error (3005, col.Location, "Identifier `{0}' differing only in case is not CLS-compliant", col.GetSignatureForError ());
-#endif
-                               }
-                       }
-               }
+               protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+               {
+                       base_type = Compiler.BuiltinTypes.Enum;
+                       base_class = null;
+                       return null;
+               }
 
                protected override bool VerifyClsCompliance ()
                {
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       VerifyClsName ();
-
-                       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));
+                       switch (UnderlyingType.BuiltinType) {
+                       case BuiltinTypeSpec.Type.UInt:
+                       case BuiltinTypeSpec.Type.ULong:
+                       case BuiltinTypeSpec.Type.UShort:
+                               Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
+                                       GetSignatureForError (), TypeManager.CSharpName (UnderlyingType));
+                               break;
                        }
 
                        return true;
-               }
-       
+               }       
+       }
 
-               public override MemberCache MemberCache {
-                       get {
-                               return null;
-                       }
+       class EnumSpec : TypeSpec
+       {
+               TypeSpec underlying;
+
+               public EnumSpec (TypeSpec declaringType, ITypeDefinition definition, TypeSpec underlyingType, MetaType info, Modifiers modifiers)
+                       : base (MemberKind.Enum, declaringType, definition, info, modifiers | Modifiers.SEALED)
+               {
+                       this.underlying = underlyingType;
                }
 
-               public override AttributeTargets AttributeTargets {
+               public TypeSpec UnderlyingType {
                        get {
-                               return AttributeTargets.Enum;
+                               return underlying;
                        }
-               }
+                       set {
+                               if (underlying != null)
+                                       throw new InternalErrorException ("UnderlyingType reset");
 
-               protected override TypeAttributes TypeAttr {
-                       get {
-                               return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
-                               TypeAttributes.Class | TypeAttributes.Sealed |
-                               base.TypeAttr;
+                               underlying = value;
                        }
                }
 
-               //
-               // Generates xml doc comments (if any), and if required,
-               // handle warning report.
-               //
-               internal override void GenerateDocComment (DeclSpace ds)
+               public static TypeSpec GetUnderlyingType (TypeSpec t)
                {
-                       base.GenerateDocComment (ds);
+                       return ((EnumSpec) t.GetDefinition ()).UnderlyingType;
+               }
 
-                       foreach (EnumMember em in defined_names.Values) {
-                               em.GenerateDocComment (this);
+               public static bool IsValidUnderlyingType (TypeSpec type)
+               {
+                       switch (type.BuiltinType) {
+                       case BuiltinTypeSpec.Type.Int:
+                       case BuiltinTypeSpec.Type.UInt:
+                       case BuiltinTypeSpec.Type.Long:
+                       case BuiltinTypeSpec.Type.Byte:
+                       case BuiltinTypeSpec.Type.SByte:
+                       case BuiltinTypeSpec.Type.Short:
+                       case BuiltinTypeSpec.Type.UShort:
+                       case BuiltinTypeSpec.Type.ULong:
+                               return true;
                        }
-               }
 
-               //
-               //   Represents header string for documentation comment.
-               //
-               public override string DocCommentHeader {
-                       get { return "T:"; }
+                       return false;
                }
        }
 }