New test.
[mono.git] / mcs / gmcs / generic.cs
index 440b2d034559727b1acc6c0c6fbf5aad1f5b292b..b75b603d295d3d632b991773039f878eec285206 100644 (file)
@@ -156,6 +156,11 @@ namespace Mono.CSharp {
                        }
                }
 
+               public Constraints Clone ()
+               {
+                       return new Constraints (name, constraints, loc);
+               }
+
                GenericParameterAttributes attrs;
                TypeExpr class_constraint;
                ArrayList iface_constraints;
@@ -182,7 +187,7 @@ namespace Mono.CSharp {
                        foreach (object obj in constraints) {
                                if (HasConstructorConstraint) {
                                        Report.Error (401, loc,
-                                                     "The new() constraint must be last.");
+                                                     "The new() constraint must be the last constraint specified");
                                        return false;
                                }
 
@@ -195,17 +200,14 @@ namespace Mono.CSharp {
                                                        continue;
                                                }
 
-                                               Report.Error (
-                                                       451, loc, "The new () constraint " +
-                                                       "cannot be used with the `struct' " +
-                                                       "constraint.");
+                                               Report.Error (451, loc, "The `new()' constraint " +
+                                                       "cannot be used with the `struct' constraint");
                                                return false;
                                        }
 
                                        if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
-                                               Report.Error (449, loc,
-                                                             "The `class' or `struct' " +
-                                                             "constraint must be first");
+                                               Report.Error (449, loc, "The `class' or `struct' " +
+                                                             "constraint must be the first constraint specified");
                                                return false;
                                        }
 
@@ -223,7 +225,7 @@ namespace Mono.CSharp {
                                        if (errors != Report.Errors)
                                                return false;
 
-                                       Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
+                                       NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
                                        return false;
                                }
 
@@ -235,11 +237,20 @@ namespace Mono.CSharp {
 
                                        expr = cexpr;
                                } else
-                                       expr = fn.ResolveAsTypeTerminal (ec, false);
+                                       expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
 
                                if ((expr == null) || (expr.Type == null))
                                        return false;
 
+                               // TODO: It's aleady done in ResolveAsBaseTerminal
+                               if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
+                                       Report.SymbolRelatedToPreviousError (fn.Type);
+                                       Report.Error (703, loc,
+                                               "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
+                                               fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
+                                       return false;
+                               }
+
                                TypeParameterExpr texpr = expr as TypeParameterExpr;
                                if (texpr != null)
                                        type_param_constraints.Add (expr);
@@ -254,7 +265,7 @@ namespace Mono.CSharp {
                                } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
                                        Report.Error (450, loc, "`{0}': cannot specify both " +
                                                      "a constraint class and the `class' " +
-                                                     "or `struct' constraint.", expr.Name);
+                                                     "or `struct' constraint", expr.GetSignatureForError ());
                                        return false;
                                } else
                                        class_constraint = expr;
@@ -301,10 +312,16 @@ namespace Mono.CSharp {
                                        return false;
 
                                if (class_constraint_type.IsSealed) {
-                                       Report.Error (701, loc,
-                                                     "`{0}' is not a valid bound.  Bounds " +
-                                                     "must be interfaces or non sealed " +
-                                                     "classes", TypeManager.CSharpName (class_constraint_type));
+                                       if (class_constraint_type.IsAbstract)
+                                       {
+                                               Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
+                                                       TypeManager.CSharpName (class_constraint_type));
+                                       }
+                                       else
+                                       {
+                                               Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
+                                                       "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
+                                       }
                                        return false;
                                }
 
@@ -550,6 +567,27 @@ namespace Mono.CSharp {
 
                        return true;
                }
+
+               public void VerifyClsCompliance ()
+               {
+                       if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
+                               Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
+
+                       if (iface_constraint_types != null) {
+                               for (int i = 0; i < iface_constraint_types.Length; ++i) {
+                                       if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
+                                               Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
+                                                       ((TypeExpr)iface_constraints [i]).Location);
+                               }
+                       }
+               }
+
+               void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
+               {
+                       Report.SymbolRelatedToPreviousError (t);
+                       Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
+                               TypeManager.CSharpName (t));
+               }
        }
 
        /// <summary>
@@ -684,11 +722,9 @@ namespace Mono.CSharp {
 
                        if (implementing != null) {
                                if (is_override && (constraints != null)) {
-                                       Report.Error (
-                                               460, loc, "Constraints for override and " +
-                                               "explicit interface implementation methods " +
-                                               "are inherited from the base method so they " +
-                                               "cannot be specified directly");
+                                       Report.Error (460, loc,
+                                               "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
+                                               TypeManager.CSharpSignature (builder));
                                        return false;
                                }
 
@@ -727,7 +763,7 @@ namespace Mono.CSharp {
                                                TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
                                        return false;
                                }
-                       } else if (DeclSpace is Iterator) {
+                       } else if (DeclSpace is CompilerGeneratedClass) {
                                TypeParameter[] tparams = DeclSpace.TypeParameters;
                                Type[] types = new Type [tparams.Length];
                                for (int i = 0; i < tparams.Length; i++)
@@ -1181,6 +1217,19 @@ namespace Mono.CSharp {
                        return s.ToString ();
                }
 
+               public string GetSignatureForError()
+               {
+                       StringBuilder sb = new StringBuilder();
+                       for (int i = 0; i < Count; ++i)
+                       {
+                               Expression expr = (Expression)args [i];
+                               sb.Append(expr.GetSignatureForError());
+                               if (i + 1 < Count)
+                                       sb.Append(',');
+                       }
+                       return sb.ToString();
+               }
+
                /// <summary>
                ///   Resolve the type arguments.
                /// </summary>
@@ -1200,13 +1249,21 @@ namespace Mono.CSharp {
                                if (te is TypeParameterExpr)
                                        has_type_args = true;
 
+#if !MS_COMPATIBLE
+                               if (te.Type.IsSealed && te.Type.IsAbstract) {
+                                       Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
+                                               te.GetSignatureForError ());
+                                       return false;
+                               }
+#endif
                                if (te.Type.IsPointer) {
                                        Report.Error (306, Location, "The type `{0}' may not be used " +
-                                                     "as a type argument", TypeManager.CSharpName (te.Type));
+                                                         "as a type argument", TypeManager.CSharpName (te.Type));
                                        return false;
-                               } else if (te.Type == TypeManager.void_type) {
-                                       Report.Error (1547, Location,
-                                                     "Keyword `void' cannot be used in this context");
+                               }
+
+                               if (te.Type == TypeManager.void_type) {
+                                       Expression.Error_VoidInvalidInTheContext (Location);
                                        return false;
                                }
 
@@ -1307,7 +1364,7 @@ namespace Mono.CSharp {
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.CSharpName (gt);
+                       return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
                }
 
                protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
@@ -1398,6 +1455,11 @@ namespace Mono.CSharp {
 
                public override bool AsAccessible (DeclSpace ds, int flags)
                {
+                       foreach (Type t in atypes) {
+                               if (!ds.AsAccessible (t, flags))
+                                       return false;
+                       }
+
                        return ds.AsAccessible (gt, flags);
                }
 
@@ -1440,7 +1502,6 @@ namespace Mono.CSharp {
                        }
                }
 
-
                public override string FullName {
                        get {
                                return full_name;
@@ -1495,8 +1556,8 @@ namespace Mono.CSharp {
                                if (agc != null) {
                                        if (agc is Constraints)
                                                ((Constraints) agc).Resolve (ec);
-                                       is_class = agc.HasReferenceTypeConstraint;
-                                       is_struct = agc.HasValueTypeConstraint;
+                                       is_class = agc.IsReferenceType;
+                                       is_struct = agc.IsValueType;
                                } else {
                                        is_class = is_struct = false;
                                }
@@ -1769,14 +1830,28 @@ namespace Mono.CSharp {
                ///   Define and resolve the type parameters.
                ///   We're called from Method.Define().
                /// </summary>
-               public bool Define (MethodBuilder mb)
+               public bool Define (MethodBuilder mb, ToplevelBlock block)
                {
-                       GenericTypeParameterBuilder[] gen_params;
                        TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
                        string[] snames = new string [names.Length];
-                       for (int i = 0; i < names.Length; i++)
-                               snames [i] = names [i].Name;
-                       gen_params = mb.DefineGenericParameters (snames);
+                       for (int i = 0; i < names.Length; i++) {
+                               string type_argument_name = names[i].Name;
+                               Parameter p = parameters.GetParameterByName (type_argument_name);
+                               if (p != null) {
+                                       Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
+                                       return false;
+                               }
+                               if (block != null) {
+                                       LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
+                                       if (li != null) {
+                                               Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
+                                               return false;
+                                       }
+                               }
+                               snames[i] = type_argument_name;
+                       }
+
+                       GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
                        for (int i = 0; i < TypeParameters.Length; i++)
                                TypeParameters [i].Define (gen_params [i]);
 
@@ -1791,6 +1866,12 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
+               {
+                       Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
+                               name, collisionWith);
+               }
+
                /// <summary>
                ///   We're called from MethodData.Define() after creating the MethodBuilder.
                /// </summary>
@@ -1839,11 +1920,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
-               {
-                       base.ApplyAttributeBuilder (a, cb);
-               }
-
                public override AttributeTargets AttributeTargets {
                        get {
                                return AttributeTargets.Method | AttributeTargets.ReturnValue;
@@ -1853,6 +1929,16 @@ namespace Mono.CSharp {
                public override string DocCommentHeader {
                        get { return "M:"; }
                }
+
+               public new void VerifyClsCompliance ()
+               {
+                       foreach (TypeParameter tp in TypeParameters) {
+                               if (tp.Constraints == null)
+                                       continue;
+
+                               tp.Constraints.VerifyClsCompliance ();
+                       }
+               }
        }
 
        public class DefaultValueExpression : Expression
@@ -1873,20 +1959,37 @@ namespace Mono.CSharp {
 
                        type = texpr.Type;
 
+                       if (type == TypeManager.void_type) {
+                               Error_VoidInvalidInTheContext (loc);
+                               return null;
+                       }
+
+                       if (type.IsGenericParameter)
+                       {
+                               GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
+                               if (constraints != null && constraints.IsReferenceType)
+                                       return new NullDefault (new NullLiteral (Location), type);
+                       }
+                       else
+                       {
+                               Constant c = New.Constantify(type);
+                               if (c != null)
+                                       return new NullDefault (c, type);
+
+                               if (!TypeManager.IsValueType (type))
+                                       return new NullDefault (new NullLiteral (Location), type);
+                       }
                        eclass = ExprClass.Variable;
                        return this;
                }
 
                public override void Emit (EmitContext ec)
                {
-                       if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
-                               LocalTemporary temp_storage = new LocalTemporary (type);
+                       LocalTemporary temp_storage = new LocalTemporary(type);
 
-                               temp_storage.AddressOf (ec, AddressOp.LoadStore);
-                               ec.ig.Emit (OpCodes.Initobj, type);
-                               temp_storage.Emit (ec);
-                       } else
-                               ec.ig.Emit (OpCodes.Ldnull);
+                       temp_storage.AddressOf(ec, AddressOp.LoadStore);
+                       ec.ig.Emit(OpCodes.Initobj, type);
+                       temp_storage.Emit(ec);
                }
        }
 
@@ -1936,26 +2039,11 @@ namespace Mono.CSharp {
                static public Type generic_ienumerable_type;
                static public Type generic_nullable_type;
 
-               // <remarks>
-               //   Tracks the generic parameters.
-               // </remarks>
-               static PtrHashtable builder_to_type_param;
-
                //
                // These methods are called by code generated by the compiler
                //
                static public MethodInfo activator_create_instance;
 
-               static void InitGenerics ()
-               {
-                       builder_to_type_param = new PtrHashtable ();
-               }
-
-               static void CleanUpGenerics ()
-               {
-                       builder_to_type_param = null;
-               }
-
                static void InitGenericCoreTypes ()
                {
                        activator_type = CoreLookupType ("System", "Activator");
@@ -1985,23 +2073,12 @@ namespace Mono.CSharp {
                        return CoreLookupType (ns, MemberName.MakeName (name, arity));
                }
 
-               public static void AddTypeParameter (Type t, TypeParameter tparam)
-               {
-                       if (!builder_to_type_param.Contains (t))
-                               builder_to_type_param.Add (t, tparam);
-               }
-
                public static TypeContainer LookupGenericTypeContainer (Type t)
                {
                        t = DropGenericTypeArguments (t);
                        return LookupTypeContainer (t);
                }
 
-               public static TypeParameter LookupTypeParameter (Type t)
-               {
-                       return (TypeParameter) builder_to_type_param [t];
-               }
-
                public static GenericConstraints GetTypeParameterConstraints (Type t)
                {
                        if (!t.IsGenericParameter)
@@ -2014,189 +2091,6 @@ namespace Mono.CSharp {
                        return ReflectionConstraints.GetConstraints (t);
                }
 
-               public static bool HasGenericArguments (Type t)
-               {
-                       return GetNumberOfTypeArguments (t) > 0;
-               }
-
-               public static int GetNumberOfTypeArguments (Type t)
-               {
-                       if (t.IsGenericParameter)
-                               return 0;
-                       DeclSpace tc = LookupDeclSpace (t);
-                       if (tc != null)
-                               return tc.IsGeneric ? tc.CountTypeParameters : 0;
-                       else
-                               return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
-               }
-
-               public static Type[] GetTypeArguments (Type t)
-               {
-                       DeclSpace tc = LookupDeclSpace (t);
-                       if (tc != null) {
-                               if (!tc.IsGeneric)
-                                       return Type.EmptyTypes;
-
-                               TypeParameter[] tparam = tc.TypeParameters;
-                               Type[] ret = new Type [tparam.Length];
-                               for (int i = 0; i < tparam.Length; i++) {
-                                       ret [i] = tparam [i].Type;
-                                       if (ret [i] == null)
-                                               throw new InternalErrorException ();
-                               }
-
-                               return ret;
-                       } else
-                               return t.GetGenericArguments ();
-               }
-
-               public static Type DropGenericTypeArguments (Type t)
-               {
-                       if (!t.IsGenericType)
-                               return t;
-                       // Micro-optimization: a generic typebuilder is always a generic type definition
-                       if (t is TypeBuilder)
-                               return t;
-                       return t.GetGenericTypeDefinition ();
-               }
-
-               public static MethodBase DropGenericMethodArguments (MethodBase m)
-               {
-                       if (m.IsGenericMethodDefinition)
-                               return m;
-                       if (m.IsGenericMethod)
-                               return ((MethodInfo) m).GetGenericMethodDefinition ();
-                       if (!m.DeclaringType.IsGenericType)
-                               return m;
-
-                       Type t = m.DeclaringType.GetGenericTypeDefinition ();
-                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
-                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-                       if (m is ConstructorInfo) {
-                               foreach (ConstructorInfo c in t.GetConstructors (bf))
-                                       if (c.MetadataToken == m.MetadataToken)
-                                               return c;
-                       } else {
-                               foreach (MethodBase mb in t.GetMethods (bf))
-                                       if (mb.MetadataToken == m.MetadataToken)
-                                               return mb;
-                       }
-
-                       return m;
-               }
-
-               public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
-               {
-                       if (fi.DeclaringType.IsGenericTypeDefinition ||
-                           !fi.DeclaringType.IsGenericType)
-                               return fi;
-
-                       Type t = fi.DeclaringType.GetGenericTypeDefinition ();
-                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
-                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-                       foreach (FieldInfo f in t.GetFields (bf))
-                               if (f.MetadataToken == fi.MetadataToken)
-                                       return f;
-
-                       return fi;
-               }
-
-               //
-               // Whether `array' is an array of T and `list' is `IList<T>'.
-               // For instance "string[]" -> "IList<string>".
-               //
-               public static bool IsIList (Type array, Type list)
-               {
-                       if (!array.IsArray || !list.IsGenericType)
-                               return false;
-
-                       Type gt = list.GetGenericTypeDefinition ();
-                       if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
-                           (gt != generic_ienumerable_type))
-                               return false;
-
-                       Type arg_type = GetTypeArguments (list) [0];
-                       Type element_type = GetElementType (array);
-
-                       if (arg_type == element_type)
-                               return true;
-                       else if (element_type.IsValueType)
-                               return false;
-
-                       while (element_type != null) {
-                               if (arg_type == element_type)
-                                       return true;
-                               foreach (Type iface in element_type.GetInterfaces ())
-                                       if (arg_type == iface)
-                                               return true;
-                               element_type = element_type.BaseType;
-                       }
-
-                       return false;
-               }
-
-               public static bool IsEqual (Type a, Type b)
-               {
-                       if (a.Equals (b))
-                               return true;
-
-                       if (a.IsGenericParameter && b.IsGenericParameter) {
-                               if (a.DeclaringMethod != b.DeclaringMethod &&
-                                   (a.DeclaringMethod == null || b.DeclaringMethod == null))
-                                       return false;
-                               return a.GenericParameterPosition == b.GenericParameterPosition;
-                       }
-
-                       if (a.IsArray && b.IsArray) {
-                               if (a.GetArrayRank () != b.GetArrayRank ())
-                                       return false;
-                               return IsEqual (a.GetElementType (), b.GetElementType ());
-                       }
-
-                       if (a.IsByRef && b.IsByRef)
-                               return IsEqual (a.GetElementType (), b.GetElementType ());
-
-                       if (a.IsGenericType && b.IsGenericType) {
-                               if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
-                                       return false;
-
-                               Type[] aargs = a.GetGenericArguments ();
-                               Type[] bargs = b.GetGenericArguments ();
-
-                               if (aargs.Length != bargs.Length)
-                                       return false;
-
-                               for (int i = 0; i < aargs.Length; i++) {
-                                       if (!IsEqual (aargs [i], bargs [i]))
-                                               return false;
-                               }
-
-                               return true;
-                       }
-
-                       //
-                       // This is to build with the broken circular dependencies between
-                       // System and System.Configuration in the 2.x profile where we
-                       // end up with a situation where:
-                       //
-                       // System on the second build is referencing the System.Configuration
-                       // that has references to the first System build.
-                       //
-                       // Point in case: NameValueCollection built on the first pass, vs
-                       // NameValueCollection build on the second one.  The problem is that
-                       // we need to override some methods sometimes, or we need to 
-                       //
-                       if (RootContext.BrokenCircularDeps){
-                               if (a.Name == b.Name && a.Namespace == b.Namespace){
-                                       Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
-                                       return true;
-                               }
-                       }
-                       return false;
-               }
-
                /// <summary>
                ///   Check whether `a' and `b' may become equal generic types.
                ///   The algorithm to do that is a little bit complicated.
@@ -2323,56 +2217,6 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               /// <summary>
-               ///   Check whether `type' and `parent' are both instantiations of the same
-               ///   generic type.  Note that we do not check the type parameters here.
-               /// </summary>
-               public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
-               {
-                       int tcount = GetNumberOfTypeArguments (type);
-                       int pcount = GetNumberOfTypeArguments (parent);
-
-                       if (tcount != pcount)
-                               return false;
-
-                       type = DropGenericTypeArguments (type);
-                       parent = DropGenericTypeArguments (parent);
-
-                       return type.Equals (parent);
-               }
-
-               /// <summary>
-               ///   Whether `mb' is a generic method definition.
-               /// </summary>
-               public static bool IsGenericMethodDefinition (MethodBase mb)
-               {
-                       if (mb.DeclaringType is TypeBuilder) {
-                               IMethodData method = (IMethodData) builder_to_method [mb];
-                               if (method == null)
-                                       return false;
-
-                               return method.GenericMethod != null;
-                       }
-
-                       return mb.IsGenericMethodDefinition;
-               }
-
-               /// <summary>
-               ///   Whether `mb' is a generic method definition.
-               /// </summary>
-               public static bool IsGenericMethod (MethodBase mb)
-               {
-                       if (mb.DeclaringType is TypeBuilder) {
-                               IMethodData method = (IMethodData) builder_to_method [mb];
-                               if (method == null)
-                                       return false;
-
-                               return method.GenericMethod != null;
-                       }
-
-                       return mb.IsGenericMethod;
-               }
-
                //
                // Type inference.
                //
@@ -2626,7 +2470,7 @@ namespace Mono.CSharp {
 
                                Argument a = (Argument) arguments [i];
                                if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
-                                   (a.Expr is AnonymousMethod))
+                                   (a.Expr is AnonymousMethodExpression))
                                        continue;
 
                                arg_types [i] = a.Type;
@@ -2669,27 +2513,6 @@ namespace Mono.CSharp {
                        method = ((MethodInfo)method).MakeGenericMethod (infered_types);
                        return true;
                }
-
-               public static bool IsNullableType (Type t)
-               {
-                       return generic_nullable_type == DropGenericTypeArguments (t);
-               }
-
-               public static bool IsNullableTypeOf (Type t, Type nullable)
-               {
-                       if (!IsNullableType (t))
-                               return false;
-
-                       return GetTypeArguments (t) [0] == nullable;
-               }
-
-               public static bool IsNullableValueType (Type t)
-               {
-                       if (!IsNullableType (t))
-                               return false;
-
-                       return GetTypeArguments (t) [0].IsValueType;
-               }
        }
 
        public abstract class Nullable
@@ -3431,14 +3254,13 @@ namespace Mono.CSharp {
                                        return this;
                                }
 
-                               if (unwrap != null) {
-                                       expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
-                                       if (expr != null) {
-                                               left = expr;
-                                               expr = right;
-                                               type = expr.Type;
-                                               return this;
-                                       }
+                               Expression left_null = unwrap != null ? unwrap : left;
+                               expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
+                               if (expr != null) {
+                                       left = expr;
+                                       expr = right;
+                                       type = rtype;
+                                       return this;
                                }
 
                                Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);