Allow imported members cache to be setup in 2 phases as compiled one is to deal with...
[mono.git] / mcs / mcs / generic.cs
index 2677bfeae90dac3925565532294e6db638a40043..06595900499474caefa33699446c180205b01da7 100644 (file)
@@ -16,1193 +16,1539 @@ using System.Reflection.Emit;
 using System.Globalization;
 using System.Collections.Generic;
 using System.Text;
-using System.Text.RegularExpressions;
+using System.Linq;
        
 namespace Mono.CSharp {
+       public enum Variance
+       {
+               //
+               // Don't add or modify internal values, they are used as -/+ calculation signs
+               //
+               None                    = 0,
+               Covariant               = 1,
+               Contravariant   = -1
+       }
 
-       /// <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;
-               }
+       [Flags]
+       public enum SpecialConstraint
+       {
+               None            = 0,
+               Constructor = 1 << 2,
+               Class           = 1 << 3,
+               Struct          = 1 << 4
+       }
 
-               public abstract GenericParameterAttributes Attributes {
-                       get;
+       public class SpecialContraintExpr : FullNamedExpression
+       {
+               public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
+               {
+                       this.loc = loc;
+                       this.Constraint = constraint;
                }
 
-               public bool HasConstructorConstraint {
-                       get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
-               }
+               public SpecialConstraint Constraint { get; private set; }
 
-               public bool HasReferenceTypeConstraint {
-                       get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
+               protected override Expression DoResolve (ResolveContext rc)
+               {
+                       throw new NotImplementedException ();
                }
+       }
 
-               public bool HasValueTypeConstraint {
-                       get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
+       //
+       // A set of parsed constraints for a type parameter
+       //
+       public class Constraints
+       {
+               SimpleMemberName tparam;
+               List<FullNamedExpression> constraints;
+               Location loc;
+               bool resolved;
+               bool resolving;
+               
+               public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
+               {
+                       this.tparam = tparam;
+                       this.constraints = constraints;
+                       this.loc = loc;
                }
 
-               public virtual bool HasClassConstraint {
-                       get { return ClassConstraint != null; }
+               #region Properties
+
+               public Location Location {
+                       get {
+                               return loc;
+                       }
                }
 
-               public abstract Type ClassConstraint {
-                       get;
+               public SimpleMemberName TypeParameter {
+                       get {
+                               return tparam;
+                       }
                }
 
-               public abstract Type[] InterfaceConstraints {
-                       get;
+               #endregion
+
+               bool CheckConflictingInheritedConstraint (TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
+               {
+                       if (!TypeSpec.IsBaseClass (ba, bb, false) && !TypeSpec.IsBaseClass (bb, ba, false)) {
+                               context.Compiler.Report.Error (455, loc,
+                                       "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
+                                       tparam.Value,
+                                       ba.GetSignatureForError (), bb.GetSignatureForError ());
+                               return false;
+                       }
+
+                       return true;
                }
 
-               public abstract Type EffectiveBaseClass {
-                       get;
+               public void CheckGenericConstraints (IMemberContext context)
+               {
+                       foreach (var c in constraints) {
+                               var ge = c as GenericTypeExpr;
+                               if (ge != null)
+                                       ge.CheckConstraints (context);
+                       }
                }
 
-               // <summary>
-               //   Returns whether the type parameter is "known to be a reference type".
-               // </summary>
-               public virtual bool IsReferenceType {
-                       get {
-                               if (HasReferenceTypeConstraint)
-                                       return true;
-                               if (HasValueTypeConstraint)
-                                       return false;
+               //
+               // Resolve the constraints types with only possible early checks, return
+               // value `false' is reserved for recursive failure
+               //
+               public bool Resolve (IMemberContext context, TypeParameter tp)
+               {
+                       if (resolved)
+                               return true;
 
-                               if (ClassConstraint != null) {
-                                       if (ClassConstraint.IsValueType)
-                                               return false;
+                       if (resolving)
+                               return false;
 
-                                       if (ClassConstraint != TypeManager.object_type)
-                                               return true;
+                       resolving = true;
+                       var spec = tp.Type;
+                       List<TypeParameterSpec> tparam_types = null;
+                       bool iface_found = false;
+
+                       spec.BaseType = TypeManager.object_type;
+
+                       for (int i = 0; i < constraints.Count; ++i) {
+                               var constraint = constraints[i];
+
+                               if (constraint is SpecialContraintExpr) {
+                                       spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
+                                       if (spec.HasSpecialStruct)
+                                               spec.BaseType = TypeManager.value_type;
+
+                                       // Set to null as it does not have a type
+                                       constraints[i] = null;
+                                       continue;
                                }
 
-                               foreach (Type t in InterfaceConstraints) {
-                                       if (!t.IsGenericParameter)
-                                               continue;
+                               var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
+                               if (type_expr == null)
+                                       continue;
 
-                                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
-                                       if ((gc != null) && gc.IsReferenceType)
-                                               return true;
+                               var gexpr = type_expr as GenericTypeExpr;
+                               if (gexpr != null && gexpr.HasDynamicArguments ()) {
+                                       context.Compiler.Report.Error (1968, constraint.Location,
+                                               "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
+                                       continue;
                                }
 
-                               return false;
-                       }
-               }
+                               var type = type_expr.Type;
 
-               // <summary>
-               //   Returns whether the type parameter is "known to be a value type".
-               // </summary>
-               public virtual bool IsValueType {
-                       get {
-                               if (HasValueTypeConstraint)
-                                       return true;
-                               if (HasReferenceTypeConstraint)
-                                       return false;
+                               if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
+                                       context.Compiler.Report.SymbolRelatedToPreviousError (type);
+                                       context.Compiler.Report.Error (703, loc,
+                                               "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
+                                               type.GetSignatureForError (), context.GetSignatureForError ());
+                               }
 
-                               if (ClassConstraint != null) {
-                                       if (!TypeManager.IsValueType (ClassConstraint))
-                                               return false;
+                               if (type.IsInterface) {
+                                       if (!spec.AddInterface (type)) {
+                                               context.Compiler.Report.Error (405, constraint.Location,
+                                                       "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
+                                       }
 
-                                       if (ClassConstraint != TypeManager.value_type)
-                                               return true;
+                                       iface_found = true;
+                                       continue;
                                }
 
-                               foreach (Type t in InterfaceConstraints) {
-                                       if (!t.IsGenericParameter)
+
+                               var constraint_tp = type as TypeParameterSpec;
+                               if (constraint_tp != null) {
+                                       if (tparam_types == null) {
+                                               tparam_types = new List<TypeParameterSpec> (2);
+                                       } else if (tparam_types.Contains (constraint_tp)) {
+                                               context.Compiler.Report.Error (405, constraint.Location,
+                                                       "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
                                                continue;
+                                       }
 
-                                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
-                                       if ((gc != null) && gc.IsValueType)
-                                               return true;
+                                       //
+                                       // Checks whether each generic method parameter constraint type
+                                       // is valid with respect to T
+                                       //
+                                       if (tp.IsMethodTypeParameter) {
+                                               TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
+                                       }
+
+                                       var tp_def = constraint_tp.MemberDefinition as TypeParameter;
+                                       if (tp_def != null && !tp_def.ResolveConstraints (context)) {
+                                               context.Compiler.Report.Error (454, constraint.Location,
+                                                       "Circular constraint dependency involving `{0}' and `{1}'",
+                                                       constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
+                                               continue;
+                                       }
+
+                                       //
+                                       // Checks whether there are no conflicts between type parameter constraints
+                                       //
+                                       // class Foo<T, U>
+                                       //      where T : A
+                                       //      where U : B, T
+                                       //
+                                       // A and B are not convertible and only 1 class constraint is allowed
+                                       //
+                                       if (constraint_tp.HasTypeConstraint) {
+                                               if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
+                                                       if (!CheckConflictingInheritedConstraint (spec.BaseType, constraint_tp.BaseType, context, constraint.Location))
+                                                               continue;
+                                               } else {
+                                                       for (int ii = 0; ii < tparam_types.Count; ++ii) {
+                                                               if (!tparam_types[ii].HasTypeConstraint)
+                                                                       continue;
+
+                                                               if (!CheckConflictingInheritedConstraint (tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
+                                                                       break;
+                                                       }
+                                               }
+                                       }
+
+                                       if (constraint_tp.HasSpecialStruct) {
+                                               context.Compiler.Report.Error (456, constraint.Location,
+                                                       "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
+                                                       constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
+                                               continue;
+                                       }
+
+                                       tparam_types.Add (constraint_tp);
+                                       continue;
                                }
 
-                               return false;
+                               if (iface_found || spec.HasTypeConstraint) {
+                                       context.Compiler.Report.Error (406, constraint.Location,
+                                               "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
+                                               type.GetSignatureForError ());
+                               }
+
+                               if (spec.HasSpecialStruct || spec.HasSpecialClass) {
+                                       context.Compiler.Report.Error (450, type_expr.Location,
+                                               "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
+                                               type.GetSignatureForError ());
+                               }
+
+                               if (type == InternalType.Dynamic) {
+                                       context.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
+                                       continue;
+                               }
+
+                               if (type.IsSealed || !type.IsClass) {
+                                       context.Compiler.Report.Error (701, loc,
+                                               "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
+                                               TypeManager.CSharpName (type));
+                                       continue;
+                               }
+
+                               if (type.IsStatic) {
+                                       context.Compiler.Report.Error (717, constraint.Location,
+                                               "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
+                                               type.GetSignatureForError ());
+                               } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
+                                                       type == TypeManager.enum_type || type == TypeManager.value_type ||
+                                                       type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
+                                       context.Compiler.Report.Error (702, constraint.Location,
+                                               "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
+                                       continue;
+                               }
+
+                               spec.BaseType = type;
+                       }
+
+                       if (tparam_types != null)
+                               spec.TypeArguments = tparam_types.ToArray ();
+
+                       resolving = false;
+                       resolved = true;
+                       return true;
+               }
+
+               public void VerifyClsCompliance (Report report)
+               {
+                       foreach (var c in constraints)
+                       {
+                               if (c == null)
+                                       continue;
+
+                               if (!c.Type.IsCLSCompliant ()) {
+                                       report.SymbolRelatedToPreviousError (c.Type);
+                                       report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
+                                               c.Type.GetSignatureForError ());
+                               }
                        }
                }
        }
 
-       public class ReflectionConstraints : GenericConstraints
+       //
+       // A type parameter for a generic type or generic method definition
+       //
+       public class TypeParameter : MemberCore, ITypeDefinition
        {
-               GenericParameterAttributes attrs;
-               Type base_type;
-               Type class_constraint;
-               Type[] iface_constraints;
-               string name;
+               static readonly string[] attribute_target = new string [] { "type parameter" };
+               
+               Constraints constraints;
+               GenericTypeParameterBuilder builder;
+               TypeParameterSpec spec;
 
-               public static GenericConstraints GetConstraints (Type t)
+               public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
+                       : base (parent, name, attrs)
                {
-                       Type[] constraints = t.GetGenericParameterConstraints ();
-                       GenericParameterAttributes attrs = t.GenericParameterAttributes;
-                       if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
-                               return null;
-                       return new ReflectionConstraints (t.Name, constraints, attrs);
+                       this.constraints = constraints;
+                       this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
                }
 
-               private ReflectionConstraints (string name, Type[] constraints, GenericParameterAttributes attrs)
+               public TypeParameter (TypeParameterSpec spec, DeclSpace parent, TypeSpec parentSpec, MemberName name, Attributes attrs)
+                       : base (parent, name, attrs)
                {
-                       this.name = name;
-                       this.attrs = attrs;
+                       this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
+                               BaseType = spec.BaseType,
+                               InterfacesDefined = spec.InterfacesDefined,
+                               TypeArguments = spec.TypeArguments
+                       };
+               }
 
-                       int interface_constraints_pos = 0;
-                       if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
-                               base_type = TypeManager.value_type;
-                               interface_constraints_pos = 1;
-                       } else if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
-                               if (constraints.Length > 0 && constraints[0].IsClass) {
-                                       class_constraint = base_type = constraints[0];
-                                       interface_constraints_pos = 1;
-                               } else {
-                                       base_type = TypeManager.object_type;
-                               }
-                       } else {
-                               base_type = TypeManager.object_type;
+               #region Properties
+
+               public override AttributeTargets AttributeTargets {
+                       get {
+                               return AttributeTargets.GenericParameter;
                        }
+               }
 
-                       if (constraints.Length > interface_constraints_pos) {
-                               if (interface_constraints_pos == 0) {
-                                       iface_constraints = constraints;
-                               } else {
-                                       iface_constraints = new Type[constraints.Length - interface_constraints_pos];
-                                       Array.Copy (constraints, interface_constraints_pos, iface_constraints, 0, iface_constraints.Length);
-                               }
-                       } else {
-                               iface_constraints = Type.EmptyTypes;
+               public override string DocCommentHeader {
+                       get {
+                               throw new InvalidOperationException (
+                                       "Unexpected attempt to get doc comment from " + this.GetType ());
+                       }
+               }
+
+               public bool IsMethodTypeParameter {
+                       get {
+                               return spec.IsMethodOwned;
+                       }
+               }
+
+               public string Namespace {
+                       get {
+                               return null;
+                       }
+               }
+
+               public TypeParameterSpec Type {
+                       get {
+                               return spec;
+                       }
+               }
+
+               public int TypeParametersCount {
+                       get {
+                               return 0;
+                       }
+               }
+
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return null;
+                       }
+               }
+
+               public override string[] ValidAttributeTargets {
+                       get {
+                               return attribute_target;
+                       }
+               }
+
+               public Variance Variance {
+                       get {
+                               return spec.Variance;
+                       }
+               }
+
+               #endregion
+
+               //
+               // This is called for each part of a partial generic type definition.
+               //
+               // If partial type parameters constraints are 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.
+               //
+               public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
+               {
+                       if (builder == null)
+                               throw new InvalidOperationException ();
+
+                       var new_constraints = tp.constraints;
+                       if (new_constraints == null)
+                               return true;
+
+                       // TODO: could create spec only
+                       //tp.Define (null, -1, part.Definition);
+                       tp.spec.DeclaringType = part.Definition;
+                       if (!tp.ResolveConstraints (part))
+                               return false;
+
+                       if (constraints != null)
+                               return spec.HasSameConstraintsDefinition (tp.Type);
+
+                       // Copy constraint from resolved part to partial container
+                       spec.SpecialConstraint = tp.spec.SpecialConstraint;
+                       spec.InterfacesDefined = tp.spec.InterfacesDefined;
+                       spec.TypeArguments = tp.spec.TypeArguments;
+                       spec.BaseType = tp.spec.BaseType;
+                       
+                       return true;
+               }
+
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+               {
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+               }
+
+               public void CheckGenericConstraints ()
+               {
+                       if (constraints != null)
+                               constraints.CheckGenericConstraints (this);
+               }
+
+               public TypeParameter CreateHoistedCopy (TypeContainer declaringType, TypeSpec declaringSpec)
+               {
+                       return new TypeParameter (spec, declaringType, declaringSpec, MemberName, null);
+               }
+
+               public override bool Define ()
+               {
+                       return true;
+               }
+
+               //
+               // 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).
+               //
+               public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
+               {
+                       if (builder != null)
+                               throw new InternalErrorException ();
+
+                       this.builder = type;
+                       spec.DeclaringType = declaringType;
+                       spec.SetMetaInfo (type);
+               }
+
+               public void EmitConstraints (GenericTypeParameterBuilder builder)
+               {
+                       var attr = GenericParameterAttributes.None;
+                       if (spec.Variance == Variance.Contravariant)
+                               attr |= GenericParameterAttributes.Contravariant;
+                       else if (spec.Variance == Variance.Covariant)
+                               attr |= GenericParameterAttributes.Covariant;
+
+                       if (spec.HasSpecialClass)
+                               attr |= GenericParameterAttributes.ReferenceTypeConstraint;
+                       else if (spec.HasSpecialStruct)
+                               attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
+
+                       if (spec.HasSpecialConstructor)
+                               attr |= GenericParameterAttributes.DefaultConstructorConstraint;
+
+                       if (spec.BaseType != TypeManager.object_type)
+                               builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
+
+                       if (spec.InterfacesDefined != null)
+                               builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
+
+                       if (spec.TypeArguments != null)
+                               builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
+
+                       builder.SetGenericParameterAttributes (attr);
+               }
+
+               public override void Emit ()
+               {
+                       EmitConstraints (builder);
+
+                       if (OptAttributes != null)
+                               OptAttributes.Emit ();
+
+                       base.Emit ();
+               }
+
+               public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
+               {
+                       Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
+                       string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
+                       string gtype_variance;
+                       switch (expected) {
+                       case Variance.Contravariant: gtype_variance = "contravariantly"; break;
+                       case Variance.Covariant: gtype_variance = "covariantly"; break;
+                       default: gtype_variance = "invariantly"; break;
                        }
+
+                       Delegate d = mc as Delegate;
+                       string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
+
+                       Report.Error (1961, Location,
+                               "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
+                                       GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
                }
 
-               public override string TypeParameter
-               {
-                       get { return name; }
-               }
+               public TypeSpec GetAttributeCoClass ()
+               {
+                       return null;
+               }
+
+               public string GetAttributeDefaultMember ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return MemberName.Name;
+               }
+
+               public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+               {
+                       throw new NotSupportedException ("Not supported for compiled definition");
+               }
+
+               //
+               // Resolves all type parameter constraints
+               //
+               public bool ResolveConstraints (IMemberContext context)
+               {
+                       if (constraints != null)
+                               return constraints.Resolve (context, this);
+
+                       if (spec.BaseType == null)
+                               spec.BaseType = TypeManager.object_type;
 
-               public override GenericParameterAttributes Attributes
-               {
-                       get { return attrs; }
+                       return true;
                }
 
-               public override Type ClassConstraint
+               public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
                {
-                       get { return class_constraint; }
+                       foreach (var tp in tparams) {
+                               if (tp.Name == name)
+                                       return tp;
+                       }
+
+                       return null;
                }
 
-               public override Type EffectiveBaseClass
+               public override bool IsClsComplianceRequired ()
                {
-                       get { return base_type; }
+                       return false;
                }
 
-               public override Type[] InterfaceConstraints
+               public new void VerifyClsCompliance ()
                {
-                       get { return iface_constraints; }
+                       if (constraints != null)
+                               constraints.VerifyClsCompliance (Report);
                }
        }
 
-       public enum Variance
+       [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
+       public class TypeParameterSpec : TypeSpec
        {
+               public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
+
+               Variance variance;
+               SpecialConstraint spec;
+               readonly int tp_pos;
+               TypeSpec[] targs;
+               TypeSpec[] ifaces_defined;
+
                //
-               // Don't add or modify internal values, they are used as -/+ calculation signs
+               // Creates type owned type parameter
                //
-               None                    = 0,
-               Covariant               = 1,
-               Contravariant   = -1
-       }
-
-       public enum SpecialConstraint
-       {
-               Constructor,
-               ReferenceType,
-               ValueType
-       }
+               public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
+                       : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
+               {
+                       this.variance = variance;
+                       this.spec = spec;
+                       state &= ~StateFlags.Obsolete_Undetected;
+                       tp_pos = index;
+               }
 
-       /// <summary>
-       ///   Tracks the constraints for a type parameter from a generic type definition.
-       /// </summary>
-       public class Constraints : GenericConstraints {
-               string name;
-               List<object> constraints;
-               Location loc;
-               
                //
-               // name is the identifier, constraints is an arraylist of
-               // Expressions (with types) or `true' for the constructor constraint.
-               // 
-               public Constraints (string name, List<object> constraints, Location loc)
+               // Creates method owned type parameter
+               //
+               public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
+                       : this (null, index, definition, spec, variance, info)
                {
-                       this.name = name;
-                       this.constraints = constraints;
-                       this.loc = loc;
                }
 
-               public override string TypeParameter {
+               #region Properties
+
+               public int DeclaredPosition {
                        get {
-                               return name;
+                               return tp_pos;
                        }
                }
 
-               public Constraints Clone ()
-               {
-                       return new Constraints (name, constraints, loc);
+               public bool HasSpecialConstructor {
+                       get {
+                               return (spec & SpecialConstraint.Constructor) != 0;
+                       }
                }
 
-               GenericParameterAttributes attrs;
-               TypeExpr class_constraint;
-               List<TypeExpr> iface_constraints;
-               List<TypeExpr> type_param_constraints;
-               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 (MemberCore ec, TypeParameter tp, Report Report)
-               {
-                       if (resolved)
-                               return true;
-
-                       if (ec == null)
-                               return false;
-
-                       iface_constraints = new List<TypeExpr> (2);     // TODO: Too expensive allocation
-                       type_param_constraints = new List<TypeExpr> ();
+               public bool HasSpecialClass {
+                       get {
+                               return (spec & SpecialConstraint.Class) != 0;
+                       }
+               }
 
-                       foreach (object obj in constraints) {
-                               if (HasConstructorConstraint) {
-                                       Report.Error (401, loc,
-                                                     "The new() constraint must be the last constraint specified");
-                                       return false;
-                               }
+               public bool HasSpecialStruct {
+                       get {
+                               return (spec & SpecialConstraint.Struct) != 0;
+                       }
+               }
 
-                               if (obj is SpecialConstraint) {
-                                       SpecialConstraint sc = (SpecialConstraint) obj;
+               public bool HasTypeConstraint {
+                       get {
+                               return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
+                       }
+               }
 
-                                       if (sc == SpecialConstraint.Constructor) {
-                                               if (!HasValueTypeConstraint) {
-                                                       attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
-                                                       continue;
+               public override IList<TypeSpec> Interfaces {
+                       get {
+                               if ((state & StateFlags.InterfacesExpanded) == 0) {
+                                       if (ifaces != null) {
+                                               for (int i = 0; i < ifaces.Count; ++i ) {
+                                                       var iface_type = ifaces[i];
+                                                       if (iface_type.Interfaces != null) {
+                                                               if (ifaces_defined == null)
+                                                                       ifaces_defined = ifaces.ToArray ();
+
+                                                               for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
+                                                                       var ii_iface_type = iface_type.Interfaces [ii];
+
+                                                                       AddInterface (ii_iface_type);
+                                                               }
+                                                       }
                                                }
-
-                                               Report.Error (451, loc, "The `new()' constraint " +
-                                                       "cannot be used with the `struct' constraint");
-                                               return false;
                                        }
 
-                                       if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
-                                               Report.Error (449, loc, "The `class' or `struct' " +
-                                                             "constraint must be the first constraint specified");
-                                               return false;
-                                       }
+                                       if (ifaces_defined == null && ifaces != null)
+                                               ifaces_defined = ifaces.ToArray ();
 
-                                       if (sc == SpecialConstraint.ReferenceType)
-                                               attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
-                                       else
-                                               attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
-                                       continue;
+                                       state |= StateFlags.InterfacesExpanded;
                                }
 
-                               int errors = Report.Errors;
-                               FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
+                               return ifaces;
+                       }
+               }
 
-                               if (fn == null) {
-                                       if (errors != Report.Errors)
-                                               return false;
+               //
+               // Unexpanded interfaces list
+               //
+               public TypeSpec[] InterfacesDefined {
+                       get {
+                               if (ifaces_defined == null && ifaces != null)
+                                       ifaces_defined = ifaces.ToArray ();
 
-                                       NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError (), Report);
-                                       return false;
-                               }
+                               return ifaces_defined;
+                       }
+                       set {
+                               ifaces_defined = value;
+                       }
+               }
 
-                               TypeExpr expr;
-                               GenericTypeExpr cexpr = fn as GenericTypeExpr;
-                               if (cexpr != null) {
-                                       expr = cexpr.ResolveAsBaseTerminal (ec, false);
-                                       if (expr != null && cexpr.HasDynamicArguments ()) {
-                                               Report.Error (1968, cexpr.Location,
-                                                       "A constraint cannot be the dynamic type `{0}'",
-                                                       cexpr.GetSignatureForError ());
-                                               expr = null;
-                                       }
-                               } else
-                                       expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
+               public bool IsConstrained {
+                       get {
+                               return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
+                       }
+               }
 
-                               if ((expr == null) || (expr.Type == null))
-                                       return false;
+               //
+               // Returns whether the type parameter is "known to be a reference type"
+               //
+               public bool IsReferenceType {
+                       get {
+                               return (spec & SpecialConstraint.Class) != 0 || HasTypeConstraint;
+                       }
+               }
 
-                               if (TypeManager.IsGenericParameter (expr.Type))
-                                       type_param_constraints.Add (expr);
-                               else if (expr.IsInterface)
-                                       iface_constraints.Add (expr);
-                               else if (class_constraint != null || iface_constraints.Count != 0) {
-                                       Report.Error (406, loc,
-                                               "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
-                                               expr.GetSignatureForError ());
-                                       return false;
-                               } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
-                                       Report.Error (450, loc, "`{0}': cannot specify both " +
-                                                     "a constraint class and the `class' " +
-                                                     "or `struct' constraint", expr.GetSignatureForError ());
-                                       return false;
-                               } else
-                                       class_constraint = expr;
+               public bool IsValueType {       // TODO: Do I need this ?
+                       get {
+                               // TODO MemberCache: probably wrong
+                               return HasSpecialStruct;
+                       }
+               }
 
+               public override string Name {
+                       get {
+                               return definition.Name;
+                       }
+               }
 
-                               //
-                               // Checks whether each generic method parameter constraint type
-                               // is valid with respect to T
-                               //
-                               if (tp != null && tp.Type.DeclaringMethod != null) {
-                                       TypeManager.CheckTypeVariance (expr.Type, Variance.Contravariant, ec as MemberCore);
-                               }
+               public bool IsMethodOwned {
+                       get {
+                               return DeclaringType == null;
+                       }
+               }
 
-                               if (!ec.IsAccessibleAs (fn.Type)) {
-                                       Report.SymbolRelatedToPreviousError (fn.Type);
-                                       Report.Error (703, loc,
-                                               "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
-                                               fn.GetSignatureForError (), ec.GetSignatureForError ());
-                               }
+               public SpecialConstraint SpecialConstraint {
+                       get {
+                               return spec;
+                       }
+                       set {
+                               spec = value;
+                       }
+               }
 
-                               num_constraints++;
+               //
+               // Types used to inflate the generic type
+               //
+               public new TypeSpec[] TypeArguments {
+                       get {
+                               return targs;
                        }
+                       set {
+                               targs = value;
+                       }
+               }
 
-                       var list = new List<Type> ();
-                       foreach (TypeExpr iface_constraint in iface_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (iface_constraint.Type))
-                                               continue;
+               public Variance Variance {
+                       get {
+                               return variance;
+                       }
+               }
 
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", iface_constraint.GetSignatureForError (),
-                                                     name);
-                                       return false;
-                               }
+               #endregion
 
-                               list.Add (iface_constraint.Type);
-                       }
+               public string DisplayDebugInfo ()
+               {
+                       var s = GetSignatureForError ();
+                       return IsMethodOwned ? s + "!!" : s + "!";
+               }
 
-                       foreach (TypeExpr expr in type_param_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (expr.Type))
-                                               continue;
+               //
+               // Finds effective base class
+               //
+               public TypeSpec GetEffectiveBase ()
+               {
+                       if (HasSpecialStruct) {
+                               return TypeManager.value_type;
+                       }
 
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", expr.GetSignatureForError (), name);
-                                       return false;
-                               }
+                       if (BaseType != null && targs == null)
+                               return BaseType;
 
-                               list.Add (expr.Type);
+                       var types = targs;
+                       if (HasTypeConstraint) {
+                               Array.Resize (ref types, types.Length + 1);
+                               types[types.Length - 1] = BaseType;
                        }
 
-                       iface_constraint_types = new Type [list.Count];
-                       list.CopyTo (iface_constraint_types, 0);
+                       if (types != null)
+                               return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
 
-                       if (class_constraint != null) {
-                               class_constraint_type = class_constraint.Type;
-                               if (class_constraint_type == null)
-                                       return false;
+                       return TypeManager.object_type;
+               }
 
-                               if (class_constraint_type.IsSealed) {
-                                       if (class_constraint_type.IsAbstract)
-                                       {
-                                               Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
-                                                       TypeManager.CSharpName (class_constraint_type));
-                                       }
-                                       else
-                                       {
-                                               Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
-                                                       "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
-                                       }
-                                       return false;
-                               }
+               public override string GetSignatureForError ()
+               {
+                       return Name;
+               }
 
-                               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) ||
-                                       class_constraint_type == TypeManager.multicast_delegate_type) {
-                                       Report.Error (702, loc,
-                                                         "A constraint cannot be special class `{0}'",
-                                                     TypeManager.CSharpName (class_constraint_type));
-                                       return false;
-                               }
+               //
+               // Constraints have to match by definition but not position, used by
+               // partial classes or methods
+               //
+               public bool HasSameConstraintsDefinition (TypeParameterSpec other)
+               {
+                       if (spec != other.spec)
+                               return false;
 
-                               if (TypeManager.IsDynamicType (class_constraint_type)) {
-                                       Report.Error (1967, loc, "A constraint cannot be the dynamic type");
-                                       return false;
-                               }
-                       }
+                       if (BaseType != other.BaseType)
+                               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;
+                       if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
+                               return false;
 
-                       if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
-                               attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
+                       if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
+                               return false;
 
-                       resolved = true;
                        return true;
                }
 
-               bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, List<Type> seen, Report Report)
+               //
+               // Constraints have to match by using same set of types, used by
+               // implicit interface implementation
+               //
+               public bool HasSameConstraintsImplementation (TypeParameterSpec other)
                {
-                       seen.Add (tparam);
-
-                       Constraints constraints = TypeManager.LookupTypeParameter (tparam).Constraints;
-                       if (constraints == null)
-                               return true;
-
-                       if (constraints.HasValueTypeConstraint) {
-                               Report.Error (456, loc,
-                                       "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
-                                       tparam.Name, name);
+                       if (spec != other.spec)
                                return false;
-                       }
 
                        //
-                       //  Checks whether there are no conflicts between type parameter constraints
+                       // It can be same base type or inflated type parameter
                        //
-                       //   class Foo<T, U>
-                       //      where T : A
-                       //      where U : A, B  // A and B are not convertible
+                       // interface I<T> { void Foo<U> where U : T; }
+                       // class A : I<int> { void Foo<X> where X : int {} }
                        //
-                       if (constraints.HasClassConstraint) {
-                               if (prevConstraint != null) {
-                                       Type t2 = constraints.ClassConstraint;
-                                       TypeExpr e2 = constraints.class_constraint;
-
-                                       if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
-                                               !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
-                                               Report.Error (455, loc,
-                                                       "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
-                                                       name, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
-                                               return false;
-                                       }
-                               }
-
-                               prevConstraint = constraints.class_constraint;
-                       }
-
-                       if (constraints.type_param_constraints == null)
-                               return true;
-
-                       foreach (TypeExpr expr in constraints.type_param_constraints) {
-                               if (seen.Contains (expr.Type)) {
-                                       Report.Error (454, loc, "Circular constraint " +
-                                                     "dependency involving `{0}' and `{1}'",
-                                                     tparam.Name, expr.GetSignatureForError ());
+                       bool found;
+                       if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
+                               if (other.targs == null)
                                        return false;
+
+                               found = false;
+                               foreach (var otarg in other.targs) {
+                                       if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
+                                               found = true;
+                                               break;
+                                       }
                                }
 
-                               if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen, Report))
+                               if (!found)
                                        return false;
                        }
 
-                       return true;
-               }
+                       // Check interfaces implementation -> definition
+                       if (InterfacesDefined != null) {
+                               foreach (var iface in InterfacesDefined) {
+                                       found = false;
+                                       if (other.InterfacesDefined != null) {
+                                               foreach (var oiface in other.InterfacesDefined) {
+                                                       if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
+                                                               found = true;
+                                                               break;
+                                                       }
+                                               }
+                                       }
 
-               /// <summary>
-               ///   Resolve the constraints into actual types.
-               /// </summary>
-               public bool ResolveTypes (IMemberContext ec, Report r)
-               {
-                       if (resolved_types)
-                               return true;
+                                       if (found)
+                                               continue;
 
-                       resolved_types = true;
+                                       if (other.targs != null) {
+                                               foreach (var otarg in other.targs) {
+                                                       if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
+                                                               found = true;
+                                                               break;
+                                                       }
+                                               }
+                                       }
 
-                       foreach (object obj in constraints) {
-                               GenericTypeExpr cexpr = obj as GenericTypeExpr;
-                               if (cexpr == null)
-                                       continue;
+                                       if (!found)
+                                               return false;
+                               }
+                       }
 
-                               if (!cexpr.CheckConstraints (ec))
+                       // Check interfaces implementation <- definition
+                       if (other.InterfacesDefined != null) {
+                               if (InterfacesDefined == null)
                                        return false;
-                       }
 
-                       if (type_param_constraints.Count != 0) {
-                               var seen = new List<Type> ();
-                               TypeExpr prev_constraint = class_constraint;
-                               foreach (TypeExpr expr in type_param_constraints) {
-                                       if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen, r))
+                               foreach (var oiface in other.InterfacesDefined) {
+                                       found = false;
+                                       foreach (var iface in InterfacesDefined) {
+                                               if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (!found)
                                                return false;
-                                       seen.Clear ();
                                }
                        }
 
-                       for (int i = 0; i < iface_constraints.Count; ++i) {
-                               TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
-                               iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
-                               if (iface_constraint == null)
+                       // Check type parameters implementation -> definition
+                       if (targs != null) {
+                               if (other.targs == null)
                                        return false;
-                               iface_constraints [i] = iface_constraint;
-                       }
 
-                       if (class_constraint != null) {
-                               class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
-                               if (class_constraint == null)
-                                       return false;
-                       }
+                               foreach (var targ in targs) {
+                                       found = false;
+                                       foreach (var otarg in other.targs) {
+                                               if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
 
-                       return true;
-               }
+                                       if (!found)
+                                               return false;
+                               }
+                       }
 
-               public override GenericParameterAttributes Attributes {
-                       get { return attrs; }
-               }
+                       // Check type parameters implementation <- definition
+                       if (other.targs != null) {
+                               foreach (var otarg in other.targs) {
+                                       // Ignore inflated type arguments, were checked above
+                                       if (!otarg.IsGenericParameter)
+                                               continue;
 
-               public override bool HasClassConstraint {
-                       get { return class_constraint != null; }
-               }
+                                       if (targs == null)
+                                               return false;
 
-               public override Type ClassConstraint {
-                       get { return class_constraint_type; }
-               }
+                                       found = false;
+                                       foreach (var targ in targs) {
+                                               if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
 
-               public override Type[] InterfaceConstraints {
-                       get { return iface_constraint_types; }
-               }
+                                       if (!found)
+                                               return false;
+                               }                               
+                       }
 
-               public override Type EffectiveBaseClass {
-                       get { return effective_base_type; }
+                       return true;
                }
 
-               public bool IsSubclassOf (Type t)
+               public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
                {
-                       if ((class_constraint_type != null) &&
-                           class_constraint_type.IsSubclassOf (t))
-                               return true;
+                       TypeParameterSpec[] constraints = null;
 
-                       if (iface_constraint_types == null)
-                               return false;
+                       for (int i = 0; i < tparams.Length; ++i) {
+                               var tp = tparams[i];
+                               if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
+                                       if (constraints == null) {
+                                               constraints = new TypeParameterSpec[tparams.Length];
+                                               Array.Copy (tparams, constraints, constraints.Length);
+                                       }
 
-                       foreach (Type iface in iface_constraint_types) {
-                               if (TypeManager.IsSubclassOf (iface, t))
-                                       return true;
+                                       constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator);
+                               }
                        }
 
-                       return false;
-               }
+                       if (constraints == null)
+                               constraints = tparams;
 
-               public Location Location {
-                       get {
-                               return loc;
-                       }
+                       return constraints;
                }
 
-               /// <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 AreEqual (GenericConstraints gc)
+               public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
                {
-                       if (gc.Attributes != attrs)
-                               return false;
-
-                       if (HasClassConstraint != gc.HasClassConstraint)
-                               return false;
-                       if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
-                               return false;
-
-                       int gc_icount = gc.InterfaceConstraints != null ?
-                               gc.InterfaceConstraints.Length : 0;
-                       int icount = InterfaceConstraints != null ?
-                               InterfaceConstraints.Length : 0;
-
-                       if (gc_icount != icount)
-                               return false;
-
-                       for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
-                               Type iface = gc.InterfaceConstraints [i];
-                               if (iface.IsGenericType)
-                                       iface = iface.GetGenericTypeDefinition ();
-                               
-                               bool ok = false;
-                               for (int ii = 0; ii < InterfaceConstraints.Length; ii++) {
-                                       Type check = InterfaceConstraints [ii];
-                                       if (check.IsGenericType)
-                                               check = check.GetGenericTypeDefinition ();
-                                       
-                                       if (TypeManager.IsEqual (iface, check)) {
-                                               ok = true;
-                                               break;
-                                       }
-                               }
-
-                               if (!ok)
-                                       return false;
+                       tps.BaseType = inflator.Inflate (BaseType);
+                       if (ifaces != null) {
+                               tps.ifaces = new List<TypeSpec> (ifaces.Count);
+                               for (int i = 0; i < ifaces.Count; ++i)
+                                       tps.ifaces.Add (inflator.Inflate (ifaces[i]));
+                       }
+                       if (targs != null) {
+                               tps.targs = new TypeSpec[targs.Length];
+                               for (int i = 0; i < targs.Length; ++i)
+                                       tps.targs[i] = inflator.Inflate (targs[i]);
                        }
+               }
 
-                       return true;
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var tps = (TypeParameterSpec) MemberwiseClone ();
+                       InflateConstraints (inflator, tps);
+                       return tps;
+               }
+
+               //
+               // Populates type parameter members using type parameter constraints
+               // The trick here is to be called late enough but not too late to
+               // populate member cache with all members from other types
+               //
+               protected override void InitializeMemberCache (bool onlyTypes)
+               {
+                       cache = new MemberCache ();
+                       if (ifaces != null) {
+                               foreach (var iface_type in Interfaces) {
+                                       cache.AddInterface (iface_type);
+                               }
+                       }
                }
 
-               public void VerifyClsCompliance (Report r)
+               public bool IsConvertibleToInterface (TypeSpec iface)
                {
-                       if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
-                               Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location, r);
+                       if (Interfaces != null) {
+                               foreach (var t in Interfaces) {
+                                       if (t == iface)
+                                               return true;
+                               }
+                       }
 
-                       if (iface_constraint_types != null) {
-                               for (int i = 0; i < iface_constraint_types.Length; ++i) {
-                                       if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
-                                               Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
-                                                       ((TypeExpr)iface_constraints [i]).Location, r);
+                       if (TypeArguments != null) {
+                               foreach (var t in TypeArguments) {
+                                       if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
+                                               return true;
                                }
                        }
+
+                       return false;
                }
 
-               void Warning_ConstrainIsNotClsCompliant (Type t, Location loc, Report Report)
+               public override TypeSpec Mutate (TypeParameterMutator mutator)
                {
-                       Report.SymbolRelatedToPreviousError (t);
-                       Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
-                               TypeManager.CSharpName (t));
+                       return mutator.Mutate (this);
                }
        }
 
-       /// <summary>
-       ///   A type parameter from a generic type definition.
-       /// </summary>
-       public class TypeParameter : MemberCore, IMemberContainer
+       public struct TypeParameterInflator
        {
-               static readonly string[] attribute_target = new string [] { "type parameter" };
-               
-               DeclSpace decl;
-               GenericConstraints gc;
-               Constraints constraints;
-               GenericTypeParameterBuilder type;
-               MemberCache member_cache;
-               Variance variance;
+               readonly TypeSpec type;
+               readonly TypeParameterSpec[] tparams;
+               readonly TypeSpec[] targs;
 
-               public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
-                                     Constraints constraints, Attributes attrs, Variance variance, Location loc)
-                       : base (parent, new MemberName (name, loc), attrs)
+               public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
+                       : this (type, nested.tparams, nested.targs)
                {
-                       this.decl = decl;
-                       this.constraints = constraints;
-                       this.variance = variance;
                }
 
-               public GenericConstraints GenericConstraints {
-                       get { return gc != null ? gc : constraints; }
-               }
-
-               public Constraints Constraints {
-                       get { return constraints; }
-               }
-
-               public DeclSpace DeclSpace {
-                       get { return decl; }
-               }
+               public TypeParameterInflator (TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
+               {
+                       if (tparams.Length != targs.Length)
+                               throw new ArgumentException ("Invalid arguments");
 
-               public Variance Variance {
-                       get { return variance; }
+                       this.tparams = tparams;
+                       this.targs = targs;
+                       this.type = type;
                }
 
-               public Type Type {
-                       get { return type; }
+               //
+               // Type parameters to inflate
+               //
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return tparams;
+                       }
                }
 
-               /// <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)
+               public TypeSpec Inflate (TypeSpec ts)
                {
-                       if (this.type != null)
-                               throw new InvalidOperationException ();
+                       var tp = ts as TypeParameterSpec;
+                       if (tp != null)
+                               return Inflate (tp);
 
-                       this.type = type;
-                       TypeManager.AddTypeParameter (type, this);
-               }
+                       var ac = ts as ArrayContainer;
+                       if (ac != null) {
+                               var et = Inflate (ac.Element);
+                               if (et != ac.Element)
+                                       return ArrayContainer.MakeType (et, ac.Rank);
 
-               public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
-               {
-// TODO:       Report.SymbolRelatedToPreviousError (mc);
-                       string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
-                       string gtype_variance;
-                       switch (expected) {
-                       case Variance.Contravariant: gtype_variance = "contravariantly"; break;
-                       case Variance.Covariant: gtype_variance = "covariantly"; break;
-                       default: gtype_variance = "invariantly"; break;
+                               return ac;
                        }
 
-                       Delegate d = mc as Delegate;
-                       string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
+                       //
+                       // When inflating a nested type, inflate its parent first
+                       // in case it's using same type parameters (was inflated within the type)
+                       //
+                       if (ts.IsNested) {
+                               var parent = Inflate (ts.DeclaringType);
+                               if (ts.DeclaringType != parent) {
+                                       //
+                                       // Keep the inflated type arguments
+                                       // 
+                                       var targs = ts.TypeArguments;
 
-                       Report.Error (1961, Location,
-                               "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
-                                       GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
-               }
+                                       //
+                                       // Parent was inflated, find the same type on inflated type
+                                       // to use same cache for nested types on same generic parent
+                                       //
+                                       // TODO: Should use BindingRestriction.DeclaredOnly or GetMember
+                                       ts = MemberCache.FindNestedType (parent, ts.Name, ts.Arity);
 
-               /// <summary>
-               ///   This is the second method which is called during the resolving
-               ///   process - in case of class type parameters, we're called from
-               ///   TypeContainer.ResolveType() - after it resolved the class'es
-               ///   base class and interfaces. For method type parameters, we're
-               ///   called immediately after Define().
-               ///
-               ///   We're just resolving the constraints into expressions here, we
-               ///   don't resolve them into actual types.
-               ///
-               ///   Note that in the special case of partial generic classes, we may be
-               ///   called _before_ Define() and we may also be called multiple types.
-               /// </summary>
-               public bool Resolve (DeclSpace ds)
-               {
-                       if (constraints != null) {
-                               if (!constraints.Resolve (ds, this, Report)) {
-                                       constraints = null;
-                                       return false;
-                               }
-                       }
+                                       //
+                                       // Handle the tricky case where parent shares local type arguments
+                                       // which means inflating inflated type
+                                       //
+                                       // class Test<T> {
+                                       //              public static Nested<T> Foo () { return null; }
+                                       //
+                                       //              public class Nested<U> {}
+                                       //      }
+                                       //
+                                       //  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
+                                       //
+                                       if (targs.Length > 0) {
+                                               var inflated_targs = new TypeSpec [targs.Length];
+                                               for (var i = 0; i < targs.Length; ++i)
+                                                       inflated_targs[i] = Inflate (targs[i]);
 
-                       return true;
-               }
+                                               ts = ts.MakeGenericType (inflated_targs);
+                                       }
 
-               /// <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 (IMemberContext ec)
-               {
-                       if (constraints != null) {
-                               if (!constraints.ResolveTypes (ec, Report)) {
-                                       constraints = null;
-                                       return false;
+                                       return ts;
                                }
                        }
 
-                       return true;
+                       // Inflate generic type
+                       if (ts.Arity > 0)
+                               return InflateTypeParameters (ts);
+
+                       return ts;
                }
 
-               /// <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 (IMemberContext ec)
+               public TypeSpec Inflate (TypeParameterSpec tp)
                {
-                       return DefineType (ec, null, null, false);
+                       for (int i = 0; i < tparams.Length; ++i)
+                               if (tparams [i] == tp)
+                                       return targs[i];
+
+                       // This can happen when inflating nested types
+                       // without type arguments specified
+                       return tp;
                }
 
-               /// <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 (IMemberContext ec, MethodBuilder builder,
-                                       MethodInfo implementing, bool is_override)
+               //
+               // Inflates generic types
+               //
+               TypeSpec InflateTypeParameters (TypeSpec type)
                {
-                       if (!ResolveType (ec))
-                               return false;
+                       var targs = new TypeSpec[type.Arity];
+                       var i = 0;
 
-                       if (implementing != null) {
-                               if (is_override && (constraints != null)) {
-                                       Report.Error (460, Location,
-                                               "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
-                                               TypeManager.CSharpSignature (builder));
-                                       return false;
-                               }
+                       var gti = type as InflatedTypeSpec;
 
-                               MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
+                       //
+                       // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
+                       //
+                       if (gti != null) {
+                               for (; i < targs.Length; ++i)
+                                       targs[i] = Inflate (gti.TypeArguments[i]);
 
-                               int pos = type.GenericParameterPosition;
-                               Type mparam = mb.GetGenericArguments () [pos];
-                               GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
+                               return gti.GetDefinition ().MakeGenericType (targs);
+                       }
 
-                               if (temp_gc != null)
-                                       gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
-                               else if (constraints != null)
-                                       gc = new InflatedConstraints (constraints, implementing.DeclaringType);
+                       //
+                       // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
+                       //
+                       var args = type.MemberDefinition.TypeParameters;
+                       foreach (var ds_tp in args)
+                               targs[i++] = Inflate (ds_tp);
 
-                               bool ok = true;
-                               if (constraints != null) {
-                                       if (temp_gc == null)
-                                               ok = false;
-                                       else if (!constraints.AreEqual (gc))
-                                               ok = false;
-                               } else {
-                                       if (!is_override && (temp_gc != null))
-                                               ok = false;
-                               }
+                       return type.MakeGenericType (targs);
+               }
 
-                               if (!ok) {
-                                       Report.SymbolRelatedToPreviousError (implementing);
+               public TypeSpec TypeInstance {
+                       get { return type; }
+               }
+       }
 
-                                       Report.Error (
-                                               425, Location, "The constraints for type " +
-                                               "parameter `{0}' of method `{1}' must match " +
-                                               "the constraints for type parameter `{2}' " +
-                                               "of interface method `{3}'. Consider using " +
-                                               "an explicit interface implementation instead",
-                                               Name, TypeManager.CSharpSignature (builder),
-                                               TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
-                                       return false;
-                               }
-                       } else if (DeclSpace is CompilerGeneratedClass) {
-                               TypeParameter[] tparams = DeclSpace.TypeParameters;
-                               Type[] types = new Type [tparams.Length];
-                               for (int i = 0; i < tparams.Length; i++)
-                                       types [i] = tparams [i].Type;
+       //
+       // Before emitting any code we have to change all MVAR references to VAR
+       // when the method is of generic type and has hoisted variables
+       //
+       public class TypeParameterMutator
+       {
+               TypeParameter[] mvar;
+               TypeParameter[] var;
+               Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
 
-                               if (constraints != null)
-                                       gc = new InflatedConstraints (constraints, types);
-                       } else {
-                               gc = (GenericConstraints) constraints;
-                       }
+               public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
+               {
+                       if (mvar.Length != var.Length)
+                               throw new ArgumentException ();
 
-                       SetConstraints (type);
-                       return true;
+                       this.mvar = mvar;
+                       this.var = var;
                }
 
-               public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
-               {
-                       foreach (var tp in tparams) {
-                               if (tp.Name == name)
-                                       return tp;
-                       }
+               #region Properties
 
-                       return null;
+               public TypeParameter[] MethodTypeParameters {
+                       get {
+                               return mvar;
+                       }
                }
 
-               public void SetConstraints (GenericTypeParameterBuilder type)
-               {
-                       GenericParameterAttributes attr = GenericParameterAttributes.None;
-                       if (variance == Variance.Contravariant)
-                               attr |= GenericParameterAttributes.Contravariant;
-                       else if (variance == Variance.Covariant)
-                               attr |= GenericParameterAttributes.Covariant;
+               #endregion
 
-                       if (gc != null) {
-                               if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
-                                       type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
+               public static TypeSpec GetMemberDeclaringType (TypeSpec type)
+               {
+                       if (type is InflatedTypeSpec) {
+                               if (type.DeclaringType == null)
+                                       return type.GetDefinition ();
 
-                               attr |= gc.Attributes;
-                               type.SetInterfaceConstraints (gc.InterfaceConstraints);
-                               TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
+                               var parent = GetMemberDeclaringType (type.DeclaringType);
+                               type = MemberCache.GetMember<TypeSpec> (parent, type);
                        }
-                       
-                       type.SetGenericParameterAttributes (attr);
+
+                       return type;
                }
 
-               /// <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 (MemberCore ec, Constraints new_constraints)
+               public TypeSpec Mutate (TypeSpec ts)
                {
-                       if (type == null)
-                               throw new InvalidOperationException ();
+                       TypeSpec value;
+                       if (mutated_typespec.TryGetValue (ts, out value))
+                               return value;
 
-                       if (new_constraints == null)
-                               return true;
-
-                       if (!new_constraints.Resolve (ec, this, Report))
-                               return false;
-                       if (!new_constraints.ResolveTypes (ec, Report))
-                               return false;
+                       value = ts.Mutate (this);
+                       mutated_typespec.Add (ts, value);
+                       return value;
+               }
 
-                       if (constraints != null) 
-                               return constraints.AreEqual (new_constraints);
+               public TypeParameterSpec Mutate (TypeParameterSpec tp)
+               {
+                       for (int i = 0; i < mvar.Length; ++i) {
+                               if (mvar[i].Type == tp)
+                                       return var[i].Type;
+                       }
 
-                       constraints = new_constraints;
-                       return true;
+                       return tp;
                }
 
-               public override void Emit ()
+               public TypeSpec[] Mutate (TypeSpec[] targs)
                {
-                       if (OptAttributes != null)
-                               OptAttributes.Emit ();
+                       TypeSpec[] mutated = new TypeSpec[targs.Length];
+                       bool changed = false;
+                       for (int i = 0; i < targs.Length; ++i) {
+                               mutated[i] = Mutate (targs[i]);
+                               changed |= targs[i] != mutated[i];
+                       }
 
-                       base.Emit ();
+                       return changed ? mutated : targs;
                }
+       }
 
-               public override string DocCommentHeader {
-                       get {
-                               throw new InvalidOperationException (
-                                       "Unexpected attempt to get doc comment from " + this.GetType () + ".");
-                       }
+       /// <summary>
+       ///   A TypeExpr which already resolved to a type parameter.
+       /// </summary>
+       public class TypeParameterExpr : TypeExpr {
+               
+               public TypeParameterExpr (TypeParameter type_parameter, Location loc)
+               {
+                       this.type = type_parameter.Type;
+                       this.eclass = ExprClass.TypeParameter;
+                       this.loc = loc;
                }
 
-               //
-               // MemberContainer
-               //
+               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
+               {
+                       throw new NotSupportedException ();
+               }
 
-               public override bool Define ()
+               public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
                {
-                       return true;
+                       return this;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override bool CheckAccessLevel (IMemberContext ds)
                {
-                       type.SetCustomAttribute (cb);
+                       return true;
                }
+       }
 
-               public override AttributeTargets AttributeTargets {
-                       get {
-                               return AttributeTargets.GenericParameter;
-                       }
+       public class InflatedTypeSpec : TypeSpec
+       {
+               TypeSpec[] targs;
+               TypeParameterSpec[] constraints;
+               readonly TypeSpec open_type;
+
+               public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
+                       : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
+               {
+                       if (targs == null)
+                               throw new ArgumentNullException ("targs");
+
+//                     this.state = openType.state;
+                       this.open_type = openType;
+                       this.targs = targs;
                }
 
-               public override string[] ValidAttributeTargets {
+               #region Properties
+
+               public override TypeSpec BaseType {
                        get {
-                               return attribute_target;
+                               if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
+                                       InitializeMemberCache (true);
+
+                               return base.BaseType;
                        }
                }
 
                //
-               // IMemberContainer
+               // Inflated type parameters with constraints array, mapping with type arguments is based on index
                //
-
-               string IMemberContainer.Name {
-                       get { return Name; }
-               }
-
-               MemberCache IMemberContainer.BaseCache {
+               public TypeParameterSpec[] Constraints {
                        get {
-                               if (gc == null)
-                                       return null;
-
-                               if (gc.EffectiveBaseClass.BaseType == null)
-                                       return null;
+                               if (constraints == null) {
+                                       var inflator = new TypeParameterInflator (this, MemberDefinition.TypeParameters, targs);
+                                       constraints = TypeParameterSpec.InflateConstraints (inflator, MemberDefinition.TypeParameters);
+                               }
 
-                               return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
+                               return constraints;
                        }
                }
 
-               bool IMemberContainer.IsInterface {
-                       get { return false; }
-               }
+               public override IList<TypeSpec> Interfaces {
+                       get {
+                               if (cache == null)
+                                       InitializeMemberCache (true);
 
-               MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
+                               return base.Interfaces;
+                       }
                }
 
-               public MemberCache MemberCache {
+               //
+               // Types used to inflate the generic  type
+               //
+               public override TypeSpec[] TypeArguments {
                        get {
-                               if (member_cache != null)
-                                       return member_cache;
-
-                               if (gc == null)
-                                       return null;
-
-                               Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
-                               member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
-
-                               return member_cache;
+                               return targs;
                        }
                }
 
-               public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                              MemberFilter filter, object criteria)
-               {
-                       if (gc == null)
-                               return MemberList.Empty;
-
-                       var members = new List<MemberInfo> ();
-
-                       if (gc.HasClassConstraint) {
-                               MemberList list = TypeManager.FindMembers (
-                                       gc.ClassConstraint, mt, bf, filter, criteria);
+               #endregion
 
-                               members.AddRange (list);
-                       }
+               Type CreateMetaInfo (TypeParameterMutator mutator)
+               {
+                       //
+                       // Converts nested type arguments into right order
+                       // Foo<string, bool>.Bar<int> => string, bool, int
+                       //
+                       var all = new List<Type> ();
+                       TypeSpec type = this;
+                       TypeSpec definition = type;
+                       do {
+                               if (type.GetDefinition().IsGeneric) {
+                                       all.InsertRange (0,
+                                               type.TypeArguments != TypeSpec.EmptyTypes ?
+                                               type.TypeArguments.Select (l => l.GetMetaInfo ()) :
+                                               type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
+                               }
 
-                       Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
-                       foreach (Type t in ifaces) {
-                               MemberList list = TypeManager.FindMembers (
-                                       t, mt, bf, filter, criteria);
+                               definition = definition.GetDefinition ();
+                               type = type.DeclaringType;
+                       } while (type != null);
 
-                               members.AddRange (list);
-                       }
+                       return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
+               }
 
-                       return new MemberList (members);
+               public override ObsoleteAttribute GetAttributeObsolete ()
+               {
+                       return open_type.GetAttributeObsolete ();
                }
 
-               public bool IsSubclassOf (Type t)
+               protected override bool IsNotCLSCompliant ()
                {
-                       if (type.Equals (t))
+                       if (base.IsNotCLSCompliant ())
                                return true;
 
-                       if (constraints != null)
-                               return constraints.IsSubclassOf (t);
+                       foreach (var ta in TypeArguments) {
+                               if (ta.MemberDefinition.IsNotCLSCompliant ())
+                                       return true;
+                       }
 
                        return false;
                }
 
-               public void InflateConstraints (Type declaring)
+               public override TypeSpec GetDefinition ()
                {
-                       if (constraints != null)
-                               gc = new InflatedConstraints (constraints, declaring);
+                       return open_type;
                }
-               
-               public override bool IsClsComplianceRequired ()
+
+               public override Type GetMetaInfo ()
                {
-                       return false;
+                       if (info == null)
+                               info = CreateMetaInfo (null);
+
+                       return info;
                }
 
-               protected class InflatedConstraints : GenericConstraints
+               public override string GetSignatureForError ()
                {
-                       GenericConstraints gc;
-                       Type base_type;
-                       Type class_constraint;
-                       Type[] iface_constraints;
-                       Type[] dargs;
+                       if (TypeManager.IsNullableType (open_type))
+                               return targs[0].GetSignatureForError () + "?";
 
-                       public InflatedConstraints (GenericConstraints gc, Type declaring)
-                               : this (gc, TypeManager.GetTypeArguments (declaring))
-                       { }
+                       return base.GetSignatureForError ();
+               }
 
-                       public InflatedConstraints (GenericConstraints gc, Type[] dargs)
-                       {
-                               this.gc = gc;
-                               this.dargs = dargs;
+               protected override string GetTypeNameSignature ()
+               {
+                       if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
+                               return null;
 
-                               var list = new List<Type> ();
-                               if (gc.HasClassConstraint)
-                                       list.Add (inflate (gc.ClassConstraint));
-                               foreach (Type iface in gc.InterfaceConstraints)
-                                       list.Add (inflate (iface));
+                       return "<" + TypeManager.CSharpName (targs) + ">";
+               }
 
-                               bool has_class_constr = false;
-                               if (list.Count > 0) {
-                                       Type first = (Type) list [0];
-                                       has_class_constr = !first.IsGenericParameter && !first.IsInterface;
-                               }
+               protected override void InitializeMemberCache (bool onlyTypes)
+               {
+                       if (cache == null)
+                               cache = new MemberCache (onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache);
 
-                               if ((list.Count > 0) && has_class_constr) {
-                                       class_constraint = (Type) list [0];
-                                       iface_constraints = new Type [list.Count - 1];
-                                       list.CopyTo (1, iface_constraints, 0, list.Count - 1);
+                       TypeParameterSpec[] tparams_full;
+                       TypeSpec[] targs_full = targs;
+                       if (IsNested) {
+                               //
+                               // Special case is needed when we are inflating an open type (nested type definition)
+                               // on inflated parent. Consider following case
+                               //
+                               // Foo<T>.Bar<U> => Foo<string>.Bar<U>
+                               //
+                               // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
+                               //
+                               List<TypeSpec> merged_targs = null;
+                               List<TypeParameterSpec> merged_tparams = null;
+
+                               var type = DeclaringType;
+
+                               do {
+                                       if (type.TypeArguments.Length > 0) {
+                                               if (merged_targs == null) {
+                                                       merged_targs = new List<TypeSpec> ();
+                                                       merged_tparams = new List<TypeParameterSpec> ();
+                                                       if (targs.Length > 0) {
+                                                               merged_targs.AddRange (targs);
+                                                               merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
+                                                       }
+                                               }
+                                               merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
+                                               merged_targs.AddRange (type.TypeArguments);
+                                       }
+                                       type = type.DeclaringType;
+                               } while (type != null);
+
+                               if (merged_targs != null) {
+                                       // Type arguments are not in the right order but it should not matter in this case
+                                       targs_full = merged_targs.ToArray ();
+                                       tparams_full = merged_tparams.ToArray ();
+                               } else if (targs.Length == 0) {
+                                       tparams_full = TypeParameterSpec.EmptyTypes;
                                } else {
-                                       iface_constraints = new Type [list.Count];
-                                       list.CopyTo (iface_constraints, 0);
+                                       tparams_full = open_type.MemberDefinition.TypeParameters;
                                }
-
-                               if (HasValueTypeConstraint)
-                                       base_type = TypeManager.value_type;
-                               else if (class_constraint != null)
-                                       base_type = class_constraint;
-                               else
-                                       base_type = TypeManager.object_type;
+                       } else if (targs.Length == 0) {
+                               tparams_full = TypeParameterSpec.EmptyTypes;
+                       } else {
+                               tparams_full = open_type.MemberDefinition.TypeParameters;
                        }
 
-                       Type inflate (Type t)
-                       {
-                               if (t == null)
-                                       return null;
-                               if (t.IsGenericParameter)
-                                       return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
-                               if (t.IsGenericType) {
-                                       Type[] args = t.GetGenericArguments ();
-                                       Type[] inflated = new Type [args.Length];
+                       var inflator = new TypeParameterInflator (this, tparams_full, targs_full);
+
+                       //
+                       // Two stage inflate due to possible nested types recursive
+                       // references
+                       //
+                       // class A<T> {
+                       //    B b;
+                       //    class B {
+                       //      T Value;
+                       //    }
+                       // }
+                       //
+                       // When resolving type of `b' members of `B' cannot be 
+                       // inflated because are not yet available in membercache
+                       //
+                       if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
+                               open_type.MemberCacheTypes.InflateTypes (cache, inflator);
 
-                                       for (int i = 0; i < args.Length; i++)
-                                               inflated [i] = inflate (args [i]);
+                               //
+                               // Inflate any implemented interfaces
+                               //
+                               if (open_type.Interfaces != null) {
+                                       ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
+                                       foreach (var iface in open_type.Interfaces) {
+                                               var iface_inflated = inflator.Inflate (iface);
+                                               AddInterface (iface_inflated);
+                                       }
+                               }
 
-                                       t = t.GetGenericTypeDefinition ();
-                                       t = t.MakeGenericType (inflated);
+                               //
+                               // Handles the tricky case of recursive nested base generic type
+                               //
+                               // class A<T> : Base<A<T>.Nested> {
+                               //    class Nested {}
+                               // }
+                               //
+                               // When inflating A<T>. base type is not yet known, secondary
+                               // inflation is required (not common case) once base scope
+                               // is known
+                               //
+                               if (open_type.BaseType == null) {
+                                       if (IsClass)
+                                               state |= StateFlags.PendingBaseTypeInflate;
+                               } else {
+                                       BaseType = inflator.Inflate (open_type.BaseType);
                                }
-
-                               return t;
-                       }
-
-                       public override string TypeParameter {
-                               get { return gc.TypeParameter; }
+                       } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
+                               BaseType = inflator.Inflate (open_type.BaseType);
+                               state &= ~StateFlags.PendingBaseTypeInflate;
                        }
 
-                       public override GenericParameterAttributes Attributes {
-                               get { return gc.Attributes; }
+                       if (onlyTypes) {
+                               state |= StateFlags.PendingMemberCacheMembers;
+                               return;
                        }
 
-                       public override Type ClassConstraint {
-                               get { return class_constraint; }
-                       }
+                       var tc = open_type.MemberDefinition as TypeContainer;
+                       if (tc != null && !tc.HasMembersDefined)
+                               throw new InternalErrorException ("Inflating MemberCache with undefined members");
 
-                       public override Type EffectiveBaseClass {
-                               get { return base_type; }
+                       if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
+                               BaseType = inflator.Inflate (open_type.BaseType);
+                               state &= ~StateFlags.PendingBaseTypeInflate;
                        }
 
-                       public override Type[] InterfaceConstraints {
-                               get { return iface_constraints; }
-                       }
+                       state &= ~StateFlags.PendingMemberCacheMembers;
+                       open_type.MemberCache.InflateMembers (cache, open_type, inflator);
                }
-       }
 
-       /// <summary>
-       ///   A TypeExpr which already resolved to a type parameter.
-       /// </summary>
-       public class TypeParameterExpr : TypeExpr {
-               
-               public TypeParameterExpr (TypeParameter type_parameter, Location loc)
+               public override TypeSpec Mutate (TypeParameterMutator mutator)
                {
-                       this.type = type_parameter.Type;
-                       this.eclass = ExprClass.TypeParameter;
-                       this.loc = loc;
-               }
+                       var targs = TypeArguments;
+                       if (targs != null)
+                               targs = mutator.Mutate (targs);
 
-               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
-               {
-                       throw new NotSupportedException ();
-               }
+                       var decl = DeclaringType;
+                       if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
+                               decl = mutator.Mutate (decl);
 
-               public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
-               {
-                       return this;
-               }
+                       if (targs == TypeArguments && decl == DeclaringType)
+                               return this;
 
-               public override bool IsInterface {
-                       get { return false; }
-               }
+                       var mutated = (InflatedTypeSpec) MemberwiseClone ();
+                       if (decl != DeclaringType) {
+                               // Gets back MethodInfo in case of metaInfo was inflated
+                               //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
 
-               public override bool CheckAccessLevel (IMemberContext ds)
-               {
-                       return true;
+                               mutated.declaringType = decl;
+                               mutated.state |= StateFlags.PendingMetaInflate;
+                       }
+
+                       if (targs != null) {
+                               mutated.targs = targs;
+                               mutated.info = null;
+                       }
+
+                       return mutated;
                }
        }
 
+
        //
        // Tracks the type arguments when instantiating a generic type. It's used
        // by both type arguments and type parameters
        //
-       public class TypeArguments {
+       public class TypeArguments
+       {
                List<FullNamedExpression> args;
-               Type[] atypes;
-               
-               public TypeArguments ()
-               {
-                       args = new List<FullNamedExpression> ();
-               }
+               TypeSpec[] atypes;
 
                public TypeArguments (params FullNamedExpression[] types)
                {
@@ -1214,11 +1560,6 @@ namespace Mono.CSharp {
                        args.Add (type);
                }
 
-               public void Add (TypeArguments new_args)
-               {
-                       args.AddRange (new_args.args);
-               }
-
                // TODO: Kill this monster
                public TypeParameterName[] GetDeclarations ()
                {
@@ -1229,7 +1570,8 @@ namespace Mono.CSharp {
                ///   We may only be used after Resolve() is called and return the fully
                ///   resolved types.
                /// </summary>
-               public Type[] Arguments {
+               // TODO: Not needed, just return type from resolve
+               public TypeSpec[] Arguments {
                        get {
                                return atypes;
                        }
@@ -1241,34 +1583,42 @@ namespace Mono.CSharp {
                        }
                }
 
+               public virtual bool IsEmpty {
+                       get {
+                               return false;
+                       }
+               }
+
                public string GetSignatureForError()
                {
-                       StringBuilder sb = new StringBuilder();
-                       for (int i = 0; i < Count; ++i)
-                       {
-                               Expression expr = (Expression)args [i];
-                               sb.Append(expr.GetSignatureForError());
+                       StringBuilder sb = new StringBuilder ();
+                       for (int i = 0; i < Count; ++i) {
+                               var expr = args[i];
+                               if (expr != null)
+                                       sb.Append (expr.GetSignatureForError ());
+
                                if (i + 1 < Count)
-                                       sb.Append(',');
+                                       sb.Append (',');
                        }
-                       return sb.ToString();
+
+                       return sb.ToString ();
                }
 
                /// <summary>
                ///   Resolve the type arguments.
                /// </summary>
-               public bool Resolve (IMemberContext ec)
+               public virtual bool Resolve (IMemberContext ec)
                {
                        if (atypes != null)
-                               return atypes.Length != 0;
+                           return atypes.Length != 0;
 
                        int count = args.Count;
                        bool ok = true;
 
-                       atypes = new Type [count];
+                       atypes = new TypeSpec [count];
 
                        for (int i = 0; i < count; i++){
-                               TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
+                               TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
                                if (te == null) {
                                        ok = false;
                                        continue;
@@ -1276,7 +1626,7 @@ namespace Mono.CSharp {
 
                                atypes[i] = te.Type;
 
-                               if (te.Type.IsSealed && te.Type.IsAbstract) {
+                               if (te.Type.IsStatic) {
                                        ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
                                                te.GetSignatureForError ());
                                        ok = false;
@@ -1291,7 +1641,7 @@ namespace Mono.CSharp {
                        }
 
                        if (!ok)
-                               atypes = Type.EmptyTypes;
+                               atypes = TypeSpec.EmptyTypes;
 
                        return ok;
                }
@@ -1306,6 +1656,26 @@ namespace Mono.CSharp {
                }
        }
 
+       public class UnboundTypeArguments : TypeArguments
+       {
+               public UnboundTypeArguments (int arity)
+                       : base (new FullNamedExpression[arity])
+               {
+               }
+
+               public override bool IsEmpty {
+                       get {
+                               return true;
+                       }
+               }
+
+               public override bool Resolve (IMemberContext ec)
+               {
+                       // Nothing to be resolved
+                       return true;
+               }
+       }
+
        public class TypeParameterName : SimpleName
        {
                Attributes attributes;
@@ -1336,41 +1706,23 @@ namespace Mono.CSharp {
                }
        }
 
-       /// <summary>
-       ///   A reference expression to generic type
-       /// </summary>  
+       //
+       // A type expression of generic type with type arguments
+       //
        class GenericTypeExpr : TypeExpr
        {
                TypeArguments args;
-               Type[] gen_params;      // TODO: Waiting for constrains check cleanup
-               Type open_type;
-
-               //
-               // Should be carefully used only with defined generic containers. Type parameters
-               // can be used as type arguments in this case.
-               //
-               // TODO: This could be GenericTypeExpr specialization
-               //
-               public GenericTypeExpr (DeclSpace gType, Location l)
-               {
-                       open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
-
-                       args = new TypeArguments ();
-                       foreach (TypeParameter type_param in gType.TypeParameters)
-                               args.Add (new TypeParameterExpr (type_param, l));
-
-                       this.loc = l;
-               }
+               TypeSpec open_type;
+               bool constraints_checked;
 
                /// <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 GenericTypeExpr (Type t, TypeArguments args, Location l)
+               public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
                {
-                       open_type = t.GetGenericTypeDefinition ();
-
+                       this.open_type = open_type;
                        loc = l;
                        this.args = args;
                }
@@ -1386,38 +1738,51 @@ namespace Mono.CSharp {
 
                protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
                {
-                       eclass = ExprClass.Type;
-
                        if (!args.Resolve (ec))
                                return null;
 
-                       gen_params = open_type.GetGenericArguments ();
-                       Type[] atypes = args.Arguments;
-                       
-                       if (atypes.Length != gen_params.Length) {
-                               Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, open_type, loc);
-                               return null;
-                       }
+                       TypeSpec[] atypes = args.Arguments;
 
                        //
                        // Now bind the parameters
                        //
                        type = open_type.MakeGenericType (atypes);
+
+                       //
+                       // Check constraints when context is not method/base type
+                       //
+                       if (!ec.HasUnresolvedConstraints)
+                               CheckConstraints (ec);
+
                        return this;
                }
 
-               /// <summary>
-               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
-               ///   after fully resolving the constructed type.
-               /// </summary>
+               //
+               // Checks the constraints of open generic type against type
+               // arguments. Has to be called after all members have been defined
+               //
                public bool CheckConstraints (IMemberContext ec)
                {
-                       return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
+                       if (constraints_checked)
+                               return true;
+
+                       constraints_checked = true;
+
+                       var gtype = (InflatedTypeSpec) type;
+                       var constraints = gtype.Constraints;
+                       if (constraints == null)
+                               return true;
+
+                       return new ConstraintChecker(ec).CheckAll (open_type, args.Arguments, constraints, loc);
                }
        
                public override bool CheckAccessLevel (IMemberContext mc)
                {
-                       return mc.CurrentTypeDefinition.CheckAccessLevel (open_type);
+                       DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
+                       if (c == null)
+                               c = mc.CurrentMemberDefinition.Parent;
+
+                       return c.CheckAccessLevel (open_type);
                }
 
                public bool HasDynamicArguments ()
@@ -1425,34 +1790,28 @@ namespace Mono.CSharp {
                        return HasDynamicArguments (args.Arguments);
                }
 
-               static bool HasDynamicArguments (Type[] args)
+               static bool HasDynamicArguments (TypeSpec[] args)
                {
-                       foreach (var item in args)
-                       {
-                               if (TypeManager.IsGenericType (item))
-                                       return HasDynamicArguments (TypeManager.GetTypeArguments (item));
+                       for (int i = 0; i < args.Length; ++i) {
+                               var item = args[i];
 
-                               if (TypeManager.IsDynamicType (item))
+                               if (item == InternalType.Dynamic)
                                        return true;
-                       }
-
-                       return false;
-               }
 
-               public override bool IsClass {
-                       get { return open_type.IsClass; }
-               }
+                               if (TypeManager.IsGenericType (item))
+                                       return HasDynamicArguments (TypeManager.GetTypeArguments (item));
 
-               public override bool IsValueType {
-                       get { return TypeManager.IsStruct (open_type); }
-               }
+                               if (item.IsArray) {
+                                       while (item.IsArray) {
+                                               item = ((ArrayContainer) item).Element;
+                                       }
 
-               public override bool IsInterface {
-                       get { return open_type.IsInterface; }
-               }
+                                       if (item == InternalType.Dynamic)
+                                               return true;
+                               }
+                       }
 
-               public override bool IsSealed {
-                       get { return open_type.IsSealed; }
+                       return false;
                }
 
                public override bool Equals (object obj)
@@ -1473,333 +1832,252 @@ namespace Mono.CSharp {
                }
        }
 
-       public abstract class ConstraintChecker
+       //
+       // Generic type with unbound type arguments, used for typeof (G<,,>)
+       //
+       class GenericOpenTypeExpr : TypeExpr
        {
-               protected readonly Type[] gen_params;
-               protected readonly Type[] atypes;
-               protected readonly Location loc;
-               protected Report Report;
-
-               protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
+               public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
                {
-                       this.gen_params = gen_params;
-                       this.atypes = atypes;
+                       this.type = type.GetDefinition ();
                        this.loc = loc;
-                       this.Report = r;
                }
 
-               /// <summary>
-               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
-               ///   after fully resolving the constructed type.
-               /// </summary>
-               public bool CheckConstraints (IMemberContext ec)
+               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
                {
-                       for (int i = 0; i < gen_params.Length; i++) {
-                               if (!CheckConstraints (ec, i))
-                                       return false;
-                       }
-
-                       return true;
+                       return this;
                }
+       }
 
-               protected bool CheckConstraints (IMemberContext ec, int index)
+       struct ConstraintChecker
+       {
+               IMemberContext mc;
+               bool ignore_inferred_dynamic;
+
+               public ConstraintChecker (IMemberContext ctx)
                {
-                       Type atype = TypeManager.TypeToCoreType (atypes [index]);
-                       Type ptype = gen_params [index];
+                       this.mc = ctx;
+                       ignore_inferred_dynamic = false;
+               }
 
-                       if (atype == ptype)
-                               return true;
+               #region Properties
 
-                       Expression aexpr = new EmptyExpression (atype);
+               public bool IgnoreInferredDynamic {
+                       get {
+                               return ignore_inferred_dynamic;
+                       }
+                       set {
+                               ignore_inferred_dynamic = value;
+                       }
+               }
 
-                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
-                       if (gc == null)
-                               return true;
+               #endregion
 
-                       bool is_class, is_struct;
-                       if (atype.IsGenericParameter) {
-                               GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
-                               if (agc != null) {
-                                       if (agc is Constraints) {
-                                               // FIXME: No constraints can be resolved here, we are in
-                                               // completely wrong/different context. This path is hit
-                                               // when resolving base type of unresolved generic type
-                                               // with constraints. We are waiting with CheckConsttraints
-                                               // after type-definition but not in this case
-                                               if (!((Constraints) agc).Resolve (null, null, Report))
-                                                       return true;
-                                       }
-                                       is_class = agc.IsReferenceType;
-                                       is_struct = agc.IsValueType;
-                               } else {
-                                       is_class = is_struct = false;
-                               }
-                       } else {
-                               is_class = TypeManager.IsReferenceType (atype);
-                               is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
+               //
+               // Checks all type arguments againts type parameters constraints
+               // NOTE: It can run in probing mode when `mc' is null
+               //
+               public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
+               {
+                       for (int i = 0; i < tparams.Length; i++) {
+                               if (ignore_inferred_dynamic && targs[i] == InternalType.Dynamic)
+                                       continue;
+
+                               if (!CheckConstraint (context, targs [i], tparams [i], loc))
+                                       return false;
                        }
 
+                       return true;
+               }
+
+               bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
+               {
                        //
                        // First, check the `class' and `struct' constraints.
                        //
-                       if (gc.HasReferenceTypeConstraint && !is_class) {
-                               Report.Error (452, loc, "The type `{0}' must be " +
-                                             "a reference type in order to use it " +
-                                             "as type parameter `{1}' in the " +
-                                             "generic type or method `{2}'.",
-                                             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 " +
-                                             "non-nullable value type in order to use it " +
-                                             "as type parameter `{1}' in the " +
-                                             "generic type or method `{2}'.",
-                                             TypeManager.CSharpName (atype),
-                                             TypeManager.CSharpName (ptype),
-                                             GetSignatureForError ());
+                       if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
+                               if (mc != null) {
+                                       mc.Compiler.Report.Error (452, loc,
+                                               "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
+                                               TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
+                               }
+
                                return false;
                        }
 
-                       //
-                       // The class constraint comes next.
-                       //
-                       if (gc.HasClassConstraint) {
-                               if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
-                                       return false;
+                       if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
+                               if (mc != null) {
+                                       mc.Compiler.Report.Error (453, loc,
+                                               "The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
+                                               TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
+                               }
+
+                               return false;
                        }
 
+                       bool ok = true;
+
                        //
-                       // Now, check the interface constraints.
+                       // Check the class constraint
                        //
-                       if (gc.InterfaceConstraints != null) {
-                               foreach (Type it in gc.InterfaceConstraints) {
-                                       if (!CheckConstraint (ec, ptype, aexpr, it))
+                       if (tparam.HasTypeConstraint) {
+                               if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
+                                       if (mc == null)
                                                return false;
+
+                                       ok = false;
                                }
                        }
 
                        //
-                       // Finally, check the constructor constraint.
+                       // Check the interfaces constraints
                        //
+                       if (tparam.Interfaces != null) {
+                               if (TypeManager.IsNullableType (atype)) {
+                                       if (mc == null)
+                                               return false;
 
-                       if (!gc.HasConstructorConstraint)
-                               return true;
-
-                       if (TypeManager.IsValueType (atype))
-                               return true;
-
-                       if (HasDefaultConstructor (atype))
-                               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;
-               }
-               
-               Type InflateType(IMemberContext ec, Type ctype)
-               {
-                       Type[] types = TypeManager.GetTypeArguments (ctype);
-
-                       TypeArguments new_args = new TypeArguments ();
-
-                       for (int i = 0; i < types.Length; i++) {
-                               Type t = TypeManager.TypeToCoreType (types [i]);
+                                       mc.Compiler.Report.Error (313, loc,
+                                               "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
+                                       ok = false;
+                               } else {
+                                       foreach (TypeSpec iface in tparam.Interfaces) {
+                                               if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
+                                                       if (mc == null)
+                                                               return false;
 
-                               if (t.IsGenericParameter) {
-                                       int pos = t.GenericParameterPosition;
-                                       if (t.DeclaringMethod == null && this is MethodConstraintChecker) {
-                                               Type parent = ((MethodConstraintChecker) this).declaring_type;
-                                               t = parent.GetGenericArguments ()[pos];
-                                       } else {
-                                               t = atypes [pos];
-                                       }
-                               } else if(TypeManager.HasGenericArguments(t)) {
-                                       t = InflateType (ec, t);
-                                       if (t == null) {
-                                               return null;
+                                                       ok = false;
+                                               }
                                        }
                                }
-                               new_args.Add (new TypeExpression (t, loc));
                        }
 
-                       TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
-                       if (ct.ResolveAsTypeStep (ec, false) == null)
-                               return null;
-                       
-                       return ct.Type;
-               }
-
-               protected bool CheckConstraint (IMemberContext ec, Type ptype, Expression expr,
-                                               Type ctype)
-               {
                        //
-                       // All this is needed because we don't have
-                       // real inflated type hierarchy
+                       // Check the type parameter constraint
                        //
-                       if (TypeManager.HasGenericArguments (ctype)) {
-                               ctype = InflateType (ec, ctype);
-                               if(ctype == null) {
-                                       return false;
-                               }
-                       } else if (ctype.IsGenericParameter) {
-                               int pos = ctype.GenericParameterPosition;
-                               if (ctype.DeclaringMethod == null) {
-                                       // FIXME: Implement
-                                       return true;
-                               } else {                                
-                                       ctype = atypes [pos];
+                       if (tparam.TypeArguments != null) {
+                               foreach (var ta in tparam.TypeArguments) {
+                                       if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
+                                               if (mc == null)
+                                                       return false;
+
+                                               ok = false;
+                                       }
                                }
                        }
 
-                       if (Convert.ImplicitStandardConversionExists (expr, ctype))
-                               return true;
-
-                       Report_SymbolRelatedToPreviousError ();
-                       Report.SymbolRelatedToPreviousError (expr.Type);
+                       //
+                       // Finally, check the constructor constraint.
+                       //
+                       if (!tparam.HasSpecialConstructor)
+                               return ok;
 
-                       if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
-                               Report.Error (313, loc,
-                                       "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
-                                       "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
-                                       TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
-                                       GetSignatureForError (), TypeManager.CSharpName (ctype));
-                       } else {
-                               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 (expr.Type), TypeManager.CSharpName (ctype),
-                                       TypeManager.CSharpName (ptype), GetSignatureForError ());
+                       if (!HasDefaultConstructor (atype)) {
+                               if (mc != null) {
+                                       mc.Compiler.Report.SymbolRelatedToPreviousError (atype);
+                                       mc.Compiler.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), tparam.GetSignatureForError (), context.GetSignatureForError ());
+                               }
+                               return false;
                        }
-                       return false;
+
+                       return ok;
                }
 
-               static bool HasDefaultConstructor (Type atype)
+               static bool HasDynamicTypeArgument (TypeSpec[] targs)
                {
-                       TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
-                       if (tparam != null) {
-                               if (tparam.GenericConstraints == null)
-                                       return false;
-                                               
-                               return tparam.GenericConstraints.HasConstructorConstraint || 
-                                       tparam.GenericConstraints.HasValueTypeConstraint;
-                       }
-               
-                       if (atype.IsAbstract)
-                               return false;
-
-               again:
-                       atype = TypeManager.DropGenericTypeArguments (atype);
-                       if (atype is TypeBuilder) {
-                               TypeContainer tc = TypeManager.LookupTypeContainer (atype);
-                               if (tc.InstanceConstructors == null) {
-                                       atype = atype.BaseType;
-                                       goto again;
-                               }
-
-                               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;
-
+                       for (int i = 0; i < targs.Length; ++i) {
+                               var targ = targs [i];
+                               if (targ == InternalType.Dynamic)
                                        return true;
-                               }
-                       }
 
-                       MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                               ConstructorInfo.ConstructorName, null);
-
-                       if (list == null)
-                               return false;
-
-                       foreach (MethodBase mb in list) {
-                               AParametersCollection pd = TypeManager.GetParameterData (mb);
-                               if (pd.Count == 0)
+                               if (HasDynamicTypeArgument (targ.TypeArguments))
                                        return true;
                        }
 
                        return false;
                }
 
-               protected abstract string GetSignatureForError ();
-               protected abstract void Report_SymbolRelatedToPreviousError ();
-
-               public static bool CheckConstraints (IMemberContext ec, MethodBase definition,
-                                                    MethodBase instantiated, Location loc)
+               bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
                {
-                       MethodConstraintChecker checker = new MethodConstraintChecker (
-                               definition, instantiated.DeclaringType, definition.GetGenericArguments (),
-                               instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
+                       var expr = new EmptyExpression (atype);
+                       if (Convert.ImplicitStandardConversionExists (expr, ttype))
+                               return true;
 
-                       return checker.CheckConstraints (ec);
-               }
+                       //
+                       // When partial/full type inference finds a dynamic type argument delay
+                       // the constraint check to runtime, it can succeed for real underlying
+                       // dynamic type
+                       //
+                       if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
+                               return true;
 
-               public static bool CheckConstraints (IMemberContext ec, Type gt, Type[] gen_params,
-                                                    Type[] atypes, Location loc)
-               {
-                       TypeConstraintChecker checker = new TypeConstraintChecker (
-                               gt, gen_params, atypes, loc, ec.Compiler.Report);
+                       if (mc != null) {
+                               mc.Compiler.Report.SymbolRelatedToPreviousError (tparam);
+                               if (TypeManager.IsValueType (atype)) {
+                                       mc.Compiler.Report.Error (315, loc,
+                                               "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+                               } else if (atype.IsGenericParameter) {
+                                       mc.Compiler.Report.Error (314, loc,
+                                               "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+                               } else {
+                                       mc.Compiler.Report.Error (311, loc,
+                                               "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+                               }
+                       }
 
-                       return checker.CheckConstraints (ec);
+                       return false;
                }
 
-               protected class MethodConstraintChecker : ConstraintChecker
+               bool HasDefaultConstructor (TypeSpec atype)
                {
-                       MethodBase definition;
-                       public Type declaring_type;
-
-                       public MethodConstraintChecker (MethodBase definition, Type declaringType, Type[] gen_params,
-                                                       Type[] atypes, Location loc, Report r)
-                               : base (gen_params, atypes, loc, r)
-                       {
-                               this.declaring_type = declaringType;
-                               this.definition = definition;
+                       var tp = atype as TypeParameterSpec;
+                       if (tp != null) {
+                               return tp.HasSpecialConstructor || tp.HasSpecialStruct;
                        }
 
-                       protected override string GetSignatureForError ()
-                       {
-                               return TypeManager.CSharpSignature (definition);
-                       }
+                       if (atype.IsStruct || atype.IsEnum)
+                               return true;
 
-                       protected override void Report_SymbolRelatedToPreviousError ()
-                       {
-                               Report.SymbolRelatedToPreviousError (definition);
-                       }
-               }
+                       if (atype.IsAbstract)
+                               return false;
 
-               protected class TypeConstraintChecker : ConstraintChecker
-               {
-                       Type gt;
+                       var tdef = atype.GetDefinition ();
+
+                       //
+                       // In some circumstances MemberCache is not yet populated and members
+                       // cannot be defined yet (recursive type new constraints)
+                       //
+                       // class A<T> where T : B<T>, new () {}
+                       // class B<T> where T : A<T>, new () {}
+                       //
+                       var tc = tdef.MemberDefinition as Class;
+                       if (tc != null) {
+                               if (tc.InstanceConstructors == null) {
+                                       // Default ctor will be generated later
+                                       return true;
+                               }
+
+                               foreach (var c in tc.InstanceConstructors) {
+                                       if (c.ParameterInfo.IsEmpty) {
+                                               if ((c.ModFlags & Modifiers.PUBLIC) != 0)
+                                                       return true;
+                                       }
+                               }
 
-                       public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
-                                                     Location loc, Report r)
-                               : base (gen_params, atypes, loc, r)
-                       {
-                               this.gt = gt;
+                               return false;
                        }
 
-                       protected override string GetSignatureForError ()
-                       {
-                               return TypeManager.CSharpName (gt);
-                       }
+                       var found = MemberCache.FindMember (tdef,
+                               MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
+                               BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
 
-                       protected override void Report_SymbolRelatedToPreviousError ()
-                       {
-                               Report.SymbolRelatedToPreviousError (gt);
-                       }
+                       return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
                }
        }
 
@@ -1808,21 +2086,20 @@ namespace Mono.CSharp {
        /// </summary>
        public class GenericMethod : DeclSpace
        {
-               FullNamedExpression return_type;
                ParametersCompiled parameters;
 
                public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
                                      FullNamedExpression return_type, ParametersCompiled parameters)
                        : base (ns, parent, name, null)
                {
-                       this.return_type = return_type;
                        this.parameters = parameters;
                }
 
-               public override TypeContainer CurrentTypeDefinition {
-                       get {
-                               return Parent.CurrentTypeDefinition;
-                       }
+               public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
+                                         FullNamedExpression return_type, ParametersCompiled parameters)
+                       : this (ns, parent, name, return_type, parameters)
+               {
+                       this.type_params = tparams;
                }
 
                public override TypeParameter[] CurrentTypeParameters {
@@ -1836,13 +2113,14 @@ namespace Mono.CSharp {
                        throw new Exception ();
                }
 
-               public override bool Define ()
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
-                       for (int i = 0; i < TypeParameters.Length; i++)
-                               if (!TypeParameters [i].Resolve (this))
-                                       return false;
+                       throw new NotSupportedException ();
+               }
 
-                       return true;
+               public override bool Define ()
+               {
+                       throw new NotSupportedException ();
                }
 
                /// <summary>
@@ -1853,81 +2131,47 @@ namespace Mono.CSharp {
                {
                        TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
                        string[] snames = new string [names.Length];
+                       var block = m.Block;
                        for (int i = 0; i < names.Length; i++) {
                                string type_argument_name = names[i].Name;
-                               int idx = parameters.GetParameterIndexByName (type_argument_name);
-                               if (idx >= 0) {
-                                       Block b = m.Block;
-                                       if (b == null)
-                                               b = new Block (null);
 
-                                       b.Error_AlreadyDeclaredTypeParameter (Report, parameters [i].Location,
-                                               type_argument_name, "method parameter");
+                               if (block == null) {
+                                       int idx = parameters.GetParameterIndexByName (type_argument_name);
+                                       if (idx >= 0) {
+                                               var b = m.Block;
+                                               if (b == null)
+                                                       b = new ToplevelBlock (Compiler, Location);
+
+                                               b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
+                                       }
+                               } else {
+                                       INamedBlockVariable variable = null;
+                                       block.GetLocalName (type_argument_name, m.Block, ref variable);
+                                       if (variable != null)
+                                               variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
                                }
-                               
+
                                snames[i] = type_argument_name;
                        }
 
                        GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
                        for (int i = 0; i < TypeParameters.Length; i++)
-                               TypeParameters [i].Define (gen_params [i]);
-
-                       if (!Define ())
-                               return false;
-
-                       for (int i = 0; i < TypeParameters.Length; i++) {
-                               if (!TypeParameters [i].ResolveType (this))
-                                       return false;
-                       }
+                               TypeParameters [i].Define (gen_params [i], null);
 
                        return true;
                }
 
-               /// <summary>
-               ///   We're called from MethodData.Define() after creating the MethodBuilder.
-               /// </summary>
-               public bool DefineType (IMemberContext ec, MethodBuilder mb,
-                                       MethodInfo implementing, bool is_override)
-               {
-                       for (int i = 0; i < TypeParameters.Length; i++)
-                               if (!TypeParameters [i].DefineType (
-                                           ec, mb, implementing, is_override))
-                                       return false;
-
-                       bool ok = parameters.Resolve (ec);
-
-                       if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
-                               ok = false;
-
-                       return ok;
-               }
-
                public void EmitAttributes ()
                {
-                       for (int i = 0; i < TypeParameters.Length; i++)
-                               TypeParameters [i].Emit ();
-
                        if (OptAttributes != null)
                                OptAttributes.Emit ();
                }
 
-               public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                                       MemberFilter filter, object criteria)
-               {
-                       throw new Exception ();
-               }
-
                public override string GetSignatureForError ()
                {
                        return base.GetSignatureForError () + parameters.GetSignatureForError ();
                }
 
-               public override MemberCache MemberCache {
-                       get {
-                               return null;
-                       }
-               }
-
                public override AttributeTargets AttributeTargets {
                        get {
                                return AttributeTargets.Method | AttributeTargets.ReturnValue;
@@ -1941,56 +2185,32 @@ namespace Mono.CSharp {
                public new void VerifyClsCompliance ()
                {
                        foreach (TypeParameter tp in TypeParameters) {
-                               if (tp.Constraints == null)
-                                       continue;
-
-                               tp.Constraints.VerifyClsCompliance (Report);
+                               tp.VerifyClsCompliance ();
                        }
                }
        }
 
-       partial class TypeManager
+       public partial class TypeManager
        {
-               public static TypeContainer LookupGenericTypeContainer (Type t)
-               {
-                       t = DropGenericTypeArguments (t);
-                       return LookupTypeContainer (t);
-               }
-
-               public static Variance GetTypeParameterVariance (Type type)
+               public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
                {
-                       TypeParameter tparam = LookupTypeParameter (type);
-                       if (tparam != null)
-                               return tparam.Variance;
-
-                       switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
-                       case GenericParameterAttributes.Covariant:
-                               return Variance.Covariant;
-                       case GenericParameterAttributes.Contravariant:
-                               return Variance.Contravariant;
-                       default:
-                               return Variance.None;
-                       }
-               }
-
-               public static Variance CheckTypeVariance (Type t, Variance expected, IMemberContext member)
-               {
-                       TypeParameter tp = LookupTypeParameter (t);
+                       var tp = t as TypeParameterSpec;
                        if (tp != null) {
                                Variance v = tp.Variance;
                                if (expected == Variance.None && v != expected ||
                                        expected == Variance.Covariant && v == Variance.Contravariant ||
-                                       expected == Variance.Contravariant && v == Variance.Covariant)
-                                       tp.ErrorInvalidVariance (member, expected);
+                                       expected == Variance.Contravariant && v == Variance.Covariant) {
+                                       ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
+                               }
 
                                return expected;
                        }
 
-                       if (t.IsGenericType) {
-                               Type[] targs_definition = GetTypeArguments (DropGenericTypeArguments (t));
-                               Type[] targs = GetTypeArguments (t);
-                               for (int i = 0; i < targs_definition.Length; ++i) {
-                                       Variance v = GetTypeParameterVariance (targs_definition[i]);
+                       if (t.TypeArguments.Length > 0) {
+                               var targs_definition = t.MemberDefinition.TypeParameters;
+                               TypeSpec[] targs = GetTypeArguments (t);
+                               for (int i = 0; i < targs.Length; ++i) {
+                                       Variance v = targs_definition[i].Variance;
                                        CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
                                }
 
@@ -2002,281 +2222,39 @@ namespace Mono.CSharp {
 
                        return Variance.None;
                }
-
-               public static bool IsVariantOf (Type type1, Type type2)
-               {
-                       if (!type1.IsGenericType || !type2.IsGenericType)
-                               return false;
-
-                       Type generic_target_type = DropGenericTypeArguments (type2);
-                       if (DropGenericTypeArguments (type1) != generic_target_type)
-                               return false;
-
-                       Type[] t1 = GetTypeArguments (type1);
-                       Type[] t2 = GetTypeArguments (type2);
-                       Type[] targs_definition = GetTypeArguments (generic_target_type);
-                       for (int i = 0; i < targs_definition.Length; ++i) {
-                               Variance v = GetTypeParameterVariance (targs_definition [i]);
-                               if (v == Variance.None) {
-                                       if (t1[i] == t2[i])
-                                               continue;
-                                       return false;
-                               }
-
-                               if (v == Variance.Covariant) {
-                                       if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1 [i]), t2 [i]))
-                                               return false;
-                               } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2[i]), t1[i])) {
-                                       return false;
-                               }
-                       }
-
-                       return true;
-               }
-
-               /// <summary>
-               ///   Check whether `a' and `b' may become equal generic types.
-               ///   The algorithm to do that is a little bit complicated.
-               /// </summary>
-               public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
-                                                              Type[] method_inferred)
-               {
-                       if (a.IsGenericParameter) {
-                               //
-                               // If a is an array of a's type, they may never
-                               // become equal.
-                               //
-                               while (b.IsArray) {
-                                       b = GetElementType (b);
-                                       if (a.Equals (b))
-                                               return false;
-                               }
-
-                               //
-                               // If b is a generic parameter or an actual type,
-                               // they may become equal:
-                               //
-                               //    class X<T,U> : I<T>, I<U>
-                               //    class X<T> : I<T>, I<float>
-                               // 
-                               if (b.IsGenericParameter || !b.IsGenericType) {
-                                       int pos = a.GenericParameterPosition;
-                                       Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
-                                       if (args [pos] == null) {
-                                               args [pos] = b;
-                                               return true;
-                                       }
-
-                                       return args [pos] == a;
-                               }
-
-                               //
-                               // We're now comparing a type parameter with a
-                               // generic instance.  They may become equal unless
-                               // the type parameter appears anywhere in the
-                               // generic instance:
-                               //
-                               //    class X<T,U> : I<T>, I<X<U>>
-                               //        -> error because you could instanciate it as
-                               //           X<X<int>,int>
-                               //
-                               //    class X<T> : I<T>, I<X<T>> -> ok
-                               //
-
-                               Type[] bargs = GetTypeArguments (b);
-                               for (int i = 0; i < bargs.Length; i++) {
-                                       if (a.Equals (bargs [i]))
-                                               return false;
-                               }
-
-                               return true;
-                       }
-
-                       if (b.IsGenericParameter)
-                               return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
-
-                       //
-                       // At this point, neither a nor b are a type parameter.
-                       //
-                       // If one of them is a generic instance, let
-                       // MayBecomeEqualGenericInstances() compare them (if the
-                       // other one is not a generic instance, they can never
-                       // become equal).
-                       //
-
-                       if (a.IsGenericType || b.IsGenericType)
-                               return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
-
-                       //
-                       // If both of them are arrays.
-                       //
-
-                       if (a.IsArray && b.IsArray) {
-                               if (a.GetArrayRank () != b.GetArrayRank ())
-                                       return false;
-                       
-                               a = GetElementType (a);
-                               b = GetElementType (b);
-
-                               return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
-                       }
-
-                       //
-                       // Ok, two ordinary types.
-                       //
-
-                       return a.Equals (b);
-               }
-
-               //
-               // Checks whether two generic instances may become equal for some
-               // particular instantiation (26.3.1).
-               //
-               public static bool MayBecomeEqualGenericInstances (Type a, Type b,
-                                                                  Type[] class_inferred,
-                                                                  Type[] method_inferred)
-               {
-                       if (!a.IsGenericType || !b.IsGenericType)
-                               return false;
-                       if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
-                               return false;
-
-                       return MayBecomeEqualGenericInstances (
-                               GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
-               }
-
-               public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
-                                                                  Type[] class_inferred,
-                                                                  Type[] method_inferred)
-               {
-                       if (aargs.Length != bargs.Length)
-                               return false;
-
-                       for (int i = 0; i < aargs.Length; i++) {
-                               if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
-                                       return false;
-                       }
-
-                       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 int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodSpec method)
-               {
-                       ATypeInference ti = ATypeInference.CreateInstance (arguments);
-                       Type[] i_args = ti.InferMethodArguments (ec, method);
-                       if (i_args == null)
-                               return ti.InferenceScore;
-
-                       if (i_args.Length == 0)
-                               return 0;
-
-                       method = method.Inflate (i_args);
-                       return 0;
-               }
-
-/*
-               public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
-               {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
-
-                       ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
-                       Type[] i_args = ti.InferDelegateArguments (ec, method);
-                       if (i_args == null)
-                               return false;
-
-                       method = ((MethodInfo) method).MakeGenericMethod (i_args);
-                       return true;
-               }
-*/
-       }
-
-       abstract class ATypeInference
-       {
-               protected readonly Arguments arguments;
-               protected readonly int arg_count;
-
-               protected ATypeInference (Arguments arguments)
-               {
-                       this.arguments = arguments;
-                       if (arguments != null)
-                               arg_count = arguments.Count;
-               }
-
-               public static ATypeInference CreateInstance (Arguments arguments)
-               {
-                       return new TypeInference (arguments);
-               }
-
-               public virtual int InferenceScore {
-                       get {
-                               return int.MaxValue;
-                       }
-               }
-
-               public abstract Type[] InferMethodArguments (ResolveContext ec, MethodSpec method);
-//             public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
        }
 
        //
        // Implements C# type inference
        //
-       class TypeInference : ATypeInference
+       class TypeInference
        {
                //
                // Tracks successful rate of type inference
                //
                int score = int.MaxValue;
+               readonly Arguments arguments;
+               readonly int arg_count;
 
                public TypeInference (Arguments arguments)
-                       : base (arguments)
                {
+                       this.arguments = arguments;
+                       if (arguments != null)
+                               arg_count = arguments.Count;
                }
 
-               public override int InferenceScore {
+               public int InferenceScore {
                        get {
                                return score;
                        }
                }
 
-/*
-               public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
-               {
-                       AParametersCollection pd = TypeManager.GetParameterData (method);
-                       if (arg_count != pd.Count)
-                               return null;
-
-                       Type[] d_gargs = method.GetGenericArguments ();
-                       TypeInferenceContext context = new TypeInferenceContext (d_gargs);
-
-                       // A lower-bound inference is made from each argument type Uj of D
-                       // to the corresponding parameter type Tj of M
-                       for (int i = 0; i < arg_count; ++i) {
-                               Type t = pd.Types [i];
-                               if (!t.IsGenericParameter)
-                                       continue;
-
-                               context.LowerBoundInference (arguments [i].Expr.Type, t);
-                       }
-
-                       if (!context.FixAllTypes (ec))
-                               return null;
-
-                       return context.InferredTypeArguments;
-               }
-*/
-               public override Type[] InferMethodArguments (ResolveContext ec, MethodSpec method)
+               public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
                {
-                       var method_generic_args = method.GetGenericArguments ();
+                       var method_generic_args = method.GenericDefinition.TypeParameters;
                        TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
                        if (!context.UnfixedVariableExists)
-                               return Type.EmptyTypes;
+                               return TypeSpec.EmptyTypes;
 
                        AParametersCollection pd = method.Parameters;
                        if (!InferInPhases (ec, context, pd))
@@ -2297,12 +2275,12 @@ namespace Mono.CSharp {
                                params_arguments_start = arg_count;
                        }
 
-                       Type [] ptypes = methodParameters.Types;
+                       TypeSpec [] ptypes = methodParameters.Types;
                        
                        //
                        // The first inference phase
                        //
-                       Type method_parameter = null;
+                       TypeSpec method_parameter = null;
                        for (int i = 0; i < arg_count; i++) {
                                Argument a = arguments [i];
                                if (a == null)
@@ -2316,7 +2294,7 @@ namespace Mono.CSharp {
                                        else
                                                method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
 
-                                       ptypes = (Type[]) ptypes.Clone ();
+                                       ptypes = (TypeSpec[]) ptypes.Clone ();
                                        ptypes [i] = method_parameter;
                                }
 
@@ -2336,7 +2314,7 @@ namespace Mono.CSharp {
                                        continue;
                                }
 
-                               if (a.Expr.Type == TypeManager.null_type)
+                               if (a.Expr.Type == InternalType.Null)
                                        continue;
 
                                if (TypeManager.IsValueType (method_parameter)) {
@@ -2361,7 +2339,7 @@ namespace Mono.CSharp {
                        return DoSecondPhase (ec, tic, ptypes, !fixed_any);
                }
 
-               bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
+               bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
                {
                        bool fixed_any = false;
                        if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
@@ -2380,23 +2358,17 @@ namespace Mono.CSharp {
                        for (int i = 0; i < arg_count; i++) {
                                
                                // Align params arguments
-                               Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
+                               TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
                                
                                if (!TypeManager.IsDelegateType (t_i)) {
-                                       if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
+                                       if (t_i.GetDefinition () != TypeManager.expression_type)
                                                continue;
 
-                                       t_i = t_i.GetGenericArguments () [0];
+                                       t_i = TypeManager.GetTypeArguments (t_i) [0];
                                }
 
-                               var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
-                               Type rtype = mi.ReturnType;
-
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             Type[] g_args = t_i.GetGenericArguments ();
-//                             rtype = g_args[rtype.GenericParameterPosition];
-#endif
+                               var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
+                               TypeSpec rtype = mi.ReturnType;
 
                                if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
                                        score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
@@ -2416,12 +2388,12 @@ namespace Mono.CSharp {
                        Upper   = 2
                }
 
-               class BoundInfo
+               class BoundInfo : IEquatable<BoundInfo>
                {
-                       public readonly Type Type;
+                       public readonly TypeSpec Type;
                        public readonly BoundKind Kind;
 
-                       public BoundInfo (Type type, BoundKind kind)
+                       public BoundInfo (TypeSpec type, BoundKind kind)
                        {
                                this.Type = type;
                                this.Kind = kind;
@@ -2432,29 +2404,33 @@ namespace Mono.CSharp {
                                return Type.GetHashCode ();
                        }
 
-                       public override bool Equals (object obj)
+                       #region IEquatable<BoundInfo> Members
+
+                       public bool Equals (BoundInfo other)
                        {
-                               BoundInfo a = (BoundInfo) obj;
-                               return Type == a.Type && Kind == a.Kind;
+                               return Type == other.Type && Kind == other.Kind;
                        }
+
+                       #endregion
                }
 
-               readonly Type[] unfixed_types;
-               readonly Type[] fixed_types;
+               readonly TypeSpec[] unfixed_types;
+               readonly TypeSpec[] fixed_types;
                readonly List<BoundInfo>[] bounds;
                bool failed;
-               
-               public TypeInferenceContext (Type[] typeArguments)
+
+               // TODO MemberCache: Could it be TypeParameterSpec[] ??
+               public TypeInferenceContext (TypeSpec[] typeArguments)
                {
                        if (typeArguments.Length == 0)
                                throw new ArgumentException ("Empty generic arguments");
 
-                       fixed_types = new Type [typeArguments.Length];
+                       fixed_types = new TypeSpec [typeArguments.Length];
                        for (int i = 0; i < typeArguments.Length; ++i) {
                                if (typeArguments [i].IsGenericParameter) {
                                        if (bounds == null) {
                                                bounds = new List<BoundInfo> [typeArguments.Length];
-                                               unfixed_types = new Type [typeArguments.Length];
+                                               unfixed_types = new TypeSpec [typeArguments.Length];
                                        }
                                        unfixed_types [i] = typeArguments [i];
                                } else {
@@ -2469,19 +2445,19 @@ namespace Mono.CSharp {
                //
                public TypeInferenceContext ()
                {
-                       fixed_types = new Type [1];
-                       unfixed_types = new Type [1];
+                       fixed_types = new TypeSpec [1];
+                       unfixed_types = new TypeSpec [1];
                        unfixed_types[0] = InternalType.Arglist; // it can be any internal type
                        bounds = new List<BoundInfo> [1];
                }
 
-               public Type[] InferredTypeArguments {
+               public TypeSpec[] InferredTypeArguments {
                        get {
                                return fixed_types;
                        }
                }
 
-               public void AddCommonTypeBound (Type type)
+               public void AddCommonTypeBound (TypeSpec type)
                {
                        AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
                }
@@ -2496,37 +2472,29 @@ namespace Mono.CSharp {
 
                        var a = bounds [index];
                        if (a == null) {
-                               a = new List<BoundInfo> ();
+                               a = new List<BoundInfo> (2);
+                               a.Add (bound);
                                bounds [index] = a;
-                       } else {
-                               if (a.Contains (bound))
-                                       return;
+                               return;
                        }
 
-                       //
-                       // SPEC: does not cover type inference using constraints
-                       //
-                       //if (TypeManager.IsGenericParameter (t)) {
-                       //    GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
-                       //    if (constraints != null) {
-                       //        //if (constraints.EffectiveBaseClass != null)
-                       //        //    t = constraints.EffectiveBaseClass;
-                       //    }
-                       //}
+                       if (a.Contains (bound))
+                               return;
+
                        a.Add (bound);
                }
                
-               bool AllTypesAreFixed (Type[] types)
+               bool AllTypesAreFixed (TypeSpec[] types)
                {
-                       foreach (Type t in types) {
+                       foreach (TypeSpec t in types) {
                                if (t.IsGenericParameter) {
                                        if (!IsFixed (t))
                                                return false;
                                        continue;
                                }
 
-                               if (t.IsGenericType)
-                                       return AllTypesAreFixed (t.GetGenericArguments ());
+                               if (TypeManager.IsGenericType (t))
+                                       return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
                        }
                        
                        return true;
@@ -2535,26 +2503,27 @@ namespace Mono.CSharp {
                //
                // 26.3.3.8 Exact Inference
                //
-               public int ExactInference (Type u, Type v)
+               public int ExactInference (TypeSpec u, TypeSpec v)
                {
                        // If V is an array type
                        if (v.IsArray) {
                                if (!u.IsArray)
                                        return 0;
 
-                               if (u.GetArrayRank () != v.GetArrayRank ())
+                               // TODO MemberCache: GetMetaInfo ()
+                               if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
                                        return 0;
 
                                return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
                        }
 
                        // If V is constructed type and U is constructed type
-                       if (v.IsGenericType && !v.IsGenericTypeDefinition) {
-                               if (!u.IsGenericType)
+                       if (TypeManager.IsGenericType (v)) {
+                               if (!TypeManager.IsGenericType (u))
                                        return 0;
 
-                               Type [] ga_u = u.GetGenericArguments ();
-                               Type [] ga_v = v.GetGenericArguments ();
+                               TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
+                               TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
                                if (ga_u.Length != ga_v.Length)
                                        return 0;
 
@@ -2609,39 +2578,32 @@ namespace Mono.CSharp {
                //
                // All unfixed type variables Xi which depend on no Xj are fixed
                //
-               public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
+               public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
                {
-                       var types_to_fix = new List<Type> (unfixed_types);
+                       var types_to_fix = new List<TypeSpec> (unfixed_types);
                        for (int i = 0; i < methodParameters.Length; ++i) {
-                               Type t = methodParameters[i];
+                               TypeSpec t = methodParameters[i];
 
                                if (!TypeManager.IsDelegateType (t)) {
-                                       if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
+                                       if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
                                                continue;
 
-                                       t = t.GetGenericArguments () [0];
+                                       t =  TypeManager.GetTypeArguments (t) [0];
                                }
 
                                if (t.IsGenericParameter)
                                        continue;
 
-                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
-                               Type rtype = invoke.ReturnType;
-                               if (!rtype.IsGenericParameter && !rtype.IsGenericType)
+                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
+                               TypeSpec rtype = invoke.ReturnType;
+                               if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
                                        continue;
 
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             if (rtype.IsGenericParameter) {
-//                                     Type [] g_args = t.GetGenericArguments ();
-//                                     rtype = g_args [rtype.GenericParameterPosition];
-//                             }
-#endif
                                // Remove dependent types, they cannot be fixed yet
                                RemoveDependentTypes (types_to_fix, rtype);
                        }
 
-                       foreach (Type t in types_to_fix) {
+                       foreach (TypeSpec t in types_to_fix) {
                                if (t == null)
                                        continue;
 
@@ -2673,8 +2635,8 @@ namespace Mono.CSharp {
 
                        if (candidates.Count == 1) {
                                unfixed_types[i] = null;
-                               Type t = candidates[0].Type;
-                               if (t == TypeManager.null_type)
+                               TypeSpec t = candidates[0].Type;
+                               if (t == InternalType.Null)
                                        return false;
 
                                fixed_types [i] = t;
@@ -2686,16 +2648,16 @@ namespace Mono.CSharp {
                        // a standard implicit conversion to all the other
                        // candidate types.
                        //
-                       Type best_candidate = null;
+                       TypeSpec best_candidate = null;
                        int cii;
                        int candidates_count = candidates.Count;
                        for (int ci = 0; ci < candidates_count; ++ci) {
-                               BoundInfo bound = (BoundInfo)candidates [ci];
+                               BoundInfo bound = candidates [ci];
                                for (cii = 0; cii < candidates_count; ++cii) {
                                        if (cii == ci)
                                                continue;
 
-                                       BoundInfo cbound = (BoundInfo) candidates[cii];
+                                       BoundInfo cbound = candidates[cii];
                                        
                                        // Same type parameters with different bounds
                                        if (cbound.Type == bound.Type) {
@@ -2706,13 +2668,20 @@ namespace Mono.CSharp {
                                        }
 
                                        if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
-                                               if (cbound.Kind != BoundKind.Exact) {
+                                               if (cbound.Kind == BoundKind.Lower) {
                                                        if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
                                                                break;
                                                        }
 
                                                        continue;
                                                }
+                                               if (cbound.Kind == BoundKind.Upper) {
+                                                       if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
+                                                               break;
+                                                       }
+
+                                                       continue;
+                                               }
                                                
                                                if (bound.Kind != BoundKind.Exact) {
                                                        if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
@@ -2727,21 +2696,46 @@ namespace Mono.CSharp {
                                        }
 
                                        if (bound.Kind == BoundKind.Lower) {
-                                               if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
-                                                       break;
+                                               if (cbound.Kind == BoundKind.Lower) {
+                                                       if (!Convert.ImplicitConversionExists (ec, new TypeExpression (cbound.Type, Location.Null), bound.Type)) {
+                                                               break;
+                                                       }
+                                               } else {
+                                                       if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
+                                                               break;
+                                                       }
+
+                                                       bound = cbound;
                                                }
-                                       } else {
+
+                                               continue;
+                                       }
+
+                                       if (bound.Kind == BoundKind.Upper) {
                                                if (!Convert.ImplicitConversionExists (ec, new TypeExpression (bound.Type, Location.Null), cbound.Type)) {
                                                        break;
                                                }
+                                       } else {
+                                               throw new NotImplementedException ("variance conversion");
                                        }
                                }
 
                                if (cii != candidates_count)
                                        continue;
 
-                               if (best_candidate != null && best_candidate != bound.Type)
-                                       return false;
+                               //
+                               // We already have the best candidate, break if thet are different
+                               //
+                               // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
+                               //
+                               if (best_candidate != null) {
+
+                                       if (best_candidate == InternalType.Dynamic)
+                                               continue;
+
+                                       if (bound.Type != InternalType.Dynamic && best_candidate != bound.Type)
+                                               return false;
+                               }
 
                                best_candidate = bound.Type;
                        }
@@ -2755,26 +2749,34 @@ namespace Mono.CSharp {
                }
                
                //
-               // Uses inferred types to inflate delegate type argument
+               // Uses inferred or partially infered types to inflate delegate type argument. Returns
+               // null when type parameter was not yet inferres
                //
-               public Type InflateGenericArgument (Type parameter)
+               public TypeSpec InflateGenericArgument (TypeSpec parameter)
                {
-                       if (parameter.IsGenericParameter) {
+                       var tp = parameter as TypeParameterSpec;
+                       if (tp != null) {
                                //
-                               // Inflate method generic argument (MVAR) only
+                               // Type inference work on generic arguments (MVAR) only
                                //
-                               if (parameter.DeclaringMethod == null)
+                               if (!tp.IsMethodOwned)
                                        return parameter;
 
-                               return fixed_types [parameter.GenericParameterPosition];
+                               return fixed_types [tp.DeclaredPosition] ?? parameter;
                        }
 
-                       if (parameter.IsGenericType) {
-                               Type [] parameter_targs = parameter.GetGenericArguments ();
-                               for (int ii = 0; ii < parameter_targs.Length; ++ii) {
-                                       parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
+                       var gt = parameter as InflatedTypeSpec;
+                       if (gt != null) {
+                               var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
+                               for (int ii = 0; ii < inflated_targs.Length; ++ii) {
+                                       var inflated = InflateGenericArgument (gt.TypeArguments [ii]);
+                                       if (inflated == null)
+                                               return null;
+
+                                       inflated_targs[ii] = inflated;
                                }
-                               return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
+
+                               return gt.GetDefinition ().MakeGenericType (inflated_targs);
                        }
 
                        return parameter;
@@ -2784,18 +2786,18 @@ namespace Mono.CSharp {
                // Tests whether all delegate input arguments are fixed and generic output type
                // requires output type inference 
                //
-               public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, Type returnType)
+               public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
                {
                        if (returnType.IsGenericParameter) {
                                if (IsFixed (returnType))
                                    return false;
-                       } else if (returnType.IsGenericType) {
+                       } else if (TypeManager.IsGenericType (returnType)) {
                                if (TypeManager.IsDelegateType (returnType)) {
-                                       invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
+                                       invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
                                        return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
                                }
                                        
-                               Type[] g_args = returnType.GetGenericArguments ();
+                               TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
                                
                                // At least one unfixed return type has to exist 
                                if (AllTypesAreFixed (g_args))
@@ -2809,12 +2811,12 @@ namespace Mono.CSharp {
                        return AllTypesAreFixed (d_parameters.Types);
                }
                
-               bool IsFixed (Type type)
+               bool IsFixed (TypeSpec type)
                {
                        return IsUnfixed (type) == -1;
                }               
 
-               int IsUnfixed (Type type)
+               int IsUnfixed (TypeSpec type)
                {
                        if (!type.IsGenericParameter)
                                return -1;
@@ -2831,7 +2833,7 @@ namespace Mono.CSharp {
                //
                // 26.3.3.9 Lower-bound Inference
                //
-               public int LowerBoundInference (Type u, Type v)
+               public int LowerBoundInference (TypeSpec u, TypeSpec v)
                {
                        return LowerBoundInference (u, v, false);
                }
@@ -2839,7 +2841,7 @@ namespace Mono.CSharp {
                //
                // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
                //
-               int LowerBoundInference (Type u, Type v, bool inversed)
+               int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
                {
                        // If V is one of the unfixed type arguments
                        int pos = IsUnfixed (v);
@@ -2849,75 +2851,67 @@ namespace Mono.CSharp {
                        }                       
 
                        // If U is an array type
-                       if (u.IsArray) {
-                               int u_dim = u.GetArrayRank ();
-                               Type v_i;
-                               Type u_i = TypeManager.GetElementType (u);
-
-                               if (v.IsArray) {
-                                       if (u_dim != v.GetArrayRank ())
+                       var u_ac = u as ArrayContainer;
+                       if (u_ac != null) {
+                               var v_ac = v as ArrayContainer;
+                               if (v_ac != null) {
+                                       if (u_ac.Rank != v_ac.Rank)
                                                return 0;
 
-                                       v_i = TypeManager.GetElementType (v);
+                                       if (TypeManager.IsValueType (u_ac.Element))
+                                               return ExactInference (u_ac.Element, v_ac.Element);
 
-                                       if (TypeManager.IsValueType (u_i))
-                                               return ExactInference (u_i, v_i);
-
-                                       return LowerBoundInference (u_i, v_i, inversed);
+                                       return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
                                }
 
-                               if (u_dim != 1)
+                               if (u_ac.Rank != 1)
                                        return 0;
 
-                               if (v.IsGenericType) {
-                                       Type g_v = v.GetGenericTypeDefinition ();
-                                       if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
-                                               (g_v != TypeManager.generic_ienumerable_type))
+                               if (TypeManager.IsGenericType (v)) {
+                                       TypeSpec g_v = v.GetDefinition ();
+                                       if (g_v != TypeManager.generic_ilist_type &&
+                                               g_v != TypeManager.generic_icollection_type &&
+                                               g_v != TypeManager.generic_ienumerable_type)
                                                return 0;
 
-                                       v_i = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (v) [0]);
-                                       if (TypeManager.IsValueType (u_i))
-                                               return ExactInference (u_i, v_i);
+                                       var v_i = TypeManager.GetTypeArguments (v) [0];
+                                       if (TypeManager.IsValueType (u_ac.Element))
+                                               return ExactInference (u_ac.Element, v_i);
 
-                                       return LowerBoundInference (u_i, v_i);
+                                       return LowerBoundInference (u_ac.Element, v_i);
                                }
-                       } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
+                       } else if (TypeManager.IsGenericType (v)) {
                                //
                                // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
                                // such that U is identical to, inherits from (directly or indirectly),
                                // or implements (directly or indirectly) C<U1..Uk>
                                //
-                               var u_candidates = new List<Type> ();
-                               if (u.IsGenericType)
-                                       u_candidates.Add (u);
+                               var u_candidates = new List<TypeSpec> ();
+                               var open_v = v.MemberDefinition;
 
-                               for (Type t = u.BaseType; t != null; t = t.BaseType) {
-                                       if (t.IsGenericType && !t.IsGenericTypeDefinition)
+                               for (TypeSpec t = u; t != null; t = t.BaseType) {
+                                       if (open_v == t.MemberDefinition)
                                                u_candidates.Add (t);
-                               }
 
-                               // TODO: Implement GetGenericInterfaces only and remove
-                               // the if from foreach
-                               u_candidates.AddRange (TypeManager.GetInterfaces (u));
-
-                               Type open_v = v.GetGenericTypeDefinition ();
-                               Type [] unique_candidate_targs = null;
-                               Type [] ga_v = v.GetGenericArguments ();                        
-                               foreach (Type u_candidate in u_candidates) {
-                                       if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
-                                               continue;
-
-                                       if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
-                                               continue;
+                                       if (t.Interfaces != null) {
+                                               foreach (var iface in t.Interfaces) {
+                                                       if (open_v == iface.MemberDefinition)
+                                                               u_candidates.Add (iface);
+                                               }
+                                       }
+                               }
 
+                               TypeSpec [] unique_candidate_targs = null;
+                               TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
+                               foreach (TypeSpec u_candidate in u_candidates) {
                                        //
                                        // The unique set of types U1..Uk means that if we have an interface I<T>,
                                        // class U : I<int>, I<long> then no type inference is made when inferring
                                        // type I<T> by applying type U because T could be int or long
                                        //
                                        if (unique_candidate_targs != null) {
-                                               Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
-                                               if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
+                                               TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
+                                               if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
                                                        unique_candidate_targs = second_unique_candidate_targs;
                                                        continue;
                                                }
@@ -2929,16 +2923,16 @@ namespace Mono.CSharp {
                                                return 1;
                                        }
 
-                                       unique_candidate_targs = u_candidate.GetGenericArguments ();
+                                       unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
                                }
 
                                if (unique_candidate_targs != null) {
-                                       Type[] ga_open_v = open_v.GetGenericArguments ();
+                                       var ga_open_v = open_v.TypeParameters;
                                        int score = 0;
                                        for (int i = 0; i < unique_candidate_targs.Length; ++i) {
-                                               Variance variance = TypeManager.GetTypeParameterVariance (ga_open_v [i]);
+                                               Variance variance = ga_open_v [i].Variance;
 
-                                               Type u_i = unique_candidate_targs [i];
+                                               TypeSpec u_i = unique_candidate_targs [i];
                                                if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
                                                        if (ExactInference (u_i, ga_v [i]) == 0)
                                                                ++score;
@@ -2960,25 +2954,20 @@ namespace Mono.CSharp {
                //
                // 26.3.3.6 Output Type Inference
                //
-               public int OutputTypeInference (ResolveContext ec, Expression e, Type t)
+               public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
                {
                        // If e is a lambda or anonymous method with inferred return type
                        AnonymousMethodExpression ame = e as AnonymousMethodExpression;
                        if (ame != null) {
-                               Type rt = ame.InferReturnType (ec, this, t);
-                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
+                               TypeSpec rt = ame.InferReturnType (ec, this, t);
+                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
 
                                if (rt == null) {
                                        AParametersCollection pd = invoke.Parameters;
                                        return ame.Parameters.Count == pd.Count ? 1 : 0;
                                }
 
-                               Type rtype = invoke.ReturnType;
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             Type [] g_args = t.GetGenericArguments ();
-//                             rtype = g_args [rtype.GenericParameterPosition];
-#endif
+                               TypeSpec rtype = invoke.ReturnType;
                                return LowerBoundInference (rt, rtype) + 1;
                        }
 
@@ -2989,30 +2978,39 @@ namespace Mono.CSharp {
                        // then a lower-bound inference is made from U for Tb.
                        //
                        if (e is MethodGroupExpr) {
-                               // TODO: Or expression tree
-                               if (!TypeManager.IsDelegateType (t))
-                                       return 0;
+                               if (!TypeManager.IsDelegateType (t)) {
+                                       if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
+                                               return 0;
+
+                                       t = TypeManager.GetTypeArguments (t)[0];
+                               }
 
-                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
-                               Type rtype = invoke.ReturnType;
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             Type [] g_args = t.GetGenericArguments ();
-//                             rtype = g_args [rtype.GenericParameterPosition];
-#endif
+                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
+                               TypeSpec rtype = invoke.ReturnType;
 
-                               if (!TypeManager.IsGenericType (rtype))
+                               if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
                                        return 0;
 
+                               // LAMESPEC: Standard does not specify that all methodgroup arguments
+                               // has to be fixed but it does not specify how to do recursive type inference
+                               // either. We choose the simple option and infer return type only
+                               // if all delegate generic arguments are fixed.
+                               TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
+                               for (int i = 0; i < param_types.Length; ++i) {
+                                       var inflated = InflateGenericArgument (invoke.Parameters.Types[i]);
+                                       if (inflated == null)
+                                               return 0;
+
+                                       param_types[i] = inflated;
+                               }
+
                                MethodGroupExpr mg = (MethodGroupExpr) e;
-                               Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, e.Location);
-                               mg = mg.OverloadResolve (ec, ref args, true, e.Location);
+                               Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
+                               mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
                                if (mg == null)
                                        return 0;
 
-                               // TODO: What should happen when return type is of generic type ?
-                               throw new NotImplementedException ();
-//                             return LowerBoundInference (null, rtype) + 1;
+                               return LowerBoundInference (mg.BestCandidate.ReturnType, rtype) + 1;
                        }
 
                        //
@@ -3022,7 +3020,7 @@ namespace Mono.CSharp {
                        return LowerBoundInference (e.Type, t) * 2;
                }
 
-               void RemoveDependentTypes (List<Type> types, Type returnType)
+               void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
                {
                        int idx = IsUnfixed (returnType);
                        if (idx >= 0) {
@@ -3030,8 +3028,8 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       if (returnType.IsGenericType) {
-                               foreach (Type t in returnType.GetGenericArguments ()) {
+                       if (TypeManager.IsGenericType (returnType)) {
+                               foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
                                        RemoveDependentTypes (types, t);
                                }
                        }
@@ -3042,7 +3040,7 @@ namespace Mono.CSharp {
                                if (unfixed_types == null)
                                        return false;
 
-                               foreach (Type ut in unfixed_types)
+                               foreach (TypeSpec ut in unfixed_types)
                                        if (ut != null)
                                                return true;
                                return false;