* generic.cs (DropGenericTypeArguments): New. Captures the common
[mono.git] / mcs / gmcs / generic.cs
index 03ec6b4be852bf108f2bf04075a87063b8621191..e938019b20b78863e1daec5f84f8718d9579ede7 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);
+
+                               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);
 
-                               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);
-                                       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);
+                               if (iface_constraint.ResolveType (ec) == null)
                                        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);
-                                       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);
+                               if (class_constraint.ResolveType (ec) == null)
                                        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 (TypeContainer 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)
                {
@@ -598,9 +700,8 @@ namespace Mono.CSharp {
                                        mb = mb.GetGenericMethodDefinition ();
 
                                int pos = type.GenericParameterPosition;
-                               ParameterData pd = Invocation.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 +726,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 +751,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 +774,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 +801,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 +823,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" };
                        }
                }
 
@@ -764,7 +883,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 +910,21 @@ 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 ();
+               }
+
                protected class InflatedConstraints : GenericConstraints
                {
                        GenericConstraints gc;
@@ -797,14 +932,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)
@@ -843,12 +979,16 @@ namespace Mono.CSharp {
                                        return dargs [t.GenericParameterPosition];
                                if (t.IsGenericInstance) {
                                        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 +1007,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 +1059,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 +1099,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 +1127,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 +1175,9 @@ namespace Mono.CSharp {
                        return s.ToString ();
                }
 
+               /// <summary>
+               ///   Resolve the type arguments.
+               /// </summary>
                public bool Resolve (EmitContext ec)
                {
                        int count = args.Count;
@@ -1038,6 +1198,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 +1209,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 +1269,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,54 +1299,182 @@ 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 bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
-                                               Type ctype)
+               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
                {
-                       if (TypeManager.HasGenericArguments (ctype)) {
-                               Type[] types = TypeManager.GetTypeArguments (ctype);
-
-                               TypeArguments new_args = new TypeArguments (loc);
-
-                               for (int i = 0; i < types.Length; i++) {
-                                       Type t = types [i];
-
-                                       if (t.IsGenericParameter) {
-                                               int pos = t.GenericParameterPosition;
-                                               t = args.Arguments [pos];
-                                       }
-                                       new_args.Add (new TypeExpression (t, loc));
-                               }
-
-                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
-                               if (ct.ResolveAsTypeTerminal (ec) == null)
-                                       return false;
-                               ctype = ct.Type;
-                       }
+                       if (!ResolveConstructedType (ec))
+                               return null;
 
-                       return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
+                       return this;
                }
 
-               protected bool CheckConstraints (EmitContext ec, int index)
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public bool CheckConstraints (EmitContext ec)
                {
-                       Type atype = atypes [index];
-                       Type ptype = gen_params [index];
+                       return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
+               }
 
-                       if (atype == ptype)
+               /// <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);
+               }
+
+               bool DoResolveType (EmitContext ec)
+               {
+                       //
+                       // Resolve the arguments.
+                       //
+                       if (args.Resolve (ec) == false)
+                               return false;
+
+                       gen_params = gt.GetGenericArguments ();
+                       atypes = args.Arguments;
+
+                       if (atypes.Length != gen_params.Length) {
+                               Report.Error (305, loc,
+                                             "Using the generic type `{0}' " +
+                                             "requires {1} type arguments",
+                                             TypeManager.CSharpName (gt),
+                                             gen_params.Length.ToString ());
+                               return false;
+                       }
+
+                       //
+                       // Now bind the parameters.
+                       //
+                       type = gt.MakeGenericType (atypes);
+                       return true;
+               }
+
+               public Expression GetSimpleName (EmitContext ec)
+               {
+                       return this;
+               }
+
+               public override bool CheckAccessLevel (DeclSpace ds)
+               {
+                       return ds.CheckAccessLevel (gt);
+               }
+
+               public override bool AsAccessible (DeclSpace ds, int flags)
+               {
+                       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;
+                       }
+
+                       return true;
+               }
+
+               protected bool CheckConstraints (EmitContext ec, int index)
+               {
+                       Type atype = atypes [index];
+                       Type ptype = gen_params [index];
+
+                       if (atype == ptype)
                                return true;
 
                        Expression aexpr = new EmptyExpression (atype);
@@ -1200,14 +1505,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 " +
                                              "as type parameter `{1}' in the " +
                                              "generic type or method `{2}'.",
-                                             atype, ptype, DeclarationName);
+                                             TypeManager.CSharpName (atype),
+                                             TypeManager.CSharpName (ptype),
+                                             GetSignatureForError ());
                                return false;
                        }
 
@@ -1216,11 +1525,7 @@ namespace Mono.CSharp {
                        //
                        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);
+                                       Error_TypeMustBeConvertible (atype, gc.ClassConstraint, ptype);
                                        return false;
                                }
                        }
@@ -1236,11 +1541,7 @@ namespace Mono.CSharp {
                                        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);
+                                       Error_TypeMustBeConvertible (atype, itype, ptype);
                                        return false;
                                }
                        }
@@ -1255,215 +1556,178 @@ namespace Mono.CSharp {
                        if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
                                return true;
 
-                       MethodGroupExpr mg = Expression.MemberLookup (
-                               ec, atype, ".ctor", MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance |
-                               BindingFlags.DeclaredOnly, loc)
-                               as MethodGroupExpr;
-
-                       if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
-                               Report.Error (310, loc, "The type `{0}' must have a public " +
-                                             "parameterless constructor in order to use it " +
-                                             "as parameter `{1}' in the generic type or " +
-                                             "method `{2}'", atype, ptype, DeclarationName);
-                               return false;
-                       }
+                       if (HasDefaultConstructor (ec, atype))
+                               return true;
 
-                       return true;
+                       Report_SymbolRelatedToPreviousError ();
+                       Report.SymbolRelatedToPreviousError (atype);
+                       Report.Error (310, loc, "The type `{0}' must have a public " +
+                                     "parameterless constructor in order to use it " +
+                                     "as parameter `{1}' in the generic type or " +
+                                     "method `{2}'",
+                                     TypeManager.CSharpName (atype),
+                                     TypeManager.CSharpName (ptype),
+                                     GetSignatureForError ());
+                       return false;
                }
 
-               protected override TypeExpr DoResolveAsTypeStep (EmitContext ec)
+               protected bool CheckConstraint (EmitContext ec, Type ptype, Expression expr,
+                                               Type ctype)
                {
-                       if (!ResolveConstructedType (ec))
-                               return null;
-
-                       return this;
-               }
+                       if (TypeManager.HasGenericArguments (ctype)) {
+                               Type[] types = TypeManager.GetTypeArguments (ctype);
 
-               public bool CheckConstraints (EmitContext ec)
-               {
-                       for (int i = 0; i < gen_params.Length; i++) {
-                               if (!CheckConstraints (ec, i))
-                                       return false;
-                       }
+                               TypeArguments new_args = new TypeArguments (loc);
 
-                       return true;
-               }
+                               for (int i = 0; i < types.Length; i++) {
+                                       Type t = types [i];
 
-               public override TypeExpr ResolveAsTypeTerminal (EmitContext ec)
-               {
-                       if (base.ResolveAsTypeTerminal (ec) == null)
-                               return null;
+                                       if (t.IsGenericParameter) {
+                                               int pos = t.GenericParameterPosition;
+                                               t = atypes [pos];
+                                       }
+                                       new_args.Add (new TypeExpression (t, loc));
+                               }
 
-                       if (!CheckConstraints (ec))
-                               return null;
+                               TypeExpr ct = new ConstructedType (ctype, new_args, loc);
+                               if (ct.ResolveAsTypeStep (ec) == null)
+                                       return false;
+                               ctype = ct.Type;
+                       }
 
-                       return this;
+                       return Convert.ImplicitStandardConversionExists (ec, expr, ctype);
                }
 
-               public bool ResolveConstructedType (EmitContext ec)
+               bool HasDefaultConstructor (EmitContext ec, Type atype)
                {
-                       if (type != null)
-                               return true;
-                       if (gt != null)
-                               return DoResolveType (ec);
+                       if (atype is TypeBuilder) {
+                               if (atype.IsAbstract)
+                                       return false;
 
-                       //
-                       // First, resolve the generic type.
-                       //
-                       DeclSpace ds;
-                       Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
-                       if (nested != null) {
-                               gt = nested.GetGenericTypeDefinition ();
+                               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;
 
-                               TypeArguments new_args = new TypeArguments (loc);
-                               if (ds.IsGeneric) {
-                                       foreach (TypeParameter param in ds.TypeParameters)
-                                               new_args.Add (new TypeParameterExpr (param, loc));
+                                       return true;
                                }
-                               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;
-                       }
+                       MethodGroupExpr mg = Expression.MemberLookup (
+                               ec, atype, ".ctor", MemberTypes.Constructor,
+                               BindingFlags.Public | BindingFlags.Instance |
+                               BindingFlags.DeclaredOnly, loc)
+                               as MethodGroupExpr;
 
-                       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 (!atype.IsAbstract && (mg != null) && mg.IsInstance) {
+                               foreach (MethodBase mb in mg.Methods) {
+                                       ParameterData pd = TypeManager.GetParameterData (mb);
+                                       if (pd.Count == 0)
+                                               return true;
+                               }
                        }
 
-                       gt = t.GetGenericTypeDefinition ();
-                       return DoResolveType (ec);
+                       return false;
                }
 
-               bool DoResolveType (EmitContext ec)
-               {
-                       //
-                       // Resolve the arguments.
-                       //
-                       if (args.Resolve (ec) == false)
-                               return false;
-
-                       gen_params = gt.GetGenericArguments ();
-                       atypes = args.Arguments;
-
-                       if (atypes.Length != gen_params.Length) {
-                               Report.Error (305, loc,
-                                             "Using the generic type `{0}' " +
-                                             "requires {1} type arguments",
-                                             TypeManager.GetFullName (gt),
-                                             gen_params.Length);
-                               return false;
-                       }
-
-                       //
-                       // Now bind the parameters.
-                       //
-                       type = gt.BindGenericParameters (atypes);
-                       return true;
-               }
+               protected abstract string GetSignatureForError ();
+               protected abstract void Report_SymbolRelatedToPreviousError ();
 
-               public Expression GetSimpleName (EmitContext ec)
+               void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
                {
-                       return new SimpleName (Basename, args, loc);
+                       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 CheckAccessLevel (DeclSpace ds)
-               {
-                       return ds.CheckAccessLevel (gt);
-               }
-
-               public override bool AsAccessible (DeclSpace ds, int flags)
+               public static bool CheckConstraints (EmitContext ec, MethodBase definition,
+                                                    MethodBase instantiated, Location loc)
                {
-                       return ds.AsAccessible (gt, flags);
-               }
-
-               public override bool IsClass {
-                       get { return gt.IsClass; }
-               }
+                       MethodConstraintChecker checker = new MethodConstraintChecker (
+                               definition, definition.GetGenericArguments (),
+                               instantiated.GetGenericArguments (), loc);
 
-               public override bool IsValueType {
-                       get { return gt.IsValueType; }
-               }
-
-               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 +1736,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 +1771,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,7 +1782,24 @@ 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) == 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)
@@ -1531,12 +1821,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 +1838,6 @@ namespace Mono.CSharp {
        public class DefaultValueExpression : Expression
        {
                Expression expr;
-               LocalTemporary temp_storage;
 
                public DefaultValueExpression (Expression expr, Location loc)
                {
@@ -1568,8 +1852,6 @@ namespace Mono.CSharp {
                                return null;
 
                        type = texpr.Type;
-                       if (type.IsGenericParameter || TypeManager.IsValueType (type))
-                               temp_storage = new LocalTemporary (ec, type);
 
                        eclass = ExprClass.Variable;
                        return this;
@@ -1577,7 +1859,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);
@@ -1625,7 +1909,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 +1936,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 +1954,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 +1967,7 @@ namespace Mono.CSharp {
 
                public static TypeContainer LookupGenericTypeContainer (Type t)
                {
-                       while (t.IsGenericInstance)
-                               t = t.GetGenericTypeDefinition ();
-
+                       t = DropGenericTypeArguments (t);
                        return LookupTypeContainer (t);
                }
 
@@ -1694,15 +1976,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,7 +1985,7 @@ namespace Mono.CSharp {
                        if (tparam != null)
                                return tparam.GenericConstraints;
 
-                       return new ReflectionConstraints (t);
+                       return ReflectionConstraints.GetConstraints (t);
                }
 
                public static bool IsGeneric (Type t)
@@ -1729,11 +2002,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,6 +2031,32 @@ 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 ();
+               }
+
+               //
+               // Whether `array' is an array of T and `enumerator' is `IEnumerable<T>'.
+               // For instance "string[]" -> "IEnumerable<string>".
+               //
+               public static bool IsIEnumerable (Type array, Type enumerator)
+               {
+                       if (!array.IsArray || !enumerator.IsGenericInstance)
+                               return false;
+
+                       if (enumerator.GetGenericTypeDefinition () != generic_ienumerable_type)
+                               return false;
+
+                       Type[] args = GetTypeArguments (enumerator);
+                       return args [0] == GetElementType (array);
+               }
+
                public static bool IsEqual (Type a, Type b)
                {
                        if (a.Equals (b))
@@ -1799,7 +2100,8 @@ namespace Mono.CSharp {
                                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;
                        }
@@ -1831,7 +2133,12 @@ namespace Mono.CSharp {
                        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) {
                                //
@@ -1925,7 +2232,8 @@ 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)
                                return false;
@@ -1937,7 +2245,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;
@@ -1950,23 +2259,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 IsGenericMethod (MethodBase mb)
                {
                        if (mb.DeclaringType is TypeBuilder) {
                                IMethodData method = (IMethodData) builder_to_method [mb];
@@ -2034,12 +2348,10 @@ namespace Mono.CSharp {
                        ArrayList list = new ArrayList ();
                        if (at.IsGenericInstance)
                                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;
 
@@ -2089,6 +2401,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)
                {
@@ -2102,7 +2420,7 @@ namespace Mono.CSharp {
                        else
                                arg_count = arguments.Count;
                        
-                       ParameterData pd = Invocation.GetParameterData (method);
+                       ParameterData pd = TypeManager.GetParameterData (method);
 
                        int pd_count = pd.Count;
 
@@ -2155,11 +2473,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;
@@ -2179,6 +2498,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)
                {
@@ -2191,7 +2516,7 @@ namespace Mono.CSharp {
                        else
                                arg_count = 0;
 
-                       ParameterData pd = Invocation.GetParameterData (method);
+                       ParameterData pd = TypeManager.GetParameterData (method);
                        if (arg_count != pd.Count)
                                return false;
 
@@ -2216,7 +2541,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;
@@ -2225,17 +2551,20 @@ 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)
                {
                        if (!TypeManager.IsGenericMethod (method))
                                return true;
 
-                       ParameterData pd = Invocation.GetParameterData (method);
+                       ParameterData pd = TypeManager.GetParameterData (method);
                        if (apd.Count != pd.Count)
                                return false;
 
@@ -2253,40 +2582,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;
-               }
-       }
-
-       public class NullCoalescingOperator : Expression
-       {
-               Expression left;
-               Expression right;
-
-               public NullCoalescingOperator (Expression left, Expression right, Location loc)
-               {
-                       this.left = left;
-                       this.right = right;
-                       this.loc = loc;
-               }
-
-               public override Expression DoResolve (EmitContext ec)
-               {
-                       Error (-1, "The ?? operator is not yet implemented.");
-                       return null;
-               }
-
-               public override void Emit (EmitContext ec)
-               {
+                       return generic_nullable_type == DropGenericTypeArguments (t);
                }
        }
 
@@ -2305,8 +2607,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);
@@ -2314,7 +2616,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected class Unwrap : Expression, IMemoryLocation
+               protected class Unwrap : Expression, IMemoryLocation, IAssignMethod
                {
                        Expression expr;
                        NullableInfo info;
@@ -2349,23 +2651,54 @@ namespace Mono.CSharp {
                                ec.ig.EmitCall (OpCodes.Call, info.Value, null);
                        }
 
-                       public void EmitCheck (EmitContext ec, Label label)
-                       {
-                               AddressOf (ec, AddressOp.LoadStore);
-                               ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
-                               ec.ig.Emit (OpCodes.Brfalse, label);
+                       public void EmitCheck (EmitContext ec)
+                       {
+                               AddressOf (ec, AddressOp.LoadStore);
+                               ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
+                       }
+
+                       void create_temp (EmitContext ec)
+                       {
+                               if ((temp != null) && !has_temp) {
+                                       expr.Emit (ec);
+                                       temp.Store (ec);
+                                       has_temp = true;
+                               }
+                       }
+
+                       public void AddressOf (EmitContext ec, AddressOp mode)
+                       {
+                               create_temp (ec);
+                               if (temp != null)
+                                       temp.AddressOf (ec, AddressOp.LoadStore);
+                               else
+                                       ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
+                       }
+
+                       public void Emit (EmitContext ec, bool leave_copy)
+                       {
+                               create_temp (ec);
+                               if (leave_copy) {
+                                       if (temp != null)
+                                               temp.Emit (ec);
+                                       else
+                                               expr.Emit (ec);
+                               }
+
+                               Emit (ec);
                        }
 
-                       public void AddressOf (EmitContext ec, AddressOp mode)
+                       public void EmitAssign (EmitContext ec, Expression source,
+                                               bool leave_copy, bool prepare_for_load)
                        {
-                               if (temp != null) {
-                                       if (!has_temp) {
-                                               temp.Store (ec);
-                                               has_temp = true;
-                                       }
-                                       temp.AddressOf (ec, AddressOp.LoadStore);
-                               } else
-                                       ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
+                               source.Emit (ec);
+                               ec.ig.Emit (OpCodes.Newobj, info.Constructor);
+
+                               if (leave_copy)
+                                       ec.ig.Emit (OpCodes.Dup);
+
+                               Expression empty = new EmptyExpression (expr.Type);
+                               ((IAssignMethod) expr).EmitAssign (ec, empty, false, prepare_for_load);
                        }
                }
 
@@ -2404,8 +2737,8 @@ namespace Mono.CSharp {
                        }
                }
 
-               public class NullLiteral : Expression, IMemoryLocation {
-                       public NullLiteral (Type target_type, Location loc)
+               public class NullableLiteral : Expression, IMemoryLocation {
+                       public NullableLiteral (Type target_type, Location loc)
                        {
                                this.type = target_type;
                                this.loc = loc;
@@ -2466,7 +2799,7 @@ namespace Mono.CSharp {
                                if (wrap == null)
                                        return null;
 
-                               null_value = new NullLiteral (wrap.Type, loc).Resolve (ec);
+                               null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
                                if (null_value == null)
                                        return null;
 
@@ -2483,7 +2816,8 @@ namespace Mono.CSharp {
                                Label is_null_label = ig.DefineLabel ();
                                Label end_label = ig.DefineLabel ();
 
-                               unwrap.EmitCheck (ec, is_null_label);
+                               unwrap.EmitCheck (ec);
+                               ig.Emit (OpCodes.Brfalse, is_null_label);
 
                                wrap.Emit (ec);
                                ig.Emit (OpCodes.Br, end_label);
@@ -2548,8 +2882,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)
@@ -2561,7 +2894,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);
                        }
                }
 
@@ -2569,8 +2902,9 @@ namespace Mono.CSharp {
                {
                        public readonly Binary.Operator Oper;
 
-                       Expression left, right, underlying, null_value;
+                       Expression left, right, underlying, null_value, bool_wrap;
                        Unwrap left_unwrap, right_unwrap;
+                       bool is_equality, is_comparision, is_boolean;
 
                        public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
                                                     Location loc)
@@ -2583,14 +2917,6 @@ namespace Mono.CSharp {
 
                        public override Expression DoResolve (EmitContext ec)
                        {
-                               left = left.Resolve (ec);
-                               if (left == null)
-                                       return null;
-
-                               right = right.Resolve (ec);
-                               if (right == null)
-                                       return null;
-
                                if (TypeManager.IsNullableType (left.Type)) {
                                        left_unwrap = new Unwrap (left, loc);
                                        left = left_unwrap.Resolve (ec);
@@ -2605,32 +2931,265 @@ namespace Mono.CSharp {
                                                return null;
                                }
 
-                               underlying = new Wrap (new Binary (Oper, left, right, loc), loc);
-                               underlying = underlying.Resolve (ec);
-                               if (underlying == null)
-                                       return null;
+                               if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr) ||
+                                    (Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr)) &&
+                                   ((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);
+                                       null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
+
+                                       type = bool_wrap.Type;
+                                       is_boolean = true;
+                               } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
+                                       if (!(left is NullLiteral) && !(right is NullLiteral)) {
+                                               underlying = new Binary (Oper, left, right).Resolve (ec);
+                                               if (underlying == null)
+                                                       return null;
+                                       }
 
-                               null_value = new NullLiteral (underlying.Type, loc).Resolve (ec);
-                               if (null_value == null)
-                                       return null;
+                                       type = TypeManager.bool_type;
+                                       is_equality = true;
+                               } else if ((Oper == Binary.Operator.LessThan) ||
+                                          (Oper == Binary.Operator.GreaterThan) ||
+                                          (Oper == Binary.Operator.LessThanOrEqual) ||
+                                          (Oper == Binary.Operator.GreaterThanOrEqual)) {
+                                       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).Resolve (ec);
+                                       if (underlying == null)
+                                               return null;
+
+                                       underlying = new Wrap (underlying, loc).Resolve (ec);
+                                       if (underlying == null)
+                                               return null;
+
+                                       type = underlying.Type;
+                                       null_value = new NullableLiteral (type, loc).Resolve (ec);
+                               }
 
-                               type = underlying.Type;
                                eclass = ExprClass.Value;
                                return this;
                        }
 
+                       void EmitBoolean (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               Label left_is_null_label = ig.DefineLabel ();
+                               Label right_is_null_label = ig.DefineLabel ();
+                               Label is_null_label = ig.DefineLabel ();
+                               Label wrap_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               if (left_unwrap != null) {
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, left_is_null_label);
+                               }
+
+                               left.Emit (ec);
+                               ig.Emit (OpCodes.Dup);
+                               if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
+                                       ig.Emit (OpCodes.Brtrue, wrap_label);
+                               else
+                                       ig.Emit (OpCodes.Brfalse, wrap_label);
+
+                               if (right_unwrap != null) {
+                                       right_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, right_is_null_label);
+                               }
+
+                               if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
+                                       ig.Emit (OpCodes.Pop);
+
+                               right.Emit (ec);
+                               if (Oper == Binary.Operator.BitwiseOr)
+                                       ig.Emit (OpCodes.Or);
+                               else if (Oper == Binary.Operator.BitwiseAnd)
+                                       ig.Emit (OpCodes.And);
+                               ig.Emit (OpCodes.Br, wrap_label);
+
+                               ig.MarkLabel (left_is_null_label);
+                               if (right_unwrap != null) {
+                                       right_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                               }
+
+                               right.Emit (ec);
+                               ig.Emit (OpCodes.Dup);
+                               if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
+                                       ig.Emit (OpCodes.Brtrue, wrap_label);
+                               else
+                                       ig.Emit (OpCodes.Brfalse, wrap_label);
+
+                               ig.MarkLabel (right_is_null_label);
+                               ig.Emit (OpCodes.Pop);
+                               ig.MarkLabel (is_null_label);
+                               null_value.Emit (ec);
+                               ig.Emit (OpCodes.Br, end_label);
+
+                               ig.MarkLabel (wrap_label);
+                               ig.Emit (OpCodes.Nop);
+                               bool_wrap.Emit (ec);
+                               ig.Emit (OpCodes.Nop);
+
+                               ig.MarkLabel (end_label);
+                       }
+
+                       void EmitEquality (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               Label left_not_null_label = ig.DefineLabel ();
+                               Label false_label = ig.DefineLabel ();
+                               Label true_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               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) {
+                                                       true_label_used = true;
+                                                       ig.Emit (OpCodes.Brfalse, true_label);
+                                               } 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);
+                                               right_unwrap.EmitCheck (ec);
+                                               ig.Emit (OpCodes.Ceq);
+                                               if (Oper == Binary.Operator.Inequality) {
+                                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                                       ig.Emit (OpCodes.Ceq);
+                                               }
+                                               ig.Emit (OpCodes.Br, end_label);
+
+                                               ig.MarkLabel (left_not_null_label);
+                                               ig.Emit (OpCodes.Pop);
+                                       } else {
+                                               if (Oper == Binary.Operator.Equality) {
+                                                       false_label_used = true;
+                                                       ig.Emit (OpCodes.Brfalse, false_label);
+                                               } 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) {
+                                                       true_label_used = true;
+                                                       ig.Emit (OpCodes.Brfalse, true_label);
+                                               } else {
+                                                       false_label_used = true;
+                                                       ig.Emit (OpCodes.Brfalse, false_label);
+                                               }
+                                       } else {
+                                               if (Oper == Binary.Operator.Equality) {
+                                                       false_label_used = true;
+                                                       ig.Emit (OpCodes.Brfalse, false_label);
+                                               } else {
+                                                       true_label_used = true;
+                                                       ig.Emit (OpCodes.Brfalse, true_label);
+                                               }
+                                       }
+                               }
+
+                               bool left_is_null = left is NullLiteral;
+                               bool right_is_null = right is NullLiteral;
+                               if (left_is_null || right_is_null) {
+                                       if (((Oper == Binary.Operator.Equality) && (left_is_null == right_is_null)) ||
+                                           ((Oper == Binary.Operator.Inequality) && (left_is_null != right_is_null))) {
+                                               true_label_used = true;
+                                               ig.Emit (OpCodes.Br, true_label);
+                                       } 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);
+                               if (false_label_used) {
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                       if (true_label_used)
+                                               ig.Emit (OpCodes.Br, end_label);
+                               }
+
+                               ig.MarkLabel (true_label);
+                               if (true_label_used)
+                                       ig.Emit (OpCodes.Ldc_I4_1);
+
+                               ig.MarkLabel (end_label);
+                       }
+
+                       void EmitComparision (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               Label is_null_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               if (left_unwrap != null) {
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                               }
+
+                               if (right_unwrap != null) {
+                                       right_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                               }
+
+                               underlying.Emit (ec);
+                               ig.Emit (OpCodes.Br, end_label);
+
+                               ig.MarkLabel (is_null_label);
+                               ig.Emit (OpCodes.Ldc_I4_0);
+
+                               ig.MarkLabel (end_label);
+                       }
+
                        public override void Emit (EmitContext ec)
                        {
+                               if (is_boolean) {
+                                       EmitBoolean (ec);
+                                       return;
+                               } else if (is_equality) {
+                                       EmitEquality (ec);
+                                       return;
+                               } else if (is_comparision) {
+                                       EmitComparision (ec);
+                                       return;
+                               }
+
                                ILGenerator ig = ec.ig;
 
                                Label is_null_label = ig.DefineLabel ();
                                Label end_label = ig.DefineLabel ();
 
-                               if (left_unwrap != null)
-                                       left_unwrap.EmitCheck (ec, is_null_label);
+                               if (left_unwrap != null) {
+                                       left_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                               }
 
-                               if (right_unwrap != null)
-                                       right_unwrap.EmitCheck (ec, is_null_label);
+                               if (right_unwrap != null) {
+                                       right_unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                               }
 
                                underlying.Emit (ec);
                                ig.Emit (OpCodes.Br, end_label);
@@ -2641,5 +3200,232 @@ namespace Mono.CSharp {
                                ig.MarkLabel (end_label);
                        }
                }
+
+               public class OperatorTrueOrFalse : Expression
+               {
+                       public readonly bool IsTrue;
+
+                       Expression expr;
+                       Unwrap unwrap;
+
+                       public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
+                       {
+                               this.IsTrue = is_true;
+                               this.expr = expr;
+                               this.loc = loc;
+                       }
+
+                       public override Expression DoResolve (EmitContext ec)
+                       {
+                               unwrap = new Unwrap (expr, loc);
+                               expr = unwrap.Resolve (ec);
+                               if (expr == null)
+                                       return null;
+
+                               if (unwrap.Type != TypeManager.bool_type)
+                                       return null;
+
+                               type = TypeManager.bool_type;
+                               eclass = ExprClass.Value;
+                               return this;
+                       }
+
+                       public override void Emit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               Label is_null_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               unwrap.EmitCheck (ec);
+                               ig.Emit (OpCodes.Brfalse, is_null_label);
+
+                               unwrap.Emit (ec);
+                               if (!IsTrue) {
+                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                       ig.Emit (OpCodes.Ceq);
+                               }
+                               ig.Emit (OpCodes.Br, end_label);
+
+                               ig.MarkLabel (is_null_label);
+                               ig.Emit (OpCodes.Ldc_I4_0);
+
+                               ig.MarkLabel (end_label);
+                       }
+               }
+
+               public class NullCoalescingOperator : Expression
+               {
+                       Expression left, right;
+                       Expression expr;
+                       Unwrap unwrap;
+
+                       public NullCoalescingOperator (Expression left, Expression right, Location loc)
+                       {
+                               this.left = left;
+                               this.right = right;
+                               this.loc = loc;
+
+                               eclass = ExprClass.Value;
+                       }
+
+                       public override Expression DoResolve (EmitContext ec)
+                       {
+                               if (type != null)
+                                       return this;
+
+                               left = left.Resolve (ec);
+                               if (left == null)
+                                       return null;
+
+                               right = right.Resolve (ec);
+                               if (right == null)
+                                       return null;
+
+                               Type ltype = left.Type, rtype = right.Type;
+
+                               if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
+                                       Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
+                                       return null;
+                               }
+
+                               if (TypeManager.IsNullableType (ltype)) {
+                                       NullableInfo info = new NullableInfo (ltype);
+
+                                       unwrap = (Unwrap) new Unwrap (left, loc).Resolve (ec);
+                                       if (unwrap == null)
+                                               return null;
+
+                                       expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
+                                       if (expr != null) {
+                                               left = unwrap;
+                                               type = expr.Type;
+                                               return this;
+                                       }
+                               }
+
+                               expr = Convert.ImplicitConversion (ec, right, ltype, loc);
+                               if (expr != null) {
+                                       type = expr.Type;
+                                       return this;
+                               }
+
+                               if (unwrap != null) {
+                                       expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
+                                       if (expr != null) {
+                                               left = expr;
+                                               expr = right;
+                                               type = expr.Type;
+                                               return this;
+                                       }
+                               }
+
+                               Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
+                               return null;
+                       }
+
+                       public override void Emit (EmitContext ec)
+                       {
+                               ILGenerator ig = ec.ig;
+
+                               Label is_null_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               if (unwrap != null) {
+                                       unwrap.EmitCheck (ec);
+                                       ig.Emit (OpCodes.Brfalse, is_null_label);
+
+                                       left.Emit (ec);
+                                       ig.Emit (OpCodes.Br, end_label);
+
+                                       ig.MarkLabel (is_null_label);
+                                       expr.Emit (ec);
+
+                                       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);
+                               }
+                       }
+               }
+
+               public class LiftedUnaryMutator : ExpressionStatement
+               {
+                       public readonly UnaryMutator.Mode Mode;
+                       Expression expr, null_value;
+                       UnaryMutator underlying;
+                       Unwrap unwrap;
+
+                       public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
+                       {
+                               this.expr = expr;
+                               this.Mode = mode;
+                               this.loc = loc;
+
+                               eclass = ExprClass.Value;
+                       }
+
+                       public override Expression DoResolve (EmitContext ec)
+                       {
+                               expr = expr.Resolve (ec);
+                               if (expr == null)
+                                       return null;
+
+                               unwrap = (Unwrap) new Unwrap (expr, loc).Resolve (ec);
+                               if (unwrap == null)
+                                       return null;
+
+                               underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
+                               if (underlying == null)
+                                       return null;
+
+                               null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
+                               if (null_value == null)
+                                       return null;
+
+                               type = expr.Type;
+                               return this;
+                       }
+
+                       void DoEmit (EmitContext ec, bool is_expr)
+                       {
+                               ILGenerator ig = ec.ig;
+                               Label is_null_label = ig.DefineLabel ();
+                               Label end_label = ig.DefineLabel ();
+
+                               unwrap.EmitCheck (ec);
+                               ig.Emit (OpCodes.Brfalse, is_null_label);
+
+                               if (is_expr)
+                                       underlying.Emit (ec);
+                               else
+                                       underlying.EmitStatement (ec);
+                               ig.Emit (OpCodes.Br, end_label);
+
+                               ig.MarkLabel (is_null_label);
+                               if (is_expr)
+                                       null_value.Emit (ec);
+
+                               ig.MarkLabel (end_label);
+                       }
+
+                       public override void Emit (EmitContext ec)
+                       {
+                               DoEmit (ec, true);
+                       }
+
+                       public override void EmitStatement (EmitContext ec)
+                       {
+                               DoEmit (ec, false);
+                       }
+               }
        }
 }