In gmcs:
[mono.git] / mcs / gmcs / generic.cs
index 50b6d399991f9c5d863850db587066f08f196e10..ad69957df20d8196ec18c990fd533164084b325d 100644 (file)
@@ -19,7 +19,15 @@ using System.Text.RegularExpressions;
        
 namespace Mono.CSharp {
 
+       /// <summary>
+       ///   Abstract base class for type parameter constraints.
+       ///   The type parameter can come from a generic type definition or from reflection.
+       /// </summary>
        public abstract class GenericConstraints {
+               public abstract string TypeParameter {
+                       get;
+               }
+
                public abstract GenericParameterAttributes Attributes {
                        get;
                }
@@ -33,7 +41,7 @@ namespace Mono.CSharp {
                }
 
                public bool HasValueTypeConstraint {
-                       get { return (Attributes & GenericParameterAttributes.ValueTypeConstraint) != 0; }
+                       get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
                }
 
                public virtual bool HasClassConstraint {
@@ -122,9 +130,9 @@ namespace Mono.CSharp {
                ValueType
        }
 
-       //
-       // Tracks the constraints for a type parameter
-       //
+       /// <summary>
+       ///   Tracks the constraints for a type parameter from a generic type definition.
+       /// </summary>
        public class Constraints : GenericConstraints {
                string name;
                ArrayList constraints;
@@ -142,30 +150,44 @@ namespace Mono.CSharp {
                        this.loc = loc;
                }
 
-               public string TypeParameter {
+               public override string TypeParameter {
                        get {
                                return name;
                        }
                }
 
+               public Constraints Clone ()
+               {
+                       return new Constraints (name, constraints, loc);
+               }
+
                GenericParameterAttributes attrs;
                TypeExpr class_constraint;
                ArrayList iface_constraints;
                ArrayList type_param_constraints;
-               int num_constraints, first_constraint;
+               int num_constraints;
                Type class_constraint_type;
                Type[] iface_constraint_types;
                Type effective_base_type;
+               bool resolved;
+               bool resolved_types;
 
-               public bool Resolve (EmitContext ec)
+               /// <summary>
+               ///   Resolve the constraints - but only resolve things into Expression's, not
+               ///   into actual types.
+               /// </summary>
+               public bool Resolve (IResolveContext ec)
                {
+                       if (resolved)
+                               return true;
+
                        iface_constraints = new ArrayList ();
                        type_param_constraints = new ArrayList ();
 
                        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;
                                }
 
@@ -178,30 +200,34 @@ 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;
                                        }
 
                                        if (sc == SpecialConstraint.ReferenceType)
                                                attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
                                        else
-                                               attrs |= GenericParameterAttributes.ValueTypeConstraint;
+                                               attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
                                        continue;
                                }
 
-                               FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec);
-                               if (fn == null)
+                               int errors = Report.Errors;
+                               FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
+
+                               if (fn == null) {
+                                       if (errors != Report.Errors)
+                                               return false;
+
+                                       NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
                                        return false;
+                               }
 
                                TypeExpr expr;
                                ConstructedType cexpr = fn as ConstructedType;
@@ -211,10 +237,19 @@ namespace Mono.CSharp {
 
                                        expr = cexpr;
                                } else
-                                       expr = fn.ResolveAsTypeTerminal (ec);
+                                       expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
 
-                               if (expr == null)
+                               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)
@@ -230,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;
@@ -238,6 +273,78 @@ namespace Mono.CSharp {
                                num_constraints++;
                        }
 
+                       ArrayList list = new ArrayList ();
+                       foreach (TypeExpr iface_constraint in iface_constraints) {
+                               foreach (Type type in list) {
+                                       if (!type.Equals (iface_constraint.Type))
+                                               continue;
+
+                                       Report.Error (405, loc,
+                                                     "Duplicate constraint `{0}' for type " +
+                                                     "parameter `{1}'.", iface_constraint.GetSignatureForError (),
+                                                     name);
+                                       return false;
+                               }
+
+                               list.Add (iface_constraint.Type);
+                       }
+
+                       foreach (TypeParameterExpr expr in type_param_constraints) {
+                               foreach (Type type in list) {
+                                       if (!type.Equals (expr.Type))
+                                               continue;
+
+                                       Report.Error (405, loc,
+                                                     "Duplicate constraint `{0}' for type " +
+                                                     "parameter `{1}'.", expr.GetSignatureForError (), name);
+                                       return false;
+                               }
+
+                               list.Add (expr.Type);
+                       }
+
+                       iface_constraint_types = new Type [list.Count];
+                       list.CopyTo (iface_constraint_types, 0);
+
+                       if (class_constraint != null) {
+                               class_constraint_type = class_constraint.Type;
+                               if (class_constraint_type == null)
+                                       return false;
+
+                               if (class_constraint_type.IsSealed) {
+                                       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;
+                               }
+
+                               if ((class_constraint_type == TypeManager.array_type) ||
+                                   (class_constraint_type == TypeManager.delegate_type) ||
+                                   (class_constraint_type == TypeManager.enum_type) ||
+                                   (class_constraint_type == TypeManager.value_type) ||
+                                   (class_constraint_type == TypeManager.object_type)) {
+                                       Report.Error (702, loc,
+                                                     "Bound cannot be special class `{0}'",
+                                                     TypeManager.CSharpName (class_constraint_type));
+                                       return false;
+                               }
+                       }
+
+                       if (class_constraint_type != null)
+                               effective_base_type = class_constraint_type;
+                       else if (HasValueTypeConstraint)
+                               effective_base_type = TypeManager.value_type;
+                       else
+                               effective_base_type = TypeManager.object_type;
+
+                       resolved = true;
                        return true;
                }
 
@@ -275,11 +382,16 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public bool ResolveTypes (EmitContext ec)
+               /// <summary>
+               ///   Resolve the constraints into actual types.
+               /// </summary>
+               public bool ResolveTypes (IResolveContext ec)
                {
-                       if (effective_base_type != null)
+                       if (resolved_types)
                                return true;
 
+                       resolved_types = true;
+
                        foreach (object obj in constraints) {
                                ConstructedType cexpr = obj as ConstructedType;
                                if (cexpr == null)
@@ -295,94 +407,43 @@ namespace Mono.CSharp {
                                        return false;
                        }
 
-                       ArrayList list = new ArrayList ();
-
-                       foreach (TypeExpr iface_constraint in iface_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (iface_constraint.Type))
-                                               continue;
-
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", iface_constraint.Type,
-                                                     name);
-                                       return false;
-                               }
-
-                               TypeExpr te = iface_constraint.ResolveAsTypeTerminal (ec);
-                               if (te == null)
-                                       return false;
-
-                               list.Add (te.Type);
-                       }
-
-                       foreach (TypeParameterExpr expr in type_param_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (expr.Type))
-                                               continue;
-
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", expr.Type, name);
+                       for (int i = 0; i < iface_constraints.Count; ++i) {
+                               TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
+                               iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
+                               if (iface_constraint == null)
                                        return false;
-                               }
-
-                               list.Add (expr.Type);
+                               iface_constraints [i] = iface_constraint;
                        }
 
-                       iface_constraint_types = new Type [list.Count];
-                       list.CopyTo (iface_constraint_types, 0);
-
                        if (class_constraint != null) {
-                               TypeExpr te = class_constraint.ResolveAsTypeTerminal (ec);
-                               if (te == null)
-                                       return false;
-
-                               class_constraint_type = te.Type;
-                               if (class_constraint_type == null)
-                                       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", class_constraint_type);
+                               class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
+                               if (class_constraint == null)
                                        return false;
-                               }
-
-                               if ((class_constraint_type == TypeManager.array_type) ||
-                                   (class_constraint_type == TypeManager.delegate_type) ||
-                                   (class_constraint_type == TypeManager.enum_type) ||
-                                   (class_constraint_type == TypeManager.value_type) ||
-                                   (class_constraint_type == TypeManager.object_type)) {
-                                       Report.Error (702, loc,
-                                                     "Bound cannot be special class `{0}'",
-                                                     class_constraint_type);
-                                       return false;
-                               }
                        }
 
-                       if (class_constraint_type != null)
-                               effective_base_type = class_constraint_type;
-                       else if (HasValueTypeConstraint)
-                               effective_base_type = TypeManager.value_type;
-                       else
-                               effective_base_type = TypeManager.object_type;
-
                        return true;
                }
 
-               public bool CheckDependencies (EmitContext ec)
+               /// <summary>
+               ///   Check whether there are no conflicts in our type parameter constraints.
+               ///
+               ///   This is an example:
+               ///
+               ///   class Foo<T,U>
+               ///      where T : class
+               ///      where U : T, struct
+               /// </summary>
+               public bool CheckDependencies ()
                {
                        foreach (TypeParameterExpr expr in type_param_constraints) {
-                               if (!CheckDependencies (expr.TypeParameter, ec))
+                               if (!CheckDependencies (expr.TypeParameter))
                                        return false;
                        }
 
                        return true;
                }
 
-               bool CheckDependencies (TypeParameter tparam, EmitContext ec)
+               bool CheckDependencies (TypeParameter tparam)
                {
                        Constraints constraints = tparam.Constraints;
                        if (constraints == null)
@@ -391,7 +452,7 @@ namespace Mono.CSharp {
                        if (HasValueTypeConstraint && constraints.HasClassConstraint) {
                                Report.Error (455, loc, "Type parameter `{0}' inherits " +
                                              "conflicting constraints `{1}' and `{2}'",
-                                             name, constraints.ClassConstraint,
+                                             name, TypeManager.CSharpName (constraints.ClassConstraint),
                                              "System.ValueType");
                                return false;
                        }
@@ -402,12 +463,12 @@ namespace Mono.CSharp {
                                Type t2 = constraints.ClassConstraint;
                                TypeExpr e2 = constraints.class_constraint;
 
-                               if (!Convert.ImplicitReferenceConversionExists (ec, e1, t2) &&
-                                   !Convert.ImplicitReferenceConversionExists (ec, e2, t1)) {
+                               if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
+                                   !Convert.ImplicitReferenceConversionExists (e2, t1)) {
                                        Report.Error (455, loc,
                                                      "Type parameter `{0}' inherits " +
                                                      "conflicting constraints `{1}' and `{2}'",
-                                                     name, t1, t2);
+                                                     name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
                                        return false;
                                }
                        }
@@ -416,18 +477,13 @@ namespace Mono.CSharp {
                                return true;
 
                        foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
-                               if (!CheckDependencies (expr.TypeParameter, ec))
+                               if (!CheckDependencies (expr.TypeParameter))
                                        return false;
                        }
 
                        return true;
                }
 
-               public void Define (GenericTypeParameterBuilder type)
-               {
-                       type.SetGenericParameterAttributes (attrs);
-               }
-
                public override GenericParameterAttributes Attributes {
                        get { return attrs; }
                }
@@ -448,7 +504,7 @@ namespace Mono.CSharp {
                        get { return effective_base_type; }
                }
 
-               internal bool IsSubclassOf (Type t)
+               public bool IsSubclassOf (Type t)
                {
                        if ((class_constraint_type != null) &&
                            class_constraint_type.IsSubclassOf (t))
@@ -465,7 +521,20 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public bool CheckInterfaceMethod (EmitContext ec, GenericConstraints gc)
+               public Location Location {
+                       get {
+                               return loc;
+                       }
+               }
+
+               /// <summary>
+               ///   This is used when we're implementing a generic interface method.
+               ///   Each method type parameter in implementing method must have the same
+               ///   constraints than the corresponding type parameter in the interface
+               ///   method.  To do that, we're called on each of the implementing method's
+               ///   type parameters.
+               /// </summary>
+               public bool CheckInterfaceMethod (GenericConstraints gc)
                {
                        if (gc.Attributes != attrs)
                                return false;
@@ -498,58 +567,105 @@ 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));
+               }
        }
 
-       //
-       // This type represents a generic type parameter
-       //
+       /// <summary>
+       ///   A type parameter from a generic type definition.
+       /// </summary>
        public class TypeParameter : MemberCore, IMemberContainer {
                string name;
+               DeclSpace decl;
                GenericConstraints gc;
                Constraints constraints;
                Location loc;
                GenericTypeParameterBuilder type;
 
-               public TypeParameter (TypeContainer parent, string name,
-                                     Constraints constraints, Location loc)
-                       : base (parent, new MemberName (name), null, loc)
+               public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
+                                     Constraints constraints, Attributes attrs, Location loc)
+                       : base (parent, new MemberName (name, loc), attrs)
                {
                        this.name = name;
+                       this.decl = decl;
                        this.constraints = constraints;
                        this.loc = loc;
                }
 
                public GenericConstraints GenericConstraints {
-                       get {
-                               return gc != null ? gc : constraints;
-                       }
+                       get { return gc != null ? gc : constraints; }
                }
 
                public Constraints Constraints {
-                       get {
-                               return constraints;
-                       }
+                       get { return constraints; }
                }
 
                public bool HasConstructorConstraint {
-                       get {
-                               if (constraints != null)
-                                       return constraints.HasConstructorConstraint;
+                       get { return constraints != null && constraints.HasConstructorConstraint; }
+               }
 
-                               return false;
-                       }
+               public DeclSpace DeclSpace {
+                       get { return decl; }
                }
 
                public Type Type {
-                       get {
-                               return type;
-                       }
+                       get { return type; }
+               }
+
+               /// <summary>
+               ///   This is the first method which is called during the resolving
+               ///   process; we're called immediately after creating the type parameters
+               ///   with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
+               ///   MethodBuilder).
+               ///
+               ///   We're either called from TypeContainer.DefineType() or from
+               ///   GenericMethod.Define() (called from Method.Define()).
+               /// </summary>
+               public void Define (GenericTypeParameterBuilder type)
+               {
+                       if (this.type != null)
+                               throw new InvalidOperationException ();
+
+                       this.type = type;
+                       TypeManager.AddTypeParameter (type, this);
                }
 
+               /// <summary>
+               ///   This is the second method which is called during the resolving
+               ///   process - in case of class type parameters, we're called from
+               ///   TypeContainer.ResolveType() - after it resolved the class'es
+               ///   base class and interfaces. For method type parameters, we're
+               ///   called immediately after Define().
+               ///
+               ///   We're just resolving the constraints into expressions here, we
+               ///   don't resolve them into actual types.
+               ///
+               ///   Note that in the special case of partial generic classes, we may be
+               ///   called _before_ Define() and we may also be called multiple types.
+               /// </summary>
                public bool Resolve (DeclSpace ds)
                {
                        if (constraints != null) {
-                               if (!constraints.Resolve (ds.EmitContext)) {
+                               if (!constraints.Resolve (ds)) {
                                        constraints = null;
                                        return false;
                                }
@@ -558,22 +674,17 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public void Define (GenericTypeParameterBuilder type)
-               {
-                       if (this.type != null)
-                               throw new InvalidOperationException ();
-
-                       this.type = type;
-                       TypeManager.AddTypeParameter (type, this);
-               }
-
-               public void DefineConstraints ()
-               {
-                       if (constraints != null)
-                               constraints.Define (type);
-               }
-
-               public bool ResolveType (EmitContext ec)
+               /// <summary>
+               ///   This is the third method which is called during the resolving
+               ///   process.  We're called immediately after calling DefineConstraints()
+               ///   on all of the current class'es type parameters.
+               ///
+               ///   Our job is to resolve the constraints to actual types.
+               ///
+               ///   Note that we may have circular dependencies on type parameters - this
+               ///   is why Resolve() and ResolveType() are separate.
+               /// </summary>
+               public bool ResolveType (IResolveContext ec)
                {
                        if (constraints != null) {
                                if (!constraints.ResolveTypes (ec)) {
@@ -585,12 +696,25 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public bool DefineType (EmitContext ec)
+               /// <summary>
+               ///   This is the fourth and last method which is called during the resolving
+               ///   process.  We're called after everything is fully resolved and actually
+               ///   register the constraints with SRE and the TypeManager.
+               /// </summary>
+               public bool DefineType (IResolveContext ec)
                {
                        return DefineType (ec, null, null, false);
                }
 
-               public bool DefineType (EmitContext ec, MethodBuilder builder,
+               /// <summary>
+               ///   This is the fith and last method which is called during the resolving
+               ///   process.  We're called after everything is fully resolved and actually
+               ///   register the constraints with SRE and the TypeManager.
+               ///
+               ///   The `builder', `implementing' and `is_override' arguments are only
+               ///   applicable to method type parameters.
+               /// </summary>
+               public bool DefineType (IResolveContext ec, MethodBuilder builder,
                                        MethodInfo implementing, bool is_override)
                {
                        if (!ResolveType (ec))
@@ -598,22 +722,17 @@ 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;
                                }
 
-                               MethodBase mb = implementing;
-                               if (mb.Mono_IsInflatedMethod)
-                                       mb = mb.GetGenericMethodDefinition ();
+                               MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
 
                                int pos = type.GenericParameterPosition;
-                               ParameterData pd = TypeManager.GetParameterData (mb);
-                               GenericConstraints temp_gc = pd.GenericConstraints (pos);
                                Type mparam = mb.GetGenericArguments () [pos];
+                               GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
 
                                if (temp_gc != null)
                                        gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
@@ -624,7 +743,7 @@ namespace Mono.CSharp {
                                if (constraints != null) {
                                        if (temp_gc == null)
                                                ok = false;
-                                       else if (!constraints.CheckInterfaceMethod (ec, gc))
+                                       else if (!constraints.CheckInterfaceMethod (gc))
                                                ok = false;
                                } else {
                                        if (!is_override && (temp_gc != null))
@@ -638,12 +757,20 @@ namespace Mono.CSharp {
                                                425, loc, "The constraints for type " +
                                                "parameter `{0}' of method `{1}' must match " +
                                                "the constraints for type parameter `{2}' " +
-                                               "of interface method `{3}'.  Consider using " +
+                                               "of interface method `{3}'. Consider using " +
                                                "an explicit interface implementation instead",
                                                Name, TypeManager.CSharpSignature (builder),
-                                               mparam, TypeManager.CSharpSignature (mb));
+                                               TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
                                        return false;
                                }
+                       } else if (DeclSpace is CompilerGeneratedClass) {
+                               TypeParameter[] tparams = DeclSpace.TypeParameters;
+                               Type[] types = new Type [tparams.Length];
+                               for (int i = 0; i < tparams.Length; i++)
+                                       types [i] = tparams [i].Type;
+
+                               if (constraints != null)
+                                       gc = new InflatedConstraints (constraints, types);
                        } else {
                                gc = (GenericConstraints) constraints;
                        }
@@ -655,35 +782,43 @@ namespace Mono.CSharp {
                                type.SetBaseTypeConstraint (gc.ClassConstraint);
 
                        type.SetInterfaceConstraints (gc.InterfaceConstraints);
+                       type.SetGenericParameterAttributes (gc.Attributes);
                        TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
 
                        return true;
                }
 
-               public bool CheckDependencies (EmitContext ec)
+               /// <summary>
+               ///   Check whether there are no conflicts in our type parameter constraints.
+               ///
+               ///   This is an example:
+               ///
+               ///   class Foo<T,U>
+               ///      where T : class
+               ///      where U : T, struct
+               /// </summary>
+               public bool CheckDependencies ()
                {
                        if (constraints != null)
-                               return constraints.CheckDependencies (ec);
+                               return constraints.CheckDependencies ();
 
                        return true;
                }
 
-               public bool UpdateConstraints (EmitContext ec, Constraints new_constraints)
+               /// <summary>
+               ///   This is called for each part of a partial generic type definition.
+               ///
+               ///   If `new_constraints' is not null and we don't already have constraints,
+               ///   they become our constraints.  If we already have constraints, we must
+               ///   check that they're the same.
+               ///   con
+               /// </summary>
+               public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
                {
-                       //
-                       // We're used in partial generic type definitions.
-                       // If `check' is false, we just encountered the first ClassPart which has
-                       // constraints - they become our "real" constraints.
-                       // Otherwise we're called after the type parameters have already been defined
-                       // and check whether the constraints are the same in all parts.
-                       //
                        if (type == null)
                                throw new InvalidOperationException ();
 
-                       if (constraints == null) {
-                               new_constraints = constraints;
-                               return true;
-                       } else if (new_constraints == null)
+                       if (new_constraints == null)
                                return true;
 
                        if (!new_constraints.Resolve (ec))
@@ -691,7 +826,17 @@ namespace Mono.CSharp {
                        if (!new_constraints.ResolveTypes (ec))
                                return false;
 
-                       return constraints.CheckInterfaceMethod (ec, new_constraints);
+                       if (constraints != null) 
+                               return constraints.CheckInterfaceMethod (new_constraints);
+
+                       constraints = new_constraints;
+                       return true;
+               }
+
+               public void EmitAttributes ()
+               {
+                       if (OptAttributes != null)
+                               OptAttributes.Emit ();
                }
 
                public override string DocCommentHeader {
@@ -710,22 +855,21 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               protected override void VerifyObsoleteAttribute ()
-               { }
-
                public override void ApplyAttributeBuilder (Attribute a,
                                                            CustomAttributeBuilder cb)
-               { }
+               {
+                       type.SetCustomAttribute (cb);
+               }
 
                public override AttributeTargets AttributeTargets {
                        get {
-                               return (AttributeTargets) 0;
+                               return (AttributeTargets) AttributeTargets.GenericParameter;
                        }
                }
 
                public override string[] ValidAttributeTargets {
                        get {
-                               return new string [0];
+                               return new string [] { "type parameter" };
                        }
                }
 
@@ -757,13 +901,11 @@ namespace Mono.CSharp {
                public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
                                               MemberFilter filter, object criteria)
                {
-                       if (constraints == null)
+                       if (gc == null)
                                return MemberList.Empty;
 
                        ArrayList members = new ArrayList ();
 
-                       GenericConstraints gc = (GenericConstraints) constraints;
-
                        if (gc.HasClassConstraint) {
                                MemberList list = TypeManager.FindMembers (
                                        gc.ClassConstraint, mt, bf, filter, criteria);
@@ -771,7 +913,8 @@ namespace Mono.CSharp {
                                members.AddRange (list);
                        }
 
-                       foreach (Type t in gc.InterfaceConstraints) {
+                       Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
+                       foreach (Type t in ifaces) {
                                MemberList list = TypeManager.FindMembers (
                                        t, mt, bf, filter, criteria);
 
@@ -797,6 +940,27 @@ namespace Mono.CSharp {
                        return "TypeParameter[" + name + "]";
                }
 
+               public static string GetSignatureForError (TypeParameter[] tp)
+               {
+                       if (tp == null || tp.Length == 0)
+                               return "";
+
+                       StringBuilder sb = new StringBuilder ("<");
+                       for (int i = 0; i < tp.Length; ++i) {
+                               if (i > 0)
+                                       sb.Append (",");
+                               sb.Append (tp[i].GetSignatureForError ());
+                       }
+                       sb.Append ('>');
+                       return sb.ToString ();
+               }
+
+               public void InflateConstraints (Type declaring)
+               {
+                       if (constraints != null)
+                               gc = new InflatedConstraints (constraints, declaring);
+               }
+
                protected class InflatedConstraints : GenericConstraints
                {
                        GenericConstraints gc;
@@ -804,14 +968,15 @@ namespace Mono.CSharp {
                        Type class_constraint;
                        Type[] iface_constraints;
                        Type[] dargs;
-                       Type declaring;
 
                        public InflatedConstraints (GenericConstraints gc, Type declaring)
+                               : this (gc, TypeManager.GetTypeArguments (declaring))
+                       { }
+
+                       public InflatedConstraints (GenericConstraints gc, Type[] dargs)
                        {
                                this.gc = gc;
-                               this.declaring = declaring;
-
-                               dargs = TypeManager.GetTypeArguments (declaring);
+                               this.dargs = dargs;
 
                                ArrayList list = new ArrayList ();
                                if (gc.HasClassConstraint)
@@ -848,14 +1013,24 @@ namespace Mono.CSharp {
                                        return null;
                                if (t.IsGenericParameter)
                                        return dargs [t.GenericParameterPosition];
-                               if (t.IsGenericInstance) {
+                               if (t.IsGenericType) {
+                                       Type[] args = t.GetGenericArguments ();
+                                       Type[] inflated = new Type [args.Length];
+
+                                       for (int i = 0; i < args.Length; i++)
+                                               inflated [i] = inflate (args [i]);
+
                                        t = t.GetGenericTypeDefinition ();
-                                       t = t.BindGenericParameters (dargs);
+                                       t = t.MakeGenericType (inflated);
                                }
 
                                return t;
                        }
 
+                       public override string TypeParameter {
+                               get { return gc.TypeParameter; }
+                       }
+
                        public override GenericParameterAttributes Attributes {
                                get { return gc.Attributes; }
                        }
@@ -874,11 +1049,9 @@ namespace Mono.CSharp {
                }
        }
 
-       //
-       // This type represents a generic type parameter reference.
-       //
-       // These expressions are born in a fully resolved state.
-       //
+       /// <summary>
+       ///   A TypeExpr which already resolved to a type parameter.
+       /// </summary>
        public class TypeParameterExpr : TypeExpr {
                TypeParameter type_parameter;
 
@@ -906,7 +1079,7 @@ namespace Mono.CSharp {
                        this.loc = loc;
                }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
                {
                        type = type_parameter.Type;
 
@@ -924,10 +1097,14 @@ namespace Mono.CSharp {
 
                public void Error_CannotUseAsUnmanagedType (Location loc)
                {
-                       Report.Error (-203, loc, "Can not use type parameter as unamanged type");
+                       Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
                }
        }
 
+       /// <summary>
+       ///   Tracks the type arguments when instantiating a generic type.  We're used in
+       ///   ConstructedType.
+       /// </summary>
        public class TypeArguments {
                public readonly Location Location;
                ArrayList args;
@@ -964,13 +1141,24 @@ namespace Mono.CSharp {
                        args.AddRange (new_args.args);
                }
 
-               public string[] GetDeclarations ()
+               /// <summary>
+               ///   We're used during the parsing process: the parser can't distinguish
+               ///   between type parameters and type arguments.  Because of that, the
+               ///   parser creates a `MemberName' with `TypeArguments' for both cases and
+               ///   in case of a generic type definition, we call GetDeclarations().
+               /// </summary>
+               public TypeParameterName[] GetDeclarations ()
                {
-                       string[] ret = new string [args.Count];
+                       TypeParameterName[] ret = new TypeParameterName [args.Count];
                        for (int i = 0; i < args.Count; i++) {
+                               TypeParameterName name = args [i] as TypeParameterName;
+                               if (name != null) {
+                                       ret [i] = name;
+                                       continue;
+                               }
                                SimpleName sn = args [i] as SimpleName;
                                if (sn != null) {
-                                       ret [i] = sn.Name;
+                                       ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
                                        continue;
                                }
 
@@ -981,6 +1169,10 @@ namespace Mono.CSharp {
                        return ret;
                }
 
+               /// <summary>
+               ///   We may only be used after Resolve() is called and return the fully
+               ///   resolved types.
+               /// </summary>
                public Type[] Arguments {
                        get {
                                return atypes;
@@ -1025,7 +1217,23 @@ namespace Mono.CSharp {
                        return s.ToString ();
                }
 
-               public bool Resolve (EmitContext ec)
+               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>
+               public bool Resolve (IResolveContext ec)
                {
                        int count = args.Count;
                        bool ok = true;
@@ -1033,7 +1241,7 @@ namespace Mono.CSharp {
                        atypes = new Type [count];
 
                        for (int i = 0; i < count; i++){
-                               TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec);
+                               TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
                                if (te == null) {
                                        ok = false;
                                        continue;
@@ -1041,9 +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;
+                               }
+
+                               if (te.Type == TypeManager.void_type) {
+                                       Expression.Error_VoidInvalidInTheContext (Location);
                                        return false;
                                }
 
@@ -1052,14 +1272,37 @@ namespace Mono.CSharp {
                        return ok;
                }
        }
-       
+
+       public class TypeParameterName : SimpleName
+       {
+               Attributes attributes;
+
+               public TypeParameterName (string name, Attributes attrs, Location loc)
+                       : base (name, loc)
+               {
+                       attributes = attrs;
+               }
+
+               public Attributes OptAttributes {
+                       get {
+                               return attributes;
+                       }
+               }
+       }
+
+       /// <summary>
+       ///   An instantiation of a generic type.
+       /// </summary>  
        public class ConstructedType : TypeExpr {
                string full_name;
                FullNamedExpression name;
                TypeArguments args;
                Type[] gen_params, atypes;
                Type gt;
-               
+
+               /// <summary>
+               ///   Instantiate the generic type `fname' with the type arguments `args'.
+               /// </summary>          
                public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
                {
                        loc = l;
@@ -1089,6 +1332,9 @@ namespace Mono.CSharp {
                        eclass = ExprClass.Type;
                }
 
+               /// <summary>
+               ///   This is used to construct the `this' type inside a generic type definition.
+               /// </summary>
                public ConstructedType (Type t, TypeParameter[] type_params, Location l)
                        : this (type_params, l)
                {
@@ -1098,6 +1344,11 @@ namespace Mono.CSharp {
                        full_name = gt.FullName + "<" + args.ToString () + ">";
                }
 
+               /// <summary>
+               ///   Instantiate the generic type `t' with the type arguments `args'.
+               ///   Use this constructor if you already know the fully resolved
+               ///   generic type.
+               /// </summary>          
                public ConstructedType (Type t, TypeArguments args, Location l)
                        : this (args, l)
                {
@@ -1111,49 +1362,181 @@ namespace Mono.CSharp {
                        get { return args; }
                }
 
-               protected string DeclarationName {
-                       get {
-                               StringBuilder sb = new StringBuilder ();
-                               sb.Append (gt.FullName);
-                               sb.Append ("<");
-                               for (int i = 0; i < gen_params.Length; i++) {
-                                       if (i > 0)
-                                               sb.Append (",");
-                                       sb.Append (gen_params [i]);
-                               }
-                               sb.Append (">");
-                               return sb.ToString ();
-                       }
+               public override string GetSignatureForError ()
+               {
+                       return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
                }
 
-               protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
-                                               Type ctype)
+               protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
                {
-                       if (TypeManager.HasGenericArguments (ctype)) {
-                               Type[] types = TypeManager.GetTypeArguments (ctype);
+                       if (!ResolveConstructedType (ec))
+                               return null;
 
-                               TypeArguments new_args = new TypeArguments (loc);
+                       return this;
+               }
 
-                               for (int i = 0; i < types.Length; i++) {
-                                       Type t = types [i];
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public bool CheckConstraints (IResolveContext ec)
+               {
+                       return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
+               }
 
-                                       if (t.IsGenericParameter) {
-                                               int pos = t.GenericParameterPosition;
-                                               t = args.Arguments [pos];
-                                       }
-                                       new_args.Add (new TypeExpression (t, loc));
-                               }
+               /// <summary>
+               ///   Resolve the constructed type, but don't check the constraints.
+               /// </summary>
+               public bool ResolveConstructedType (IResolveContext ec)
+               {
+                       if (type != null)
+                               return true;
+                       // If we already know the fully resolved generic type.
+                       if (gt != null)
+                               return DoResolveType (ec);
 
-                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
-                               if (ct.ResolveAsTypeTerminal (ec) == null)
+                       int num_args;
+                       Type t = name.Type;
+
+                       if (t == null) {
+                               Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
+                               return false;
+                       }
+
+                       num_args = TypeManager.GetNumberOfTypeArguments (t);
+                       if (num_args == 0) {
+                               Report.Error (308, loc,
+                                             "The non-generic type `{0}' cannot " +
+                                             "be used with type arguments.",
+                                             TypeManager.CSharpName (t));
+                               return false;
+                       }
+
+                       gt = t.GetGenericTypeDefinition ();
+                       return DoResolveType (ec);
+               }
+
+               bool DoResolveType (IResolveContext ec)
+               {
+                       //
+                       // Resolve the arguments.
+                       //
+                       if (args.Resolve (ec) == false)
+                               return false;
+
+                       gen_params = gt.GetGenericArguments ();
+                       atypes = args.Arguments;
+
+                       if (atypes.Length != gen_params.Length) {
+                               Report.Error (305, loc,
+                                             "Using the generic type `{0}' " +
+                                             "requires {1} type arguments",
+                                             TypeManager.CSharpName (gt),
+                                             gen_params.Length.ToString ());
+                               return false;
+                       }
+
+                       //
+                       // Now bind the parameters.
+                       //
+                       type = gt.MakeGenericType (atypes);
+                       return true;
+               }
+
+               public Expression GetSimpleName (EmitContext ec)
+               {
+                       return this;
+               }
+
+               public override bool CheckAccessLevel (DeclSpace ds)
+               {
+                       return ds.CheckAccessLevel (gt);
+               }
+
+               public override bool AsAccessible (DeclSpace ds, int flags)
+               {
+                       foreach (Type t in atypes) {
+                               if (!ds.AsAccessible (t, flags))
                                        return false;
-                               ctype = ct.Type;
                        }
 
-                       return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
+                       return ds.AsAccessible (gt, flags);
+               }
+
+               public override bool IsClass {
+                       get { return gt.IsClass; }
+               }
+
+               public override bool IsValueType {
+                       get { return gt.IsValueType; }
+               }
+
+               public override bool IsInterface {
+                       get { return gt.IsInterface; }
+               }
+
+               public override bool IsSealed {
+                       get { return gt.IsSealed; }
+               }
+
+               public override bool Equals (object obj)
+               {
+                       ConstructedType cobj = obj as ConstructedType;
+                       if (cobj == null)
+                               return false;
+
+                       if ((type == null) || (cobj.type == null))
+                               return false;
+
+                       return type == cobj.type;
+               }
+
+               public override int GetHashCode ()
+               {
+                       return base.GetHashCode ();
+               }
+
+               public override string Name {
+                       get {
+                               return full_name;
+                       }
+               }
+
+               public override string FullName {
+                       get {
+                               return full_name;
+                       }
                }
+       }
 
-               protected bool CheckConstraints (EmitContext ec, int index)
+       public abstract class ConstraintChecker
+       {
+               protected readonly Type[] gen_params;
+               protected readonly Type[] atypes;
+               protected readonly Location loc;
+
+               protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
+               {
+                       this.gen_params = gen_params;
+                       this.atypes = atypes;
+                       this.loc = loc;
+               }
+
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public bool CheckConstraints (IResolveContext ec)
+               {
+                       for (int i = 0; i < gen_params.Length; i++) {
+                               if (!CheckConstraints (ec, i))
+                                       return false;
+                       }
+
+                       return true;
+               }
+
+               protected bool CheckConstraints (IResolveContext ec, int index)
                {
                        Type atype = atypes [index];
                        Type ptype = gen_params [index];
@@ -1171,14 +1554,20 @@ namespace Mono.CSharp {
                        if (atype.IsGenericParameter) {
                                GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
                                if (agc != null) {
-                                       is_class = agc.HasReferenceTypeConstraint;
-                                       is_struct = agc.HasValueTypeConstraint;
+                                       if (agc is Constraints)
+                                               ((Constraints) agc).Resolve (ec);
+                                       is_class = agc.IsReferenceType;
+                                       is_struct = agc.IsValueType;
                                } else {
                                        is_class = is_struct = false;
                                }
                        } else {
-                               is_class = atype.IsClass;
-                               is_struct = atype.IsValueType;
+#if MS_COMPATIBLE
+                               is_class = false;
+                               if (!atype.IsGenericType)
+#endif
+                               is_class = atype.IsClass || atype.IsInterface;
+                               is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
                        }
 
                        //
@@ -1189,14 +1578,18 @@ namespace Mono.CSharp {
                                              "a reference type in order to use it " +
                                              "as type parameter `{1}' in the " +
                                              "generic type or method `{2}'.",
-                                             atype, ptype, DeclarationName);
+                                             TypeManager.CSharpName (atype),
+                                             TypeManager.CSharpName (ptype),
+                                             GetSignatureForError ());
                                return false;
                        } else if (gc.HasValueTypeConstraint && !is_struct) {
-                               Report.Error (453, loc, "The type `{0}' must be " +
-                                             "a value type in order to use it " +
+                               Report.Error (453, loc, "The type `{0}' must be " +
+                                             "non-nullable value type in order to use it " +
                                              "as type parameter `{1}' in the " +
                                              "generic type or method `{2}'.",
-                                             atype, ptype, DeclarationName);
+                                             TypeManager.CSharpName (atype),
+                                             TypeManager.CSharpName (ptype),
+                                             GetSignatureForError ());
                                return false;
                        }
 
@@ -1204,33 +1597,17 @@ namespace Mono.CSharp {
                        // The class constraint comes next.
                        //
                        if (gc.HasClassConstraint) {
-                               if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint)) {
-                                       Report.Error (309, loc, "The type `{0}' must be " +
-                                                     "convertible to `{1}' in order to " +
-                                                     "use it as parameter `{2}' in the " +
-                                                     "generic type or method `{3}'",
-                                                     atype, gc.ClassConstraint, ptype, DeclarationName);
+                               if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
                                        return false;
-                               }
                        }
 
                        //
                        // Now, check the interface constraints.
                        //
-                       foreach (Type it in gc.InterfaceConstraints) {
-                               Type itype;
-                               if (it.IsGenericParameter)
-                                       itype = atypes [it.GenericParameterPosition];
-                               else
-                                       itype = it;
-
-                               if (!CheckConstraint (ec, ptype, aexpr, itype)) {
-                                       Report.Error (309, loc, "The type `{0}' must be " +
-                                                     "convertible to `{1}' in order to " +
-                                                     "use it as parameter `{2}' in the " +
-                                                     "generic type or method `{3}'",
-                                                     atype, itype, ptype, DeclarationName);
-                                       return false;
+                       if (gc.InterfaceConstraints != null) {
+                               foreach (Type it in gc.InterfaceConstraints) {
+                                       if (!CheckConstraint (ec, ptype, aexpr, it))
+                                               return false;
                                }
                        }
 
@@ -1244,164 +1621,196 @@ namespace Mono.CSharp {
                        if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
                                return true;
 
-                       MethodGroupExpr mg = Expression.MemberLookup (
-                               ec, atype, ".ctor", MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance |
-                               BindingFlags.DeclaredOnly, loc)
-                               as MethodGroupExpr;
-
-                       if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
-                               Report.Error (310, loc, "The type `{0}' must have a public " +
-                                             "parameterless constructor in order to use it " +
-                                             "as parameter `{1}' in the generic type or " +
-                                             "method `{2}'", atype, ptype, DeclarationName);
-                               return false;
-                       }
+                       if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
+                               return true;
 
-                       return true;
+                       Report_SymbolRelatedToPreviousError ();
+                       Report.SymbolRelatedToPreviousError (atype);
+                       Report.Error (310, loc, "The type `{0}' must have a public " +
+                                     "parameterless constructor in order to use it " +
+                                     "as parameter `{1}' in the generic type or " +
+                                     "method `{2}'",
+                                     TypeManager.CSharpName (atype),
+                                     TypeManager.CSharpName (ptype),
+                                     GetSignatureForError ());
+                       return false;
                }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
+                                               Type ctype)
                {
-                       if (!ResolveConstructedType (ec))
-                               return null;
+                       if (TypeManager.HasGenericArguments (ctype)) {
+                               Type[] types = TypeManager.GetTypeArguments (ctype);
 
-                       return this;
-               }
+                               TypeArguments new_args = new TypeArguments (loc);
 
-               public bool CheckConstraints (EmitContext ec)
-               {
-                       for (int i = 0; i < gen_params.Length; i++) {
-                               if (!CheckConstraints (ec, i))
+                               for (int i = 0; i < types.Length; i++) {
+                                       Type t = types [i];
+
+                                       if (t.IsGenericParameter) {
+                                               int pos = t.GenericParameterPosition;
+                                               t = atypes [pos];
+                                       }
+                                       new_args.Add (new TypeExpression (t, loc));
+                               }
+
+                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
+                               if (ct.ResolveAsTypeStep (ec, false) == null)
                                        return false;
+                               ctype = ct.Type;
+                       } else if (ctype.IsGenericParameter) {
+                               int pos = ctype.GenericParameterPosition;
+                               ctype = atypes [pos];
                        }
 
-                       return true;
+                       if (Convert.ImplicitStandardConversionExists (expr, ctype))
+                               return true;
+
+                       Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
+                       return false;
                }
 
-               public bool ResolveConstructedType (EmitContext ec)
+               bool HasDefaultConstructor (Type containerType, Type atype)
                {
-                       if (type != null)
-                               return true;
-                       if (gt != null)
-                               return DoResolveType (ec);
+                       if (atype.IsAbstract)
+                               return false;
 
-                       int num_args;
-                       Type t = name.Type;
+               again:
+                       atype = TypeManager.DropGenericTypeArguments (atype);
+                       if (atype is TypeBuilder) {
+                               TypeContainer tc = TypeManager.LookupTypeContainer (atype);
+                               if (tc.InstanceConstructors == null) {
+                                       atype = atype.BaseType;
+                                       goto again;
+                               }
 
-                       if (t == null) {
-                               Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
-                               return false;
-                       }
+                               foreach (Constructor c in tc.InstanceConstructors) {
+                                       if ((c.ModFlags & Modifiers.PUBLIC) == 0)
+                                               continue;
+                                       if ((c.Parameters.FixedParameters != null) &&
+                                           (c.Parameters.FixedParameters.Length != 0))
+                                               continue;
+                                       if (c.Parameters.HasArglist || c.Parameters.HasParams)
+                                               continue;
 
-                       num_args = TypeManager.GetNumberOfTypeArguments (t);
-                       if (num_args == 0) {
-                               Report.Error (308, loc,
-                                             "The non-generic type `{0}' cannot " +
-                                             "be used with type arguments.",
-                                             TypeManager.CSharpName (t));
-                               return false;
+                                       return true;
+                               }
                        }
 
-                       gt = t.GetGenericTypeDefinition ();
-                       return DoResolveType (ec);
-               }
-
-               bool DoResolveType (EmitContext ec)
-               {
-                       //
-                       // Resolve the arguments.
-                       //
-                       if (args.Resolve (ec) == false)
-                               return false;
+                       TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
+                       if (tparam != null)
+                               return tparam.HasConstructorConstraint;
 
-                       gen_params = gt.GetGenericArguments ();
-                       atypes = args.Arguments;
+                       MemberList list = TypeManager.FindMembers (
+                               atype, MemberTypes.Constructor,
+                               BindingFlags.Public | BindingFlags.Instance |
+                               BindingFlags.DeclaredOnly, null, null);
 
-                       if (atypes.Length != gen_params.Length) {
-                               Report.Error (305, loc,
-                                             "Using the generic type `{0}' " +
-                                             "requires {1} type arguments",
-                                             TypeManager.GetFullName (gt),
-                                             gen_params.Length);
+                       if (atype.IsAbstract || (list == null))
                                return false;
+
+                       foreach (MethodBase mb in list) {
+                               ParameterData pd = TypeManager.GetParameterData (mb);
+                               if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
+                                       return true;
                        }
 
-                       //
-                       // Now bind the parameters.
-                       //
-                       type = gt.BindGenericParameters (atypes);
-                       return true;
+                       return false;
                }
 
-               public Expression GetSimpleName (EmitContext ec)
-               {
-                       return this;
-               }
+               protected abstract string GetSignatureForError ();
+               protected abstract void Report_SymbolRelatedToPreviousError ();
 
-               public override bool CheckAccessLevel (DeclSpace ds)
+               void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
                {
-                       return ds.CheckAccessLevel (gt);
+                       Report_SymbolRelatedToPreviousError ();
+                       Report.SymbolRelatedToPreviousError (atype);
+                       Report.Error (309, loc, 
+                                     "The type `{0}' must be convertible to `{1}' in order to " +
+                                     "use it as parameter `{2}' in the generic type or method `{3}'",
+                                     TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
+                                     TypeManager.CSharpName (ptype), GetSignatureForError ());
                }
 
-               public override bool AsAccessible (DeclSpace ds, int flags)
+               public static bool CheckConstraints (EmitContext ec, MethodBase definition,
+                                                    MethodBase instantiated, Location loc)
                {
-                       return ds.AsAccessible (gt, flags);
-               }
+                       MethodConstraintChecker checker = new MethodConstraintChecker (
+                               definition, definition.GetGenericArguments (),
+                               instantiated.GetGenericArguments (), loc);
 
-               public override bool IsClass {
-                       get { return gt.IsClass; }
-               }
-
-               public override bool IsValueType {
-                       get { return gt.IsValueType; }
+                       return checker.CheckConstraints (ec);
                }
 
-               public override bool IsInterface {
-                       get { return gt.IsInterface; }
-               }
+               public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
+                                                    Type[] atypes, Location loc)
+               {
+                       TypeConstraintChecker checker = new TypeConstraintChecker (
+                               gt, gen_params, atypes, loc);
 
-               public override bool IsSealed {
-                       get { return gt.IsSealed; }
+                       return checker.CheckConstraints (ec);
                }
 
-               public override bool Equals (object obj)
+               protected class MethodConstraintChecker : ConstraintChecker
                {
-                       ConstructedType cobj = obj as ConstructedType;
-                       if (cobj == null)
-                               return false;
+                       MethodBase definition;
 
-                       if ((type == null) || (cobj.type == null))
-                               return false;
+                       public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
+                                                       Type[] atypes, Location loc)
+                               : base (gen_params, atypes, loc)
+                       {
+                               this.definition = definition;
+                       }
 
-                       return type == cobj.type;
+                       protected override string GetSignatureForError ()
+                       {
+                               return TypeManager.CSharpSignature (definition);
+                       }
+
+                       protected override void Report_SymbolRelatedToPreviousError ()
+                       {
+                               Report.SymbolRelatedToPreviousError (definition);
+                       }
                }
 
-               public override int GetHashCode ()
+               protected class TypeConstraintChecker : ConstraintChecker
                {
-                       return base.GetHashCode ();
-               }
+                       Type gt;
 
-               public override string Name {
-                       get {
-                               return full_name;
+                       public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
+                                                     Location loc)
+                               : base (gen_params, atypes, loc)
+                       {
+                               this.gt = gt;
                        }
-               }
 
+                       protected override string GetSignatureForError ()
+                       {
+                               return TypeManager.CSharpName (gt);
+                       }
 
-               public override string FullName {
-                       get {
-                               return full_name;
+                       protected override void Report_SymbolRelatedToPreviousError ()
+                       {
+                               Report.SymbolRelatedToPreviousError (gt);
                        }
                }
        }
 
+       /// <summary>
+       ///   A generic method definition.
+       /// </summary>
        public class GenericMethod : DeclSpace
        {
-               public GenericMethod (NamespaceEntry ns, TypeContainer parent,
-                                     MemberName name, Location l)
-                       : base (ns, parent, name, null, l)
-               { }
+               Expression return_type;
+               Parameters parameters;
+
+               public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
+                                     Expression return_type, Parameters parameters)
+                       : base (ns, parent, name, null)
+               {
+                       this.return_type = return_type;
+                       this.parameters = parameters;
+               }
 
                public override TypeBuilder DefineType ()
                {
@@ -1410,8 +1819,6 @@ namespace Mono.CSharp {
 
                public override bool Define ()
                {
-                       ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
-
                        for (int i = 0; i < TypeParameters.Length; i++)
                                if (!TypeParameters [i].Resolve (this))
                                        return false;
@@ -1419,11 +1826,32 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public bool Define (MethodBuilder mb)
+               /// <summary>
+               ///   Define and resolve the type parameters.
+               ///   We're called from Method.Define().
+               /// </summary>
+               public bool Define (MethodBuilder mb, ToplevelBlock block)
                {
-                       GenericTypeParameterBuilder[] gen_params;
-                       string[] names = MemberName.TypeArguments.GetDeclarations ();
-                       gen_params = mb.DefineGenericParameters (names);
+                       TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
+                       string[] snames = new string [names.Length];
+                       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]);
 
@@ -1431,13 +1859,22 @@ namespace Mono.CSharp {
                                return false;
 
                        for (int i = 0; i < TypeParameters.Length; i++) {
-                               if (!TypeParameters [i].ResolveType (ec))
+                               if (!TypeParameters [i].ResolveType (this))
                                        return false;
                        }
 
                        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>
                public bool DefineType (EmitContext ec, MethodBuilder mb,
                                        MethodInfo implementing, bool is_override)
                {
@@ -1446,10 +1883,27 @@ namespace Mono.CSharp {
                                            ec, mb, implementing, is_override))
                                        return false;
 
-                       return true;
+                       bool ok = true;
+                       foreach (Parameter p in parameters.FixedParameters){
+                               if (!p.Resolve (ec))
+                                       ok = false;
+                       }
+                       if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
+                               ok = false;
+
+                       return ok;
+               }
+
+               public void EmitAttributes ()
+               {
+                       for (int i = 0; i < TypeParameters.Length; i++)
+                               TypeParameters [i].EmitAttributes ();
+
+                       if (OptAttributes != null)
+                               OptAttributes.Emit ();
                }
 
-               public override bool DefineMembers (TypeContainer parent)
+               public override bool DefineMembers ()
                {
                        return true;
                }
@@ -1466,16 +1920,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
-               {
-                       // FIXME
-               }
-
-               protected override void VerifyObsoleteAttribute()
-               {
-                       // FIXME
-               }
-
                public override AttributeTargets AttributeTargets {
                        get {
                                return AttributeTargets.Method | AttributeTargets.ReturnValue;
@@ -1485,12 +1929,21 @@ 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
        {
                Expression expr;
-               LocalTemporary temp_storage;
 
                public DefaultValueExpression (Expression expr, Location loc)
                {
@@ -1500,26 +1953,43 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       TypeExpr texpr = expr.ResolveAsTypeTerminal (ec);
+                       TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
                        if (texpr == null)
                                return null;
 
                        type = texpr.Type;
-                       if (type.IsGenericParameter || TypeManager.IsValueType (type))
-                               temp_storage = new LocalTemporary (ec, 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 (temp_storage != null) {
-                               temp_storage.AddressOf (ec, AddressOp.LoadStore);
-                               ec.ig.Emit (OpCodes.Initobj, type);
-                               temp_storage.Emit (ec);
-                       } else
-                               ec.ig.Emit (OpCodes.Ldnull);
+                       LocalTemporary temp_storage = new LocalTemporary(type);
+
+                       temp_storage.AddressOf(ec, AddressOp.LoadStore);
+                       ec.ig.Emit(OpCodes.Initobj, type);
+                       temp_storage.Emit(ec);
                }
        }
 
@@ -1547,13 +2017,13 @@ namespace Mono.CSharp {
                        get { return underlying.ToString () + "?"; }
                }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
                {
                        TypeArguments args = new TypeArguments (loc);
                        args.Add (underlying);
 
                        ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
-                       return ctype.ResolveAsTypeTerminal (ec);
+                       return ctype.ResolveAsTypeTerminal (ec, false);
                }
        }
 
@@ -1562,41 +2032,32 @@ namespace Mono.CSharp {
                //
                // A list of core types that the compiler requires or uses
                //
-               static public Type new_constraint_attr_type;
                static public Type activator_type;
+               static public Type generic_ilist_type;
+               static public Type generic_icollection_type;
                static public Type generic_ienumerator_type;
                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");
-                       new_constraint_attr_type = CoreLookupType (
-                               "System.Runtime.CompilerServices.NewConstraintAttribute");
+                       activator_type = CoreLookupType ("System", "Activator");
 
-                       generic_ienumerator_type = CoreLookupType ("System.Collections.Generic.IEnumerator", 1);
-                       generic_ienumerable_type = CoreLookupType ("System.Collections.Generic.IEnumerable", 1);
-                       generic_nullable_type = CoreLookupType ("System.Nullable", 1);
+                       generic_ilist_type = CoreLookupType (
+                               "System.Collections.Generic", "IList", 1);
+                       generic_icollection_type = CoreLookupType (
+                               "System.Collections.Generic", "ICollection", 1);
+                       generic_ienumerator_type = CoreLookupType (
+                               "System.Collections.Generic", "IEnumerator", 1);
+                       generic_ienumerable_type = CoreLookupType (
+                               "System.Collections.Generic", "IEnumerable", 1);
+                       generic_nullable_type = CoreLookupType (
+                               "System", "Nullable", 1);
                }
 
                static void InitGenericCodeHelpers ()
@@ -1607,39 +2068,17 @@ namespace Mono.CSharp {
                                activator_type, "CreateInstance", type_arg);
                }
 
-               static Type CoreLookupType (string name, int arity)
-               {
-                       return CoreLookupType (MemberName.MakeName (name, arity));
-               }
-
-               public static void AddTypeParameter (Type t, TypeParameter tparam)
+               static Type CoreLookupType (string ns, string name, int arity)
                {
-                       if (!builder_to_type_param.Contains (t))
-                               builder_to_type_param.Add (t, tparam);
+                       return CoreLookupType (ns, MemberName.MakeName (name, arity));
                }
 
                public static TypeContainer LookupGenericTypeContainer (Type t)
                {
-                       while (t.IsGenericInstance)
-                               t = t.GetGenericTypeDefinition ();
-
+                       t = DropGenericTypeArguments (t);
                        return LookupTypeContainer (t);
                }
 
-               public static TypeParameter LookupTypeParameter (Type t)
-               {
-                       return (TypeParameter) builder_to_type_param [t];
-               }
-
-               public static bool HasConstructorConstraint (Type t)
-               {
-                       GenericConstraints gc = GetTypeParameterConstraints (t);
-                       if (gc == null)
-                               return false;
-
-                       return (gc.Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0;
-               }
-
                public static GenericConstraints GetTypeParameterConstraints (Type t)
                {
                        if (!t.IsGenericParameter)
@@ -1649,142 +2088,15 @@ namespace Mono.CSharp {
                        if (tparam != null)
                                return tparam.GenericConstraints;
 
-                       return new ReflectionConstraints (t);
-               }
-
-               public static bool IsGeneric (Type t)
-               {
-                       DeclSpace ds = (DeclSpace) builder_to_declspace [t];
-
-                       return ds.IsGeneric;
-               }
-
-               public static bool HasGenericArguments (Type t)
-               {
-                       return GetNumberOfTypeArguments (t) > 0;
-               }
-
-               public static int GetNumberOfTypeArguments (Type t)
-               {
-                       DeclSpace tc = LookupDeclSpace (t);
-                       if (tc != null)
-                               return tc.IsGeneric ? tc.CountTypeParameters : 0;
-                       else
-                               return t.HasGenericArguments ? 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 ();
-               }
-
-               //
-               // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
-               // For instance "string[]" -> "IEnumerable<string>".
-               //
-               public static bool IsIEnumerable (Type array, Type enumerator)
-               {
-                       if (!array.IsArray || !enumerator.IsGenericInstance)
-                               return false;
-
-                       if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
-                               return false;
-
-                       Type[] args = GetTypeArguments (enumerator);
-                       return args [0] == GetElementType (array);
-               }
-
-               public static bool IsEqual (Type a, Type b)
-               {
-                       if (a.Equals (b))
-                               return true;
-
-                       if ((a is TypeBuilder) && a.IsGenericTypeDefinition && b.IsGenericInstance) {
-                               //
-                               // `a' is a generic type definition's TypeBuilder and `b' is a
-                               // generic instance of the same type.
-                               //
-                               // Example:
-                               //
-                               // class Stack<T>
-                               // {
-                               //     void Test (Stack<T> stack) { }
-                               // }
-                               //
-                               // The first argument of `Test' will be the generic instance
-                               // "Stack<!0>" - which is the same type than the "Stack" TypeBuilder.
-                               //
-                               //
-                               // We hit this via Closure.Filter() for gen-82.cs.
-                               //
-                               if (a != b.GetGenericTypeDefinition ())
-                                       return false;
-
-                               Type[] aparams = a.GetGenericArguments ();
-                               Type[] bparams = b.GetGenericArguments ();
-
-                               if (aparams.Length != bparams.Length)
-                                       return false;
-
-                               for (int i = 0; i < aparams.Length; i++)
-                                       if (!IsEqual (aparams [i], bparams [i]))
-                                               return false;
-
-                               return true;
-                       }
-
-                       if ((b is TypeBuilder) && b.IsGenericTypeDefinition && a.IsGenericInstance)
-                               return IsEqual (b, a);
-
-                       if (a.IsGenericParameter && b.IsGenericParameter) {
-                               if ((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.IsGenericInstance && b.IsGenericInstance) {
-                               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;
-                       }
-
-                       return false;
+                       return ReflectionConstraints.GetConstraints (t);
                }
 
-               public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered, Type[] method_infered)
+               /// <summary>
+               ///   Check whether `a' and `b' may become equal generic types.
+               ///   The algorithm to do that is a little bit complicated.
+               /// </summary>
+               public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
+                                                              Type[] method_inferred)
                {
                        if (a.IsGenericParameter) {
                                //
@@ -1804,9 +2116,9 @@ namespace Mono.CSharp {
                                //    class X<T,U> : I<T>, I<U>
                                //    class X<T> : I<T>, I<float>
                                // 
-                               if (b.IsGenericParameter || !b.IsGenericInstance) {
+                               if (b.IsGenericParameter || !b.IsGenericType) {
                                        int pos = a.GenericParameterPosition;
-                                       Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
+                                       Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
                                        if (args [pos] == null) {
                                                args [pos] = b;
                                                return true;
@@ -1838,7 +2150,7 @@ namespace Mono.CSharp {
                        }
 
                        if (b.IsGenericParameter)
-                               return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
+                               return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
 
                        //
                        // At this point, neither a nor b are a type parameter.
@@ -1849,8 +2161,8 @@ namespace Mono.CSharp {
                        // become equal).
                        //
 
-                       if (a.IsGenericInstance || b.IsGenericInstance)
-                               return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
+                       if (a.IsGenericType || b.IsGenericType)
+                               return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
 
                        //
                        // If both of them are arrays.
@@ -1863,7 +2175,7 @@ namespace Mono.CSharp {
                                a = a.GetElementType ();
                                b = b.GetElementType ();
 
-                               return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
+                               return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
                        }
 
                        //
@@ -1878,100 +2190,72 @@ namespace Mono.CSharp {
                // particular instantiation (26.3.1).
                //
                public static bool MayBecomeEqualGenericInstances (Type a, Type b,
-                                                                  Type[] class_infered, Type[] method_infered)
+                                                                  Type[] class_inferred,
+                                                                  Type[] method_inferred)
                {
-                       if (!a.IsGenericInstance || !b.IsGenericInstance)
+                       if (!a.IsGenericType || !b.IsGenericType)
                                return false;
                        if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
                                return false;
 
                        return MayBecomeEqualGenericInstances (
-                               GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
+                               GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
                }
 
                public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
-                                                                  Type[] class_infered, Type[] method_infered)
+                                                                  Type[] class_inferred,
+                                                                  Type[] method_inferred)
                {
                        if (aargs.Length != bargs.Length)
                                return false;
 
                        for (int i = 0; i < aargs.Length; i++) {
-                               if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
+                               if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
                                        return false;
                        }
 
                        return true;
                }
 
-               public static bool IsEqualGenericInstance (Type type, Type parent)
-               {
-                       int tcount = GetNumberOfTypeArguments (type);
-                       int pcount = GetNumberOfTypeArguments (parent);
-
-                       if (type.IsGenericInstance)
-                               type = type.GetGenericTypeDefinition ();
-                       if (parent.IsGenericInstance)
-                               parent = parent.GetGenericTypeDefinition ();
-
-                       if (tcount != pcount)
-                               return false;
-
-                       return type.Equals (parent);
-               }
-
-               static public bool IsGenericMethod (MethodBase mb)
+               static bool UnifyType (Type pt, Type at, Type[] inferred)
                {
-                       if (mb.DeclaringType is TypeBuilder) {
-                               IMethodData method = (IMethodData) builder_to_method [mb];
-                               if (method == null)
-                                       return false;
-
-                               return method.GenericMethod != null;
-                       }
-
-                       return mb.IsGenericMethodDefinition;
-               }
-
-               //
-               // Type inference.
-               //
+                       if (pt.IsGenericParameter) {
+                               if (pt.DeclaringMethod == null)
+                                       return pt == at;
 
-               static bool InferType (Type pt, Type at, Type[] infered)
-               {
-                       if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
                                int pos = pt.GenericParameterPosition;
 
-                               if (infered [pos] == null) {
-                                       Type check = at;
-                                       while (check.IsArray)
-                                               check = check.GetElementType ();
-
-                                       if (pt == check)
-                                               return false;
-
-                                       infered [pos] = at;
-                                       return true;
-                               }
-
-                               if (infered [pos] != at)
-                                       return false;
+                               if (inferred [pos] == null)
+                                       inferred [pos] = at;
 
-                               return true;
+                               return inferred [pos] == at;
                        }
 
                        if (!pt.ContainsGenericParameters) {
                                if (at.ContainsGenericParameters)
-                                       return InferType (at, pt, infered);
+                                       return UnifyType (at, pt, inferred);
                                else
                                        return true;
                        }
 
                        if (at.IsArray) {
-                               if (!pt.IsArray ||
-                                   (at.GetArrayRank () != pt.GetArrayRank ()))
+                               if (pt.IsArray) {
+                                       if (at.GetArrayRank () != pt.GetArrayRank ())
+                                               return false;
+
+                                       return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
+                               }
+
+                               if (!pt.IsGenericType)
+                                       return false;
+
+                               Type gt = pt.GetGenericTypeDefinition ();
+                               if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
+                                   (gt != generic_ienumerable_type))
                                        return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               Type[] args = GetTypeArguments (pt);
+                               return UnifyType (args [0], at.GetElementType (), inferred);
                        }
 
                        if (pt.IsArray) {
@@ -1979,100 +2263,73 @@ namespace Mono.CSharp {
                                    (pt.GetArrayRank () != at.GetArrayRank ()))
                                        return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
                        }
 
                        if (pt.IsByRef && at.IsByRef)
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
                        ArrayList list = new ArrayList ();
-                       if (at.IsGenericInstance)
+                       if (at.IsGenericType)
                                list.Add (at);
-                       else {
-                               for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
-                                       list.Add (bt);
-
-                               list.AddRange (TypeManager.GetInterfaces (at));
-                       }
+                       for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
+                               list.Add (bt);
 
-                       bool found_one = false;
+                       list.AddRange (TypeManager.GetInterfaces (at));
 
                        foreach (Type type in list) {
-                               if (!type.IsGenericInstance)
+                               if (!type.IsGenericType)
                                        continue;
 
-                               Type[] infered_types = new Type [infered.Length];
-
-                               if (!InferGenericInstance (pt, type, infered_types))
+                               if (DropGenericTypeArguments (pt) != DropGenericTypeArguments (type))
                                        continue;
 
-                               for (int i = 0; i < infered_types.Length; i++) {
-                                       if (infered [i] == null) {
-                                               infered [i] = infered_types [i];
-                                               continue;
-                                       }
-
-                                       if (infered [i] != infered_types [i])
-                                               return false;
-                               }
-
-                               found_one = true;
+                               if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
+                                       return false;
                        }
 
-                       return found_one;
+                       return true;
                }
 
-               static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
+               static bool UnifyTypes (Type[] pts, Type [] ats, Type [] inferred)
                {
-                       Type[] at_args = at.GetGenericArguments ();
-                       Type[] pt_args = pt.GetGenericArguments ();
-
-                       if (at_args.Length != pt_args.Length)
-                               return false;
-
-                       for (int i = 0; i < at_args.Length; i++) {
-                               if (!InferType (pt_args [i], at_args [i], infered_types))
-                                       return false;
-                       }
-
-                       for (int i = 0; i < infered_types.Length; i++) {
-                               if (infered_types [i] == null)
+                       for (int i = 0; i < ats.Length; i++) {
+                               if (!UnifyType (pts [i], ats [i], inferred))
                                        return false;
                        }
-
                        return true;
                }
 
+               /// <summary>
+               ///   Type inference.  Try to infer the type arguments from the params method
+               ///   `method', which is invoked with the arguments `arguments'.  This is used
+               ///   when resolving an Invocation or a DelegateInvocation and the user
+               ///   did not explicitly specify type arguments.
+               /// </summary>
                public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
                                                             ref MethodBase method)
                {
-                       if ((arguments == null) || !TypeManager.IsGenericMethod (method))
+                       if (!TypeManager.IsGenericMethod (method))
                                return true;
 
-                       int arg_count;
-                       
-                       if (arguments == null)
-                               arg_count = 0;
-                       else
-                               arg_count = arguments.Count;
-                       
-                       ParameterData pd = TypeManager.GetParameterData (method);
+                       // if there are no arguments, there's no way to infer the type-arguments
+                       if (arguments == null || arguments.Count == 0)
+                               return false;
 
+                       ParameterData pd = TypeManager.GetParameterData (method);
                        int pd_count = pd.Count;
+                       int arg_count = arguments.Count;
 
                        if (pd_count == 0)
                                return false;
-                       
+
                        if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
                                return false;
-                       
+
                        if (pd_count - 1 > arg_count)
                                return false;
-                       
-                       if (pd_count == 1 && arg_count == 0)
-                               return true;
 
                        Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                       Type[] inferred_types = new Type [method_args.Length];
 
                        //
                        // If we have come this far, the case which
@@ -2088,7 +2345,7 @@ namespace Mono.CSharp {
                                Type pt = pd.ParameterType (i);
                                Type at = a.Type;
 
-                               if (!InferType (pt, at, infered_types))
+                               if (!UnifyType (pt, at, inferred_types))
                                        return false;
                        }
 
@@ -2100,39 +2357,43 @@ namespace Mono.CSharp {
                                if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
                                        continue;
 
-                               if (!InferType (element_type, a.Type, infered_types))
+                               if (!UnifyType (element_type, a.Type, inferred_types))
                                        return false;
                        }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
+                       for (int i = 0; i < inferred_types.Length; i++)
+                               if (inferred_types [i] == null)
                                        return false;
 
-                       method = method.BindGenericParameters (infered_types);
+                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
                        return true;
                }
 
-               public static bool InferTypeArguments (Type[] param_types, Type[] arg_types, Type[] infered_types)
+               static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
+                                               Type[] inferred_types)
                {
-                       if (infered_types == null)
-                               return false;
-
                        for (int i = 0; i < arg_types.Length; i++) {
                                if (arg_types [i] == null)
                                        continue;
 
-                               if (!InferType (param_types [i], arg_types [i], infered_types))
+                               if (!UnifyType (param_types [i], arg_types [i], inferred_types))
                                        return false;
                        }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
+                       for (int i = 0; i < inferred_types.Length; i++)
+                               if (inferred_types [i] == null)
                                        return false;
 
                        return true;
                }
 
-               public static bool InferTypeArguments (EmitContext ec, ArrayList arguments,
+               /// <summary>
+               ///   Type inference.  Try to infer the type arguments from `method',
+               ///   which is invoked with the arguments `arguments'.  This is used
+               ///   when resolving an Invocation or a DelegateInvocation and the user
+               ///   did not explicitly specify type arguments.
+               /// </summary>
+               public static bool InferTypeArguments (ArrayList arguments,
                                                       ref MethodBase method)
                {
                        if (!TypeManager.IsGenericMethod (method))
@@ -2157,10 +2418,12 @@ namespace Mono.CSharp {
                                        break;
                                }
                        }
+
+                       // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
                        if (!is_open)
-                               return true;
+                               return !TypeManager.IsGenericMethodDefinition (method);
 
-                       Type[] infered_types = new Type [method_args.Length];
+                       Type[] inferred_types = new Type [method_args.Length];
 
                        Type[] param_types = new Type [pd.Count];
                        Type[] arg_types = new Type [pd.Count];
@@ -2169,20 +2432,24 @@ namespace Mono.CSharp {
                                param_types [i] = pd.ParameterType (i);
 
                                Argument a = (Argument) arguments [i];
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
+                                   (a.Expr is AnonymousMethodExpression))
                                        continue;
 
                                arg_types [i] = a.Type;
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, infered_types))
+                       if (!InferTypeArguments (param_types, arg_types, inferred_types))
                                return false;
 
-                       method = method.BindGenericParameters (infered_types);
+                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
                        return true;
                }
 
-               public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
+               /// <summary>
+               ///   Type inference.
+               /// </summary>
+               public static bool InferTypeArguments (ParameterData apd,
                                                       ref MethodBase method)
                {
                        if (!TypeManager.IsGenericMethod (method))
@@ -2193,7 +2460,7 @@ namespace Mono.CSharp {
                                return false;
 
                        Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                       Type[] inferred_types = new Type [method_args.Length];
 
                        Type[] param_types = new Type [pd.Count];
                        Type[] arg_types = new Type [pd.Count];
@@ -2203,26 +2470,17 @@ namespace Mono.CSharp {
                                arg_types [i] = apd.ParameterType (i);
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, infered_types))
+                       if (!InferTypeArguments (param_types, arg_types, inferred_types))
                                return false;
 
-                       method = method.BindGenericParameters (infered_types);
+                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
                        return true;
                }
-
-               public static bool IsNullableType (Type t)
-               {
-                       if (!t.IsGenericInstance)
-                               return false;
-
-                       Type gt = t.GetGenericTypeDefinition ();
-                       return gt == generic_nullable_type;
-               }
        }
 
        public abstract class Nullable
        {
-               protected sealed class NullableInfo
+               public sealed class NullableInfo
                {
                        public readonly Type Type;
                        public readonly Type UnderlyingType;
@@ -2235,8 +2493,8 @@ namespace Mono.CSharp {
                                Type = type;
                                UnderlyingType = TypeManager.GetTypeArguments (type) [0];
 
-                               PropertyInfo has_value_pi = type.GetProperty ("HasValue");
-                               PropertyInfo value_pi = type.GetProperty ("Value");
+                               PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
+                               PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
 
                                HasValue = has_value_pi.GetGetMethod (false);
                                Value = value_pi.GetGetMethod (false);
@@ -2244,7 +2502,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
+               public class Unwrap : Expression, IMemoryLocation, IAssignMethod
                {
                        Expression expr;
                        NullableInfo info;
@@ -2252,10 +2510,15 @@ namespace Mono.CSharp {
                        LocalTemporary temp;
                        bool has_temp;
 
-                       public Unwrap (Expression expr, Location loc)
+                       protected Unwrap (Expression expr)
                        {
                                this.expr = expr;
-                               this.loc = loc;
+                               this.loc = expr.Location;
+                       }
+
+                       public static Unwrap Create (Expression expr, EmitContext ec)
+                       {
+                               return new Unwrap (expr).Resolve (ec) as Unwrap;
                        }
 
                        public override Expression DoResolve (EmitContext ec)
@@ -2264,8 +2527,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               if (!(expr is IMemoryLocation))
-                                       temp = new LocalTemporary (ec, expr.Type);
+                               temp = new LocalTemporary (expr.Type);
 
                                info = new NullableInfo (expr.Type);
                                type = info.UnderlyingType;
@@ -2285,6 +2547,11 @@ namespace Mono.CSharp {
                                ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
                        }
 
+                       public void Store (EmitContext ec)
+                       {
+                               create_temp (ec);
+                       }
+
                        void create_temp (EmitContext ec)
                        {
                                if ((temp != null) && !has_temp) {
@@ -2319,26 +2586,52 @@ namespace Mono.CSharp {
                        public void EmitAssign (EmitContext ec, Expression source,
                                                bool leave_copy, bool prepare_for_load)
                        {
-                               source.Emit (ec);
-                               ec.ig.Emit (OpCodes.Newobj, info.Constructor);
+                               InternalWrap wrap = new InternalWrap (source, info, loc);
+                               ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
+                       }
+
+                       protected class InternalWrap : Expression
+                       {
+                               public Expression expr;
+                               public NullableInfo info;
+
+                               public InternalWrap (Expression expr, NullableInfo info, Location loc)
+                               {
+                                       this.expr = expr;
+                                       this.info = info;
+                                       this.loc = loc;
 
-                               if (leave_copy)
-                                       ec.ig.Emit (OpCodes.Dup);
+                                       type = info.Type;
+                                       eclass = ExprClass.Value;
+                               }
+
+                               public override Expression DoResolve (EmitContext ec)
+                               {
+                                       return this;
+                               }
 
-                               Expression empty = new EmptyExpression (expr.Type);
-                               ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
+                               public override void Emit (EmitContext ec)
+                               {
+                                       expr.Emit (ec);
+                                       ec.ig.Emit (OpCodes.Newobj, info.Constructor);
+                               }
                        }
                }
 
-               protected class Wrap : Expression
+               public class Wrap : Expression
                {
                        Expression expr;
                        NullableInfo info;
 
-                       public Wrap (Expression expr, Location loc)
+                       protected Wrap (Expression expr)
                        {
                                this.expr = expr;
-                               this.loc = loc;
+                               this.loc = expr.Location;
+                       }
+
+                       public static Wrap Create (Expression expr, EmitContext ec)
+                       {
+                               return new Wrap (expr).Resolve (ec) as Wrap;
                        }
 
                        public override Expression DoResolve (EmitContext ec)
@@ -2348,7 +2641,7 @@ namespace Mono.CSharp {
                                        return null;
 
                                TypeExpr target_type = new NullableType (expr.Type, loc);
-                               target_type = target_type.ResolveAsTypeTerminal (ec);
+                               target_type = target_type.ResolveAsTypeTerminal (ec, false);
                                if (target_type == null)
                                        return null;
 
@@ -2365,11 +2658,11 @@ namespace Mono.CSharp {
                        }
                }
 
-               public class NullableLiteral : Expression, IMemoryLocation {
+               public class NullableLiteral : NullLiteral, IMemoryLocation {
                        public NullableLiteral (Type target_type, Location loc)
+                               : base (loc)
                        {
                                this.type = target_type;
-                               this.loc = loc;
 
                                eclass = ExprClass.Value;
                        }
@@ -2381,7 +2674,7 @@ namespace Mono.CSharp {
 
                        public override void Emit (EmitContext ec)
                        {
-                               LocalTemporary value_target = new LocalTemporary (ec, type);
+                               LocalTemporary value_target = new LocalTemporary (type);
 
                                value_target.AddressOf (ec, AddressOp.Store);
                                ec.ig.Emit (OpCodes.Initobj, type);
@@ -2390,7 +2683,7 @@ namespace Mono.CSharp {
 
                        public void AddressOf (EmitContext ec, AddressOp Mode)
                        {
-                               LocalTemporary value_target = new LocalTemporary (ec, type);
+                               LocalTemporary value_target = new LocalTemporary (type);
                                        
                                value_target.AddressOf (ec, AddressOp.Store);
                                ec.ig.Emit (OpCodes.Initobj, type);
@@ -2415,7 +2708,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
+                               unwrap = Unwrap.Create (expr, ec);
                                if (unwrap == null)
                                        return null;
 
@@ -2423,7 +2716,7 @@ namespace Mono.CSharp {
                                if (underlying == null)
                                        return null;
 
-                               wrap = new Wrap (underlying, loc).Resolve (ec);
+                               wrap = Wrap.Create (underlying, ec);
                                if (wrap == null)
                                        return null;
 
@@ -2510,8 +2803,7 @@ namespace Mono.CSharp {
 
                public class LiftedConditional : Lifted
                {
-                       Expression expr, true_expr, false_expr;
-                       Unwrap unwrap;
+                       Expression true_expr, false_expr;
 
                        public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
                                                  Location loc)
@@ -2523,7 +2815,7 @@ namespace Mono.CSharp {
 
                        protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
                        {
-                               return new Conditional (unwrap, true_expr, false_expr, loc);
+                               return new Conditional (unwrap, true_expr, false_expr);
                        }
                }
 
@@ -2531,7 +2823,8 @@ namespace Mono.CSharp {
                {
                        public readonly Binary.Operator Oper;
 
-                       Expression left, right, underlying, null_value, bool_wrap;
+                       Expression left, right, original_left, original_right;
+                       Expression underlying, null_value, bool_wrap;
                        Unwrap left_unwrap, right_unwrap;
                        bool is_equality, is_comparision, is_boolean;
 
@@ -2539,39 +2832,45 @@ namespace Mono.CSharp {
                                                     Location loc)
                        {
                                this.Oper = op;
-                               this.left = left;
-                               this.right = right;
+                               this.left = original_left = left;
+                               this.right = original_right = right;
                                this.loc = loc;
                        }
 
                        public override Expression DoResolve (EmitContext ec)
                        {
                                if (TypeManager.IsNullableType (left.Type)) {
-                                       left_unwrap = new Unwrap (left, loc);
-                                       left = left_unwrap.Resolve (ec);
+                                       left = left_unwrap = Unwrap.Create (left, ec);
                                        if (left == null)
                                                return null;
                                }
 
                                if (TypeManager.IsNullableType (right.Type)) {
-                                       right_unwrap = new Unwrap (right, loc);
-                                       right = right_unwrap.Resolve (ec);
+                                       right = right_unwrap = Unwrap.Create (right, ec);
                                        if (right == null)
                                                return null;
                                }
 
-                               if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
-                                    (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
+                               if ((Oper == Binary.Operator.LogicalAnd) ||
+                                   (Oper == Binary.Operator.LogicalOr)) {
+                                       Binary.Error_OperatorCannotBeApplied (
+                                               loc, Binary.OperName (Oper),
+                                               original_left.GetSignatureForError (),
+                                               original_right.GetSignatureForError ());
+                                       return null;
+                               }
+
+                               if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
                                    ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
                                        Expression empty = new EmptyExpression (TypeManager.bool_type);
-                                       bool_wrap = new Wrap (empty, loc).Resolve (ec);
+                                       bool_wrap = Wrap.Create (empty, ec);
                                        null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
 
                                        type = bool_wrap.Type;
                                        is_boolean = true;
                                } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
                                        if (!(left is NullLiteral) && !(right is NullLiteral)) {
-                                               underlying = new Binary (Oper, left, right, loc).Resolve (ec);
+                                               underlying = new Binary (Oper, left, right).Resolve (ec);
                                                if (underlying == null)
                                                        return null;
                                        }
@@ -2582,18 +2881,18 @@ namespace Mono.CSharp {
                                           (Oper == Binary.Operator.GreaterThan) ||
                                           (Oper == Binary.Operator.LessThanOrEqual) ||
                                           (Oper == Binary.Operator.GreaterThanOrEqual)) {
-                                       underlying = new Binary (Oper, left, right, loc).Resolve (ec);
+                                       underlying = new Binary (Oper, left, right).Resolve (ec);
                                        if (underlying == null)
                                                return null;
 
                                        type = TypeManager.bool_type;
                                        is_comparision = true;
                                } else {
-                                       underlying = new Binary (Oper, left, right, loc).Resolve (ec);
+                                       underlying = new Binary (Oper, left, right).Resolve (ec);
                                        if (underlying == null)
                                                return null;
 
-                                       underlying = new Wrap (underlying, loc).Resolve (ec);
+                                       underlying = Wrap.Create (underlying, ec);
                                        if (underlying == null)
                                                return null;
 
@@ -2673,73 +2972,70 @@ namespace Mono.CSharp {
                        {
                                ILGenerator ig = ec.ig;
 
-                               Label left_not_null_label = ig.DefineLabel ();
-                               Label false_label = ig.DefineLabel ();
-                               Label true_label = ig.DefineLabel ();
-                               Label end_label = ig.DefineLabel ();
+                               // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
+                               if (left is NullLiteral) {
+                                       if (right_unwrap == null)
+                                               throw new InternalErrorException ();
+                                       right_unwrap.EmitCheck (ec);
+                                       if (Oper == Binary.Operator.Equality) {
+                                               ig.Emit (OpCodes.Ldc_I4_0);
+                                               ig.Emit (OpCodes.Ceq);
+                                       }
+                                       return;
+                               }
 
-                               if (left_unwrap != null) {
+                               if (right is NullLiteral) {
+                                       if (left_unwrap == null)
+                                               throw new InternalErrorException ();
                                        left_unwrap.EmitCheck (ec);
-                                       if (right is NullLiteral) {
-                                               if (Oper == Binary.Operator.Equality)
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                               else
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                       } else if (right_unwrap != null) {
-                                               ig.Emit (OpCodes.Dup);
-                                               ig.Emit (OpCodes.Brtrue, left_not_null_label);
-                                               right_unwrap.EmitCheck (ec);
+                                       if (Oper == Binary.Operator.Equality) {
+                                               ig.Emit (OpCodes.Ldc_I4_0);
                                                ig.Emit (OpCodes.Ceq);
-                                               if (Oper == Binary.Operator.Inequality) {
-                                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                                       ig.Emit (OpCodes.Ceq);
-                                               }
-                                               ig.Emit (OpCodes.Br, end_label);
-
-                                               ig.MarkLabel (left_not_null_label);
-                                               ig.Emit (OpCodes.Pop);
-                                       } else {
-                                               if (Oper == Binary.Operator.Equality)
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                               else
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
                                        }
+                                       return;
                                }
 
-                               if (right_unwrap != null) {
+                               Label both_have_value_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               if (left_unwrap != null && right_unwrap != null) {
+                                       Label dissimilar_label = ig.DefineLabel ();
+
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Dup);
                                        right_unwrap.EmitCheck (ec);
-                                       if (left is NullLiteral) {
-                                               if (Oper == Binary.Operator.Equality)
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                               else
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                       } else {
-                                               if (Oper == Binary.Operator.Equality)
-                                                       ig.Emit (OpCodes.Brfalse, false_label);
-                                               else
-                                                       ig.Emit (OpCodes.Brfalse, true_label);
-                                       }
-                               }
+                                       ig.Emit (OpCodes.Bne_Un, dissimilar_label);
+
+                                       ig.Emit (OpCodes.Brtrue, both_have_value_label);
 
-                               bool left_is_null = left is NullLiteral;
-                               bool right_is_null = right is NullLiteral;
-                               if (left_is_null || right_is_null) {
-                                       if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
-                                           ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null)))
-                                               ig.Emit (OpCodes.Br, true_label);
+                                       // both are null
+                                       if (Oper == Binary.Operator.Equality)
+                                               ig.Emit (OpCodes.Ldc_I4_1);
                                        else
-                                               ig.Emit (OpCodes.Br, false_label);
-                               } else {
-                                       underlying.Emit (ec);
+                                               ig.Emit (OpCodes.Ldc_I4_0);
                                        ig.Emit (OpCodes.Br, end_label);
+
+                                       ig.MarkLabel (dissimilar_label);
+                                       ig.Emit (OpCodes.Pop);
+                               } else if (left_unwrap != null) {
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brtrue, both_have_value_label);
+                               } else if (right_unwrap != null) {
+                                       right_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brtrue, both_have_value_label);
+                               } else {
+                                       throw new InternalErrorException ("shouldn't get here");
                                }
 
-                               ig.MarkLabel (false_label);
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               // one is null while the other isn't
+                               if (Oper == Binary.Operator.Equality)
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                               else
+                                       ig.Emit (OpCodes.Ldc_I4_1);
                                ig.Emit (OpCodes.Br, end_label);
 
-                               ig.MarkLabel (true_label);
-                               ig.Emit (OpCodes.Ldc_I4_1);
+                               ig.MarkLabel (both_have_value_label);
+                               underlying.Emit (ec);
 
                                ig.MarkLabel (end_label);
                        }
@@ -2772,6 +3068,11 @@ namespace Mono.CSharp {
 
                        public override void Emit (EmitContext ec)
                        {
+                               if (left_unwrap != null)
+                                       left_unwrap.Store (ec);
+                               if (right_unwrap != null)
+                                       right_unwrap.Store (ec);
+
                                if (is_boolean) {
                                        EmitBoolean (ec);
                                        return;
@@ -2824,9 +3125,8 @@ namespace Mono.CSharp {
 
                        public override Expression DoResolve (EmitContext ec)
                        {
-                               unwrap = new Unwrap (expr, loc);
-                               expr = unwrap.Resolve (ec);
-                               if (expr == null)
+                               unwrap = Unwrap.Create (expr, ec);
+                               if (unwrap == null)
                                        return null;
 
                                if (unwrap.Type != TypeManager.bool_type)
@@ -2899,7 +3199,7 @@ namespace Mono.CSharp {
                                if (TypeManager.IsNullableType (ltype)) {
                                        NullableInfo info = new NullableInfo (ltype);
 
-                                       unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
+                                       unwrap = Unwrap.Create (left, ec);
                                        if (unwrap == null)
                                                return null;
 
@@ -2917,14 +3217,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);
@@ -2941,15 +3240,26 @@ namespace Mono.CSharp {
                                if (unwrap != null) {
                                        unwrap.EmitCheck (ec);
                                        ig.Emit (OpCodes.Brfalse, is_null_label);
-                               }
 
-                               left.Emit (ec);
-                               ig.Emit (OpCodes.Br, end_label);
+                                       left.Emit (ec);
+                                       ig.Emit (OpCodes.Br, end_label);
 
-                               ig.MarkLabel (is_null_label);
-                               expr.Emit (ec);
+                                       ig.MarkLabel (is_null_label);
+                                       expr.Emit (ec);
 
-                               ig.MarkLabel (end_label);
+                                       ig.MarkLabel (end_label);
+                               } else {
+                                       left.Emit (ec);
+                                       ig.Emit (OpCodes.Dup);
+                                       ig.Emit (OpCodes.Brtrue, end_label);
+
+                                       ig.MarkLabel (is_null_label);
+
+                                       ig.Emit (OpCodes.Pop);
+                                       expr.Emit (ec);
+
+                                       ig.MarkLabel (end_label);
+                               }
                        }
                }
 
@@ -2975,7 +3285,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
+                               unwrap = Unwrap.Create (expr, ec);
                                if (unwrap == null)
                                        return null;