manually synchronized with 56802
[mono.git] / mcs / gmcs / generic.cs
index 22e2d0ed925420c51652e83e946a4d9ff14ae9f5..09acdf3ea59c8a7ee650c88acc53dbd5532274a3 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,7 +150,7 @@ namespace Mono.CSharp {
                        this.loc = loc;
                }
 
-               public string TypeParameter {
+               public override string TypeParameter {
                        get {
                                return name;
                        }
@@ -152,13 +160,22 @@ namespace Mono.CSharp {
                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;
 
+               /// <summary>
+               ///   Resolve the constraints - but only resolve things into Expression's, not
+               ///   into actual types.
+               /// </summary>
                public bool Resolve (EmitContext ec)
                {
+                       if (resolved)
+                               return true;
+
                        iface_constraints = new ArrayList ();
                        type_param_constraints = new ArrayList ();
 
@@ -195,20 +212,32 @@ namespace Mono.CSharp {
                                        if (sc == SpecialConstraint.ReferenceType)
                                                attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
                                        else
-                                               attrs |= GenericParameterAttributes.ValueTypeConstraint;
+                                               attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
                                        continue;
                                }
 
+                               int errors = Report.Errors;
+                               FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
+
+                               if (fn == null) {
+                                       if (errors != Report.Errors)
+                                               return false;
+
+                                       Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
+                                       return false;
+                               }
+
                                TypeExpr expr;
-                               if (obj is ConstructedType) {
-                                       ConstructedType cexpr = (ConstructedType) obj;
+                               ConstructedType cexpr = fn as ConstructedType;
+                               if (cexpr != null) {
                                        if (!cexpr.ResolveConstructedType (ec))
                                                return false;
+
                                        expr = cexpr;
                                } else
-                                       expr = ((Expression) obj).ResolveAsTypeTerminal (ec);
+                                       expr = fn.ResolveAsTypeTerminal (ec, false);
 
-                               if (expr == null)
+                               if ((expr == null) || (expr.Type == null))
                                        return false;
 
                                TypeParameterExpr texpr = expr as TypeParameterExpr;
@@ -233,6 +262,72 @@ 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) {
+                                       Report.Error (701, loc,
+                                                     "`{0}' is not a valid bound.  Bounds " +
+                                                     "must be interfaces or non sealed " +
+                                                     "classes", 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;
                }
 
@@ -270,11 +365,16 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               /// <summary>
+               ///   Resolve the constraints into actual types.
+               /// </summary>
                public bool ResolveTypes (EmitContext 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)
@@ -290,75 +390,28 @@ 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);
+                               if (iface_constraint.ResolveType (ec) == null)
                                        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.Type, 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) {
-                                       Report.Error (701, loc,
-                                                     "`{0}' is not a valid bound.  Bounds " +
-                                                     "must be interfaces or non sealed " +
-                                                     "classes", class_constraint_type);
+                               if (class_constraint.ResolveType (ec) == 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;
                }
 
+               /// <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 (EmitContext ec)
                {
                        foreach (TypeParameterExpr expr in type_param_constraints) {
@@ -378,7 +431,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;
                        }
@@ -394,7 +447,7 @@ namespace Mono.CSharp {
                                        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;
                                }
                        }
@@ -410,11 +463,6 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public void Define (GenericTypeParameterBuilder type)
-               {
-                       type.SetGenericParameterAttributes (attrs);
-               }
-
                public override GenericParameterAttributes Attributes {
                        get { return attrs; }
                }
@@ -435,7 +483,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))
@@ -452,6 +500,13 @@ namespace Mono.CSharp {
                        return false;
                }
 
+               /// <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 (EmitContext ec, GenericConstraints gc)
                {
                        if (gc.Attributes != attrs)
@@ -487,21 +542,23 @@ namespace Mono.CSharp {
                }
        }
 
-       //
-       // 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;
                }
@@ -527,24 +584,27 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Type Type {
+               public DeclSpace DeclSpace {
                        get {
-                               return type;
+                               return decl;
                        }
                }
 
-               public bool Resolve (DeclSpace ds)
-               {
-                       if (constraints != null) {
-                               if (!constraints.Resolve (ds.EmitContext)) {
-                                       constraints = null;
-                                       return false;
-                               }
+               public Type Type {
+                       get {
+                               return type;
                        }
-
-                       return true;
                }
 
+               /// <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)
@@ -554,12 +614,41 @@ namespace Mono.CSharp {
                        TypeManager.AddTypeParameter (type, this);
                }
 
-               public void DefineConstraints ()
+               /// <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)
-                               constraints.Define (type);
+                       if (constraints != null) {
+                               if (!constraints.Resolve (ds.EmitContext)) {
+                                       constraints = null;
+                                       return false;
+                               }
+                       }
+
+                       return true;
                }
 
+               /// <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 (EmitContext ec)
                {
                        if (constraints != null) {
@@ -572,11 +661,24 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               /// <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 (EmitContext ec)
                {
                        return DefineType (ec, null, null, false);
                }
 
+               /// <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 (EmitContext ec, MethodBuilder builder,
                                        MethodInfo implementing, bool is_override)
                {
@@ -593,14 +695,11 @@ namespace Mono.CSharp {
                                        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);
@@ -625,12 +724,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 Iterator) {
+                               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;
                        }
@@ -642,11 +749,21 @@ namespace Mono.CSharp {
                                type.SetBaseTypeConstraint (gc.ClassConstraint);
 
                        type.SetInterfaceConstraints (gc.InterfaceConstraints);
+                       type.SetGenericParameterAttributes (gc.Attributes);
                        TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
 
                        return true;
                }
 
+               /// <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 (EmitContext ec)
                {
                        if (constraints != null)
@@ -655,29 +772,24 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public bool UpdateConstraints (EmitContext ec, Constraints new_constraints, bool check)
+               /// <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 (EmitContext 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 (!check) {
-                               if (type != null)
-                                       throw new InvalidOperationException ();
-                               constraints = new_constraints;
-                               return true;
-                       }
-
                        if (type == null)
                                throw new InvalidOperationException ();
 
-                       if (constraints == null)
-                               return new_constraints == null;
-                       else if (new_constraints == null)
-                               return false;
+                       if (constraints == null) {
+                               new_constraints = constraints;
+                               return true;
+                       } else if (new_constraints == null)
+                               return true;
 
                        if (!new_constraints.Resolve (ec))
                                return false;
@@ -687,6 +799,12 @@ namespace Mono.CSharp {
                        return constraints.CheckInterfaceMethod (ec, new_constraints);
                }
 
+               public void EmitAttributes (EmitContext ec)
+               {
+                       if (OptAttributes != null)
+                               OptAttributes.Emit (ec, this);
+               }
+
                public override string DocCommentHeader {
                        get {
                                throw new InvalidOperationException (
@@ -703,22 +821,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" };
                        }
                }
 
@@ -755,8 +872,6 @@ namespace Mono.CSharp {
 
                        ArrayList members = new ArrayList ();
 
-                       GenericConstraints gc = (GenericConstraints) constraints;
-
                        if (gc.HasClassConstraint) {
                                MemberList list = TypeManager.FindMembers (
                                        gc.ClassConstraint, mt, bf, filter, criteria);
@@ -764,7 +879,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);
 
@@ -790,6 +906,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;
@@ -797,14 +934,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)
@@ -841,14 +979,18 @@ namespace Mono.CSharp {
                                        return null;
                                if (t.IsGenericParameter)
                                        return dargs [t.GenericParameterPosition];
-                               if (t.IsGenericInstance) {
+                               if (t.IsGenericType) {
                                        t = t.GetGenericTypeDefinition ();
-                                       t = t.BindGenericParameters (dargs);
+                                       t = t.MakeGenericType (dargs);
                                }
 
                                return t;
                        }
 
+                       public override string TypeParameter {
+                               get { return gc.TypeParameter; }
+                       }
+
                        public override GenericParameterAttributes Attributes {
                                get { return gc.Attributes; }
                        }
@@ -867,11 +1009,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;
 
@@ -921,6 +1061,10 @@ namespace Mono.CSharp {
                }
        }
 
+       /// <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;
@@ -957,13 +1101,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;
                                }
 
@@ -974,6 +1129,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;
@@ -1018,6 +1177,9 @@ namespace Mono.CSharp {
                        return s.ToString ();
                }
 
+               /// <summary>
+               ///   Resolve the type arguments.
+               /// </summary>
                public bool Resolve (EmitContext ec)
                {
                        int count = args.Count;
@@ -1026,7 +1188,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;
@@ -1038,6 +1200,10 @@ namespace Mono.CSharp {
                                        Report.Error (306, Location, "The type `{0}' may not be used " +
                                                      "as a type argument.", TypeManager.CSharpName (te.Type));
                                        return false;
+                               } else if (te.Type == TypeManager.void_type) {
+                                       Report.Error (1547, Location,
+                                                     "Keyword `void' cannot be used in this context");
+                                       return false;
                                }
 
                                atypes [i] = te.Type;
@@ -1045,36 +1211,41 @@ namespace Mono.CSharp {
                        return ok;
                }
        }
-       
-       public class ConstructedType : TypeExpr {
-               string name, full_name;
-               TypeArguments args;
-               Type[] gen_params, atypes;
-               Type gt;
-               
-               public ConstructedType (string name, TypeArguments args, Location l)
-               {
-                       loc = l;
-                       this.name = MemberName.MakeName (name, args.Count);
-                       this.args = args;
 
-                       eclass = ExprClass.Type;
-                       full_name = name + "<" + args.ToString () + ">";
-               }
+       public class TypeParameterName : SimpleName
+       {
+               Attributes attributes;
 
-               public ConstructedType (string name, TypeParameter[] type_params, Location l)
-                       : this (type_params, l)
+               public TypeParameterName (string name, Attributes attrs, Location loc)
+                       : base (name, loc)
                {
-                       loc = l;
+                       attributes = attrs;
+               }
 
-                       this.name = name;
-                       full_name = name + "<" + args.ToString () + ">";
+               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;
-                       this.name = fname.FullName;
+                       this.name = fname;
                        this.args = args;
 
                        eclass = ExprClass.Type;
@@ -1100,21 +1271,29 @@ 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)
                {
                        gt = t.GetGenericTypeDefinition ();
 
-                       this.name = gt.FullName;
+                       this.name = new TypeExpression (gt, l);
                        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)
                {
                        gt = t.GetGenericTypeDefinition ();
 
-                       this.name = gt.FullName;
+                       this.name = new TypeExpression (gt, l);
                        full_name = gt.FullName + "<" + args.ToString () + ">";
                }
 
@@ -1122,46 +1301,174 @@ 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.CSharpName (gt);
+               }
+
+               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               {
+                       if (!ResolveConstructedType (ec))
+                               return null;
+
+                       return this;
+               }
+
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public bool CheckConstraints (EmitContext ec)
+               {
+                       return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
+               }
+
+               /// <summary>
+               ///   Resolve the constructed type, but don't check the constraints.
+               /// </summary>
+               public bool ResolveConstructedType (EmitContext ec)
+               {
+                       if (type != null)
+                               return true;
+                       // If we already know the fully resolved generic type.
+                       if (gt != null)
+                               return DoResolveType (ec);
+
+                       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);
                }
 
-               protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
-                                               Type ctype)
+               bool DoResolveType (EmitContext ec)
                {
-                       if (TypeManager.HasGenericArguments (ctype)) {
-                               Type[] types = TypeManager.GetTypeArguments (ctype);
+                       //
+                       // Resolve the arguments.
+                       //
+                       if (args.Resolve (ec) == false)
+                               return false;
 
-                               TypeArguments new_args = new TypeArguments (loc);
+                       gen_params = gt.GetGenericArguments ();
+                       atypes = args.Arguments;
 
-                               for (int i = 0; i < types.Length; i++) {
-                                       Type t = types [i];
+                       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;
+                       }
 
-                                       if (t.IsGenericParameter) {
-                                               int pos = t.GenericParameterPosition;
-                                               t = args.Arguments [pos];
-                                       }
-                                       new_args.Add (new TypeExpression (t, loc));
-                               }
+                       //
+                       // Now bind the parameters.
+                       //
+                       type = gt.MakeGenericType (atypes);
+                       return true;
+               }
 
-                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
-                               if (ct.ResolveAsTypeTerminal (ec) == null)
+               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)
+               {
+                       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;
+                       }
+               }
+       }
+
+       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 (EmitContext ec)
+               {
+                       for (int i = 0; i < gen_params.Length; i++) {
+                               if (!CheckConstraints (ec, i))
                                        return false;
-                               ctype = ct.Type;
                        }
 
-                       return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
+                       return true;
                }
 
                protected bool CheckConstraints (EmitContext ec, int index)
@@ -1188,8 +1495,8 @@ namespace Mono.CSharp {
                                        is_class = is_struct = false;
                                }
                        } else {
-                               is_class = atype.IsClass;
-                               is_struct = atype.IsValueType;
+                               is_class = atype.IsClass || atype.IsInterface;
+                               is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
                        }
 
                        //
@@ -1200,14 +1507,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;
                        }
 
@@ -1215,34 +1526,16 @@ 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);
+                               if (!CheckConstraint (ec, ptype, aexpr, it))
                                        return false;
-                               }
                        }
 
                        //
@@ -1255,215 +1548,187 @@ 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;
-                       }
-
-                       return true;
-               }
-
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
-               {
-                       if (!ResolveConstructedType (ec))
-                               return null;
-
-                       return this;
-               }
-
-               public bool CheckConstraints (EmitContext ec)
-               {
-                       for (int i = 0; i < gen_params.Length; i++) {
-                               if (!CheckConstraints (ec, i))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               public override TypeExpr ResolveAsTypeTerminal (EmitContext ec)
-               {
-                       if (base.ResolveAsTypeTerminal (ec) == null)
-                               return null;
-
-                       if (!CheckConstraints (ec))
-                               return null;
+                       if (HasDefaultConstructor (ec, atype))
+                               return true;
 
-                       return this;
+                       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;
                }
 
-               public bool ResolveConstructedType (EmitContext ec)
+               protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
+                                               Type ctype)
                {
-                       if (type != null)
-                               return true;
-                       if (gt != null)
-                               return DoResolveType (ec);
-
-                       //
-                       // First, resolve the generic type.
-                       //
-                       DeclSpace ds;
-                       Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
-                       if (nested != null) {
-                               gt = nested.GetGenericTypeDefinition ();
+                       if (TypeManager.HasGenericArguments (ctype)) {
+                               Type[] types = TypeManager.GetTypeArguments (ctype);
 
                                TypeArguments new_args = new TypeArguments (loc);
-                               if (ds.IsGeneric) {
-                                       foreach (TypeParameter param in ds.TypeParameters)
-                                               new_args.Add (new TypeParameterExpr (param, loc));
-                               }
-                               new_args.Add (args);
-
-                               args = new_args;
-                               return DoResolveType (ec);
-                       }
-
-                       Type t;
-                       int num_args;
-
-                       SimpleName sn = new SimpleName (name, loc);
-                       TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
-                       if (resolved == null)
-                               return false;
 
-                       t = resolved.Type;
-                       if (t == null) {
-                               Report.Error (246, loc, "Cannot find type `{0}'<...>",
-                                             Basename);
-                               return false;
-                       }
+                               for (int i = 0; i < types.Length; i++) {
+                                       Type t = types [i];
 
-                       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;
+                                       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];
                        }
 
-                       gt = t.GetGenericTypeDefinition ();
-                       return DoResolveType (ec);
+                       if (Convert.ImplicitStandardConversionExists (ec, expr, ctype))
+                               return true;
+
+                       Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
+                       return false;
                }
 
-               bool DoResolveType (EmitContext ec)
+               bool HasDefaultConstructor (EmitContext ec, Type atype)
                {
-                       //
-                       // Resolve the arguments.
-                       //
-                       if (args.Resolve (ec) == false)
-                               return false;
+                       atype = TypeManager.DropGenericTypeArguments (atype);
 
-                       gen_params = gt.GetGenericArguments ();
-                       atypes = args.Arguments;
+                       if (atype is TypeBuilder) {
+                               if (atype.IsAbstract)
+                                       return false;
 
-                       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);
-                               return false;
+                               TypeContainer tc = TypeManager.LookupTypeContainer (atype);
+                               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;
+
+                                       return true;
+                               }
                        }
 
-                       //
-                       // Now bind the parameters.
-                       //
-                       type = gt.BindGenericParameters (atypes);
-                       return true;
-               }
+                       MethodGroupExpr mg = Expression.MemberLookup (
+                               ec.ContainerType, atype, ".ctor", MemberTypes.Constructor,
+                               BindingFlags.Public | BindingFlags.Instance |
+                               BindingFlags.DeclaredOnly, loc)
+                               as MethodGroupExpr;
 
-               public Expression GetSimpleName (EmitContext ec)
-               {
-                       return new SimpleName (Basename, args, loc);
-               }
+                       if (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
+                               foreach (MethodBase mb in mg.Methods) {
+                                       ParameterData pd = TypeManager.GetParameterData (mb);
+                                       if (pd.Count == 0)
+                                               return true;
+                               }
+                       }
 
-               public override bool CheckAccessLevel (DeclSpace ds)
-               {
-                       return ds.CheckAccessLevel (gt);
+                       return false;
                }
 
-               public override bool AsAccessible (DeclSpace ds, int flags)
-               {
-                       return ds.AsAccessible (gt, flags);
-               }
+               protected abstract string GetSignatureForError ();
+               protected abstract void Report_SymbolRelatedToPreviousError ();
 
-               public override bool IsClass {
-                       get { return gt.IsClass; }
+               void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
+               {
+                       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 IsValueType {
-                       get { return gt.IsValueType; }
-               }
+               public static bool CheckConstraints (EmitContext ec, MethodBase definition,
+                                                    MethodBase instantiated, Location loc)
+               {
+                       MethodConstraintChecker checker = new MethodConstraintChecker (
+                               definition, definition.GetGenericArguments (),
+                               instantiated.GetGenericArguments (), loc);
 
-               public override bool IsInterface {
-                       get { return gt.IsInterface; }
+                       return checker.CheckConstraints (ec);
                }
 
-               public override bool IsSealed {
-                       get { return gt.IsSealed; }
-               }
+               public static bool CheckConstraints (EmitContext ec, Type gt, Type[] gen_params,
+                                                    Type[] atypes, Location loc)
+               {
+                       TypeConstraintChecker checker = new TypeConstraintChecker (
+                               gt, gen_params, atypes, loc);
 
-               public override bool IsAttribute {
-                       get { return false; }
+                       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 string Basename {
-                       get {
-                               int pos = name.LastIndexOf ('`');
-                               if (pos >= 0)
-                                       return name.Substring (0, pos);
-                               else
-                                       return name;
+                       public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
+                                                     Location loc)
+                               : base (gen_params, atypes, loc)
+                       {
+                               this.gt = gt;
                        }
-               }
 
-               public override string Name {
-                       get {
-                               return full_name;
+                       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, TypeContainer 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 ()
                {
@@ -1472,26 +1737,32 @@ 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 (Parent))
+                               if (!TypeParameters [i].Resolve (this))
                                        return false;
 
                        return true;
                }
 
-               public bool Define (MethodBuilder mb, Type return_type)
+               /// <summary>
+               ///   Define and resolve the type parameters.
+               ///   We're called from Method.Define().
+               /// </summary>
+               public bool Define (MethodBuilder mb)
                {
-                       if (!Define ())
-                               return false;
-
                        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++)
+                               snames [i] = names [i].Name;
+                       gen_params = mb.DefineGenericParameters (snames);
                        for (int i = 0; i < TypeParameters.Length; i++)
                                TypeParameters [i].Define (gen_params [i]);
 
-                       ec = new EmitContext (
-                               this, this, Location, null, return_type, ModFlags, false);
+                       if (!Define ())
+                               return false;
 
                        for (int i = 0; i < TypeParameters.Length; i++) {
                                if (!TypeParameters [i].ResolveType (ec))
@@ -1501,6 +1772,9 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               /// <summary>
+               ///   We're called from MethodData.Define() after creating the MethodBuilder.
+               /// </summary>
                public bool DefineType (EmitContext ec, MethodBuilder mb,
                                        MethodInfo implementing, bool is_override)
                {
@@ -1509,10 +1783,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 (EmitContext ec)
+               {
+                       for (int i = 0; i < TypeParameters.Length; i++)
+                               TypeParameters [i].EmitAttributes (ec);
+
+                       if (OptAttributes != null)
+                               OptAttributes.Emit (ec, this);
                }
 
-               public override bool DefineMembers (TypeContainer parent)
+               public override bool DefineMembers ()
                {
                        return true;
                }
@@ -1531,12 +1822,7 @@ namespace Mono.CSharp {
 
                public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
                {
-                       // FIXME
-               }
-
-               protected override void VerifyObsoleteAttribute()
-               {
-                       // FIXME
+                       base.ApplyAttributeBuilder (a, cb);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -1553,7 +1839,6 @@ namespace Mono.CSharp {
        public class DefaultValueExpression : Expression
        {
                Expression expr;
-               LocalTemporary temp_storage;
 
                public DefaultValueExpression (Expression expr, Location loc)
                {
@@ -1563,13 +1848,11 @@ 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);
 
                        eclass = ExprClass.Variable;
                        return this;
@@ -1577,7 +1860,9 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       if (temp_storage != null) {
+                       if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
+                               LocalTemporary temp_storage = new LocalTemporary (ec, type);
+
                                temp_storage.AddressOf (ec, AddressOp.LoadStore);
                                ec.ig.Emit (OpCodes.Initobj, type);
                                temp_storage.Emit (ec);
@@ -1616,7 +1901,7 @@ namespace Mono.CSharp {
                        args.Add (underlying);
 
                        ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
-                       return ctype.ResolveAsTypeTerminal (ec);
+                       return ctype.ResolveAsTypeTerminal (ec, false);
                }
        }
 
@@ -1625,7 +1910,6 @@ 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_ienumerator_type;
                static public Type generic_ienumerable_type;
@@ -1653,13 +1937,14 @@ namespace Mono.CSharp {
 
                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_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 ()
@@ -1670,9 +1955,9 @@ namespace Mono.CSharp {
                                activator_type, "CreateInstance", type_arg);
                }
 
-               static Type CoreLookupType (string name, int arity)
+               static Type CoreLookupType (string ns, string name, int arity)
                {
-                       return CoreLookupType (MemberName.MakeName (name, arity));
+                       return CoreLookupType (ns, MemberName.MakeName (name, arity));
                }
 
                public static void AddTypeParameter (Type t, TypeParameter tparam)
@@ -1683,9 +1968,7 @@ namespace Mono.CSharp {
 
                public static TypeContainer LookupGenericTypeContainer (Type t)
                {
-                       while (t.IsGenericInstance)
-                               t = t.GetGenericTypeDefinition ();
-
+                       t = DropGenericTypeArguments (t);
                        return LookupTypeContainer (t);
                }
 
@@ -1694,15 +1977,6 @@ namespace Mono.CSharp {
                        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)
@@ -1712,14 +1986,7 @@ 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;
+                       return ReflectionConstraints.GetConstraints (t);
                }
 
                public static bool HasGenericArguments (Type t)
@@ -1729,11 +1996,13 @@ namespace Mono.CSharp {
 
                public static int GetNumberOfTypeArguments (Type t)
                {
+                       if (t.IsGenericParameter)
+                               return 0;
                        DeclSpace tc = LookupDeclSpace (t);
                        if (tc != null)
                                return tc.IsGeneric ? tc.CountTypeParameters : 0;
                        else
-                               return t.HasGenericArguments ? t.GetGenericArguments ().Length : 0;
+                               return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
                }
 
                public static Type[] GetTypeArguments (Type t)
@@ -1756,13 +2025,66 @@ namespace Mono.CSharp {
                                return t.GetGenericArguments ();
                }
 
+               public static Type DropGenericTypeArguments (Type t)
+               {
+                       if (!t.IsGenericType)
+                               return t;
+                       // Micro-optimization: a generic typebuilder is always a generic type definition
+                       if (t is TypeBuilder)
+                               return t;
+                       return t.GetGenericTypeDefinition ();
+               }
+
+               public static MethodBase DropGenericMethodArguments (MethodBase m)
+               {
+                       if (m.IsGenericMethodDefinition)
+                               return m;
+                       if (m.IsGenericMethod)
+                               return ((MethodInfo) m).GetGenericMethodDefinition ();
+                       if (!m.DeclaringType.IsGenericType)
+                               return m;
+
+                       Type t = m.DeclaringType.GetGenericTypeDefinition ();
+                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
+                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
+
+                       if (m is ConstructorInfo) {
+                               foreach (ConstructorInfo c in t.GetConstructors (bf))
+                                       if (c.MetadataToken == m.MetadataToken)
+                                               return c;
+                       } else {
+                               foreach (MethodBase mb in t.GetMethods (bf))
+                                       if (mb.MetadataToken == m.MetadataToken)
+                                               return mb;
+                       }
+
+                       return m;
+               }
+
+               public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
+               {
+                       if (fi.DeclaringType.IsGenericTypeDefinition ||
+                           !fi.DeclaringType.IsGenericType)
+                               return fi;
+
+                       Type t = fi.DeclaringType.GetGenericTypeDefinition ();
+                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
+                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
+
+                       foreach (FieldInfo f in t.GetFields (bf))
+                               if (f.MetadataToken == fi.MetadataToken)
+                                       return f;
+
+                       return fi;
+               }
+
                //
                // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
                // For instance "string[]" -> "IEnumerable<string>".
                //
                public static bool IsIEnumerable (Type array, Type enumerator)
                {
-                       if (!array.IsArray || !enumerator.IsGenericInstance)
+                       if (!array.IsArray || !enumerator.IsGenericType)
                                return false;
 
                        if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
@@ -1777,45 +2099,9 @@ namespace Mono.CSharp {
                        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))
+                               if (a.DeclaringMethod != b.DeclaringMethod &&
+                                   (a.DeclaringMethod == null || b.DeclaringMethod == null))
                                        return false;
                                return a.GenericParameterPosition == b.GenericParameterPosition;
                        }
@@ -1826,7 +2112,10 @@ namespace Mono.CSharp {
                                return IsEqual (a.GetElementType (), b.GetElementType ());
                        }
 
-                       if (a.IsGenericInstance && b.IsGenericInstance) {
+                       if (a.IsByRef && b.IsByRef)
+                               return IsEqual (a.GetElementType (), b.GetElementType ());
+
+                       if (a.IsGenericType && b.IsGenericType) {
                                if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
                                        return false;
 
@@ -1844,10 +2133,33 @@ namespace Mono.CSharp {
                                return true;
                        }
 
+                       //
+                       // This is to build with the broken circular dependencies between
+                       // System and System.Configuration in the 2.x profile where we
+                       // end up with a situation where:
+                       //
+                       // System on the second build is referencing the System.Configuration
+                       // that has references to the first System build.
+                       //
+                       // Point in case: NameValueCollection built on the first pass, vs
+                       // NameValueCollection build on the second one.  The problem is that
+                       // we need to override some methods sometimes, or we need to 
+                       //
+                       if (RootContext.BrokenCircularDeps){
+                               if (a.Name == b.Name && a.Namespace == b.Namespace){
+                                       Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
+                                       return true;
+                               }
+                       }
                        return false;
                }
 
-               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_infered,
+                                                              Type[] method_infered)
                {
                        if (a.IsGenericParameter) {
                                //
@@ -1867,7 +2179,7 @@ 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;
                                        if (args [pos] == null) {
@@ -1912,7 +2224,7 @@ namespace Mono.CSharp {
                        // become equal).
                        //
 
-                       if (a.IsGenericInstance || b.IsGenericInstance)
+                       if (a.IsGenericType || b.IsGenericType)
                                return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
 
                        //
@@ -1941,9 +2253,10 @@ namespace Mono.CSharp {
                // particular instantiation (26.3.1).
                //
                public static bool MayBecomeEqualGenericInstances (Type a, Type b,
-                                                                  Type[] class_infered, Type[] method_infered)
+                                                                  Type[] class_infered,
+                                                                  Type[] method_infered)
                {
-                       if (!a.IsGenericInstance || !b.IsGenericInstance)
+                       if (!a.IsGenericType || !b.IsGenericType)
                                return false;
                        if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
                                return false;
@@ -1953,7 +2266,8 @@ namespace Mono.CSharp {
                }
 
                public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
-                                                                  Type[] class_infered, Type[] method_infered)
+                                                                  Type[] class_infered,
+                                                                  Type[] method_infered)
                {
                        if (aargs.Length != bargs.Length)
                                return false;
@@ -1966,23 +2280,28 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public static bool IsEqualGenericInstance (Type type, Type parent)
+               /// <summary>
+               ///   Check whether `type' and `parent' are both instantiations of the same
+               ///   generic type.  Note that we do not check the type parameters here.
+               /// </summary>
+               public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
                {
                        int tcount = GetNumberOfTypeArguments (type);
                        int pcount = GetNumberOfTypeArguments (parent);
 
-                       if (type.IsGenericInstance)
-                               type = type.GetGenericTypeDefinition ();
-                       if (parent.IsGenericInstance)
-                               parent = parent.GetGenericTypeDefinition ();
-
                        if (tcount != pcount)
                                return false;
 
+                       type = DropGenericTypeArguments (type);
+                       parent = DropGenericTypeArguments (parent);
+
                        return type.Equals (parent);
                }
 
-               static public bool IsGenericMethod (MethodBase mb)
+               /// <summary>
+               ///   Whether `mb' is a generic method definition.
+               /// </summary>
+               public static bool IsGenericMethodDefinition (MethodBase mb)
                {
                        if (mb.DeclaringType is TypeBuilder) {
                                IMethodData method = (IMethodData) builder_to_method [mb];
@@ -1995,13 +2314,35 @@ namespace Mono.CSharp {
                        return mb.IsGenericMethodDefinition;
                }
 
+               /// <summary>
+               ///   Whether `mb' is a generic method definition.
+               /// </summary>
+               public static bool IsGenericMethod (MethodBase mb)
+               {
+                       if (mb.DeclaringType is TypeBuilder) {
+                               IMethodData method = (IMethodData) builder_to_method [mb];
+                               if (method == null)
+                                       return false;
+
+                               return method.GenericMethod != null;
+                       }
+
+                       return mb.IsGenericMethod;
+               }
+
                //
                // Type inference.
                //
 
                static bool InferType (Type pt, Type at, Type[] infered)
                {
-                       if (pt.IsGenericParameter && (pt.DeclaringMethod != null)) {
+                       if (pt == at)
+                               return true;
+
+                       if (pt.IsGenericParameter) {
+                               if (pt.DeclaringMethod == null)
+                                       return false;
+
                                int pos = pt.GenericParameterPosition;
 
                                if (infered [pos] == null) {
@@ -2030,11 +2371,19 @@ namespace Mono.CSharp {
                        }
 
                        if (at.IsArray) {
-                               if (!pt.IsArray ||
-                                   (at.GetArrayRank () != pt.GetArrayRank ()))
-                                       return false;
+                               if (pt.IsArray) {
+                                       if (at.GetArrayRank () != pt.GetArrayRank ())
+                                               return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                                       return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               }
+
+                               if (!pt.IsGenericType ||
+                                   (pt.GetGenericTypeDefinition () != generic_ienumerable_type))
+                                   return false;
+
+                               Type[] args = GetTypeArguments (pt);
+                               return InferType (args [0], at.GetElementType (), infered);
                        }
 
                        if (pt.IsArray) {
@@ -2048,19 +2397,17 @@ namespace Mono.CSharp {
                        if (pt.IsByRef && at.IsByRef)
                                return InferType (pt.GetElementType (), at.GetElementType (), infered);
                        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);
+                       for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
+                               list.Add (bt);
 
-                               list.AddRange (TypeManager.GetInterfaces (at));
-                       }
+                       list.AddRange (TypeManager.GetInterfaces (at));
 
                        bool found_one = false;
 
                        foreach (Type type in list) {
-                               if (!type.IsGenericInstance)
+                               if (!type.IsGenericType)
                                        continue;
 
                                Type[] infered_types = new Type [infered.Length];
@@ -2105,6 +2452,12 @@ namespace Mono.CSharp {
                        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)
                {
@@ -2171,11 +2524,12 @@ namespace Mono.CSharp {
                                if (infered_types [i] == null)
                                        return false;
 
-                       method = method.BindGenericParameters (infered_types);
+                       method = ((MethodInfo)method).MakeGenericMethod (infered_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[] infered_types)
                {
                        if (infered_types == null)
                                return false;
@@ -2195,6 +2549,12 @@ namespace Mono.CSharp {
                        return true;
                }
 
+               /// <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 (EmitContext ec, ArrayList arguments,
                                                       ref MethodBase method)
                {
@@ -2232,7 +2592,8 @@ 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 AnonymousMethod))
                                        continue;
 
                                arg_types [i] = a.Type;
@@ -2241,10 +2602,13 @@ namespace Mono.CSharp {
                        if (!InferTypeArguments (param_types, arg_types, infered_types))
                                return false;
 
-                       method = method.BindGenericParameters (infered_types);
+                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
                        return true;
                }
 
+               /// <summary>
+               ///   Type inference.
+               /// </summary>
                public static bool InferTypeArguments (EmitContext ec, ParameterData apd,
                                                       ref MethodBase method)
                {
@@ -2269,17 +2633,13 @@ namespace Mono.CSharp {
                        if (!InferTypeArguments (param_types, arg_types, infered_types))
                                return false;
 
-                       method = method.BindGenericParameters (infered_types);
+                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
                        return true;
                }
 
                public static bool IsNullableType (Type t)
                {
-                       if (!t.IsGenericInstance)
-                               return false;
-
-                       Type gt = t.GetGenericTypeDefinition ();
-                       return gt == generic_nullable_type;
+                       return generic_nullable_type == DropGenericTypeArguments (t);
                }
        }
 
@@ -2298,8 +2658,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);
@@ -2327,8 +2687,7 @@ namespace Mono.CSharp {
                                if (expr == null)
                                        return null;
 
-                               if (!(expr is IMemoryLocation))
-                                       temp = new LocalTemporary (ec, expr.Type);
+                               temp = new LocalTemporary (ec, expr.Type);
 
                                info = new NullableInfo (expr.Type);
                                type = info.UnderlyingType;
@@ -2348,6 +2707,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) {
@@ -2382,14 +2746,35 @@ 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;
+
+                                       type = info.Type;
+                                       eclass = ExprClass.Value;
+                               }
 
-                               if (leave_copy)
-                                       ec.ig.Emit (OpCodes.Dup);
+                               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);
+                               }
                        }
                }
 
@@ -2411,7 +2796,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;
 
@@ -2573,8 +2958,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)
@@ -2586,7 +2970,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);
                        }
                }
 
@@ -2594,7 +2978,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;
 
@@ -2602,8 +2987,8 @@ 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;
                        }
 
@@ -2623,8 +3008,16 @@ namespace Mono.CSharp {
                                                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);
@@ -2634,7 +3027,7 @@ namespace Mono.CSharp {
                                        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;
                                        }
@@ -2645,14 +3038,14 @@ 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;
 
@@ -2741,13 +3134,19 @@ namespace Mono.CSharp {
                                Label true_label = ig.DefineLabel ();
                                Label end_label = ig.DefineLabel ();
 
+                               bool false_label_used = false;
+                               bool true_label_used = false;
+
                                if (left_unwrap != null) {
                                        left_unwrap.EmitCheck (ec);
                                        if (right is NullLiteral) {
-                                               if (Oper == Binary.Operator.Equality)
+                                               if (Oper == Binary.Operator.Equality) {
+                                                       true_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, true_label);
-                                               else
+                                               } else {
+                                                       false_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, false_label);
+                                               }
                                        } else if (right_unwrap != null) {
                                                ig.Emit (OpCodes.Dup);
                                                ig.Emit (OpCodes.Brtrue, left_not_null_label);
@@ -2762,25 +3161,34 @@ namespace Mono.CSharp {
                                                ig.MarkLabel (left_not_null_label);
                                                ig.Emit (OpCodes.Pop);
                                        } else {
-                                               if (Oper == Binary.Operator.Equality)
+                                               if (Oper == Binary.Operator.Equality) {
+                                                       false_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, false_label);
-                                               else
+                                               } else {
+                                                       true_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, true_label);
+                                               }
                                        }
                                }
 
                                if (right_unwrap != null) {
                                        right_unwrap.EmitCheck (ec);
                                        if (left is NullLiteral) {
-                                               if (Oper == Binary.Operator.Equality)
+                                               if (Oper == Binary.Operator.Equality) {
+                                                       true_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, true_label);
-                                               else
+                                               } else {
+                                                       false_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, false_label);
+                                               }
                                        } else {
-                                               if (Oper == Binary.Operator.Equality)
+                                               if (Oper == Binary.Operator.Equality) {
+                                                       false_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, false_label);
-                                               else
+                                               } else {
+                                                       true_label_used = true;
                                                        ig.Emit (OpCodes.Brfalse, true_label);
+                                               }
                                        }
                                }
 
@@ -2788,21 +3196,28 @@ namespace Mono.CSharp {
                                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)))
+                                           ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
+                                               true_label_used = true;
                                                ig.Emit (OpCodes.Br, true_label);
-                                       else
+                                       } else {
+                                               false_label_used = true;
                                                ig.Emit (OpCodes.Br, false_label);
+                                       }
                                } else {
                                        underlying.Emit (ec);
                                        ig.Emit (OpCodes.Br, end_label);
                                }
 
                                ig.MarkLabel (false_label);
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                               ig.Emit (OpCodes.Br, end_label);
+                               if (false_label_used) {
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                       if (true_label_used)
+                                               ig.Emit (OpCodes.Br, end_label);
+                               }
 
                                ig.MarkLabel (true_label);
-                               ig.Emit (OpCodes.Ldc_I4_1);
+                               if (true_label_used)
+                                       ig.Emit (OpCodes.Ldc_I4_1);
 
                                ig.MarkLabel (end_label);
                        }
@@ -2835,6 +3250,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;
@@ -3004,15 +3424,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);
+                               }
                        }
                }