2007-08-29 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / gmcs / generic.cs
index 2a79505daa0f7aa5ab279a3dde1f513fbb23b042..d69a74b9e9bed74d075fa4e8da2329f81cbefefb 100644 (file)
@@ -3,6 +3,7 @@
 //
 // Authors: Martin Baulig (martin@ximian.com)
 //          Miguel de Icaza (miguel@ximian.com)
+//          Marek Safar (marek.safar@gmail.com)
 //
 // Licensed under the terms of the GNU GPL
 //
@@ -151,7 +152,9 @@ namespace Mono.CSharp {
                }
 
                public override string TypeParameter {
-                       get { return name; }
+                       get {
+                               return name;
+                       }
                }
 
                public Constraints Clone ()
@@ -185,7 +188,7 @@ namespace Mono.CSharp {
                        foreach (object obj in constraints) {
                                if (HasConstructorConstraint) {
                                        Report.Error (401, loc,
-                                                     "The new() constraint must be last.");
+                                                     "The new() constraint must be the last constraint specified");
                                        return false;
                                }
 
@@ -198,17 +201,14 @@ namespace Mono.CSharp {
                                                        continue;
                                                }
 
-                                               Report.Error (
-                                                       451, loc, "The new () constraint " +
-                                                       "cannot be used with the `struct' " +
-                                                       "constraint.");
+                                               Report.Error (451, loc, "The `new()' constraint " +
+                                                       "cannot be used with the `struct' constraint");
                                                return false;
                                        }
 
                                        if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
-                                               Report.Error (449, loc,
-                                                             "The `class' or `struct' " +
-                                                             "constraint must be first");
+                                               Report.Error (449, loc, "The `class' or `struct' " +
+                                                             "constraint must be the first constraint specified");
                                                return false;
                                        }
 
@@ -226,7 +226,7 @@ namespace Mono.CSharp {
                                        if (errors != Report.Errors)
                                                return false;
 
-                                       Report.Error (246, loc, "Cannot find type '{0}'", ((Expression) obj).GetSignatureForError ());
+                                       NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
                                        return false;
                                }
 
@@ -238,11 +238,20 @@ namespace Mono.CSharp {
 
                                        expr = cexpr;
                                } else
-                                       expr = fn.ResolveAsTypeTerminal (ec, false);
+                                       expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
 
                                if ((expr == null) || (expr.Type == null))
                                        return false;
 
+                               // TODO: It's aleady done in ResolveAsBaseTerminal
+                               if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
+                                       Report.SymbolRelatedToPreviousError (fn.Type);
+                                       Report.Error (703, loc,
+                                               "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
+                                               fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
+                                       return false;
+                               }
+
                                TypeParameterExpr texpr = expr as TypeParameterExpr;
                                if (texpr != null)
                                        type_param_constraints.Add (expr);
@@ -257,7 +266,7 @@ namespace Mono.CSharp {
                                } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
                                        Report.Error (450, loc, "`{0}': cannot specify both " +
                                                      "a constraint class and the `class' " +
-                                                     "or `struct' constraint.", expr.Name);
+                                                     "or `struct' constraint", expr.GetSignatureForError ());
                                        return false;
                                } else
                                        class_constraint = expr;
@@ -304,10 +313,16 @@ namespace Mono.CSharp {
                                        return false;
 
                                if (class_constraint_type.IsSealed) {
-                                       Report.Error (701, loc,
-                                                     "`{0}' is not a valid bound.  Bounds " +
-                                                     "must be interfaces or non sealed " +
-                                                     "classes", TypeManager.CSharpName (class_constraint_type));
+                                       if (class_constraint_type.IsAbstract)
+                                       {
+                                               Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
+                                                       TypeManager.CSharpName (class_constraint_type));
+                                       }
+                                       else
+                                       {
+                                               Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
+                                                       "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
+                                       }
                                        return false;
                                }
 
@@ -553,6 +568,27 @@ namespace Mono.CSharp {
 
                        return true;
                }
+
+               public void VerifyClsCompliance ()
+               {
+                       if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
+                               Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
+
+                       if (iface_constraint_types != null) {
+                               for (int i = 0; i < iface_constraint_types.Length; ++i) {
+                                       if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
+                                               Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
+                                                       ((TypeExpr)iface_constraints [i]).Location);
+                               }
+                       }
+               }
+
+               void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
+               {
+                       Report.SymbolRelatedToPreviousError (t);
+                       Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
+                               TypeManager.CSharpName (t));
+               }
        }
 
        /// <summary>
@@ -565,6 +601,7 @@ namespace Mono.CSharp {
                Constraints constraints;
                Location loc;
                GenericTypeParameterBuilder type;
+               MemberCache member_cache;
 
                public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
                                      Constraints constraints, Attributes attrs, Location loc)
@@ -584,10 +621,6 @@ namespace Mono.CSharp {
                        get { return constraints; }
                }
 
-               public bool HasConstructorConstraint {
-                       get { return constraints != null && constraints.HasConstructorConstraint; }
-               }
-
                public DeclSpace DeclSpace {
                        get { return decl; }
                }
@@ -687,11 +720,9 @@ namespace Mono.CSharp {
 
                        if (implementing != null) {
                                if (is_override && (constraints != null)) {
-                                       Report.Error (
-                                               460, loc, "Constraints for override and " +
-                                               "explicit interface implementation methods " +
-                                               "are inherited from the base method so they " +
-                                               "cannot be specified directly");
+                                       Report.Error (460, loc,
+                                               "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
+                                               TypeManager.CSharpSignature (builder));
                                        return false;
                                }
 
@@ -849,11 +880,19 @@ namespace Mono.CSharp {
                }
 
                MemberCache IMemberContainer.BaseCache {
-                       get { return null; }
+                       get {
+                               if (gc == null)
+                                       return null;
+
+                               if (gc.EffectiveBaseClass.BaseType == null)
+                                       return null;
+
+                               return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
+                       }
                }
 
                bool IMemberContainer.IsInterface {
-                       get { return true; }
+                       get { return false; }
                }
 
                MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
@@ -861,14 +900,25 @@ namespace Mono.CSharp {
                        return FindMembers (mt, bf, null, null);
                }
 
-               MemberCache IMemberContainer.MemberCache {
-                       get { return null; }
+               public MemberCache MemberCache {
+                       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;
+                       }
                }
 
                public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
                                               MemberFilter filter, object criteria)
                {
-                       if (constraints == null)
+                       if (gc == null)
                                return MemberList.Empty;
 
                        ArrayList members = new ArrayList ();
@@ -954,7 +1004,7 @@ namespace Mono.CSharp {
                                bool has_class_constr = false;
                                if (list.Count > 0) {
                                        Type first = (Type) list [0];
-                                       has_class_constr = !first.IsInterface && !first.IsGenericParameter;
+                                       has_class_constr = !first.IsGenericParameter && !first.IsInterface;
                                }
 
                                if ((list.Count > 0) && has_class_constr) {
@@ -1086,6 +1136,12 @@ namespace Mono.CSharp {
                        this.Location = loc;
                }
 
+               public TypeArguments (Location loc, params Expression[] types)
+               {
+                       this.Location = loc;
+                       this.args = new ArrayList (types);
+               }
+               
                public TypeArguments (int dimension, Location loc)
                {
                        this.dimension = dimension;
@@ -1184,6 +1240,19 @@ namespace Mono.CSharp {
                        return s.ToString ();
                }
 
+               public string GetSignatureForError()
+               {
+                       StringBuilder sb = new StringBuilder();
+                       for (int i = 0; i < Count; ++i)
+                       {
+                               Expression expr = (Expression)args [i];
+                               sb.Append(expr.GetSignatureForError());
+                               if (i + 1 < Count)
+                                       sb.Append(',');
+                       }
+                       return sb.ToString();
+               }
+
                /// <summary>
                ///   Resolve the type arguments.
                /// </summary>
@@ -1200,23 +1269,42 @@ namespace Mono.CSharp {
                                        ok = false;
                                        continue;
                                }
-                               if (te is TypeParameterExpr)
-                                       has_type_args = true;
+
+                               atypes[i] = te.Type;
+                               if (te.Type.IsGenericParameter) {
+                                       if (te is TypeParameterExpr)
+                                               has_type_args = true;
+                                       continue;
+                               }
+
+                               if (te.Type.IsSealed && te.Type.IsAbstract) {
+                                       Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
+                                               te.GetSignatureForError ());
+                                       return false;
+                               }
 
                                if (te.Type.IsPointer) {
                                        Report.Error (306, Location, "The type `{0}' may not be used " +
-                                                     "as a type argument", TypeManager.CSharpName (te.Type));
-                                       return false;
-                               } else if (te.Type == TypeManager.void_type) {
-                                       Report.Error (1547, Location,
-                                                     "Keyword `void' cannot be used in this context");
+                                                         "as a type argument", TypeManager.CSharpName (te.Type));
                                        return false;
                                }
 
-                               atypes [i] = te.Type;
+                               if (te.Type == TypeManager.void_type) {
+                                       Expression.Error_VoidInvalidInTheContext (Location);
+                                       return false;
+                               }
                        }
                        return ok;
                }
+
+               public TypeArguments Clone ()
+               {
+                       TypeArguments copy = new TypeArguments (Location);
+                       foreach (Expression ta in args)
+                               copy.args.Add (ta);
+
+                       return copy;
+               }
        }
 
        public class TypeParameterName : SimpleName
@@ -1310,7 +1398,7 @@ namespace Mono.CSharp {
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.CSharpName (gt);
+                       return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
                }
 
                protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
@@ -1401,6 +1489,11 @@ namespace Mono.CSharp {
 
                public override bool AsAccessible (DeclSpace ds, int flags)
                {
+                       foreach (Type t in atypes) {
+                               if (!ds.AsAccessible (t, flags))
+                                       return false;
+                       }
+
                        return ds.AsAccessible (gt, flags);
                }
 
@@ -1443,7 +1536,6 @@ namespace Mono.CSharp {
                        }
                }
 
-
                public override string FullName {
                        get {
                                return full_name;
@@ -1498,8 +1590,8 @@ namespace Mono.CSharp {
                                if (agc != null) {
                                        if (agc is Constraints)
                                                ((Constraints) agc).Resolve (ec);
-                                       is_class = agc.HasReferenceTypeConstraint;
-                                       is_struct = agc.HasValueTypeConstraint;
+                                       is_class = agc.IsReferenceType;
+                                       is_struct = agc.IsValueType;
                                } else {
                                        is_class = is_struct = false;
                                }
@@ -1563,7 +1655,7 @@ namespace Mono.CSharp {
                        if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
                                return true;
 
-                       if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
+                       if (HasDefaultConstructor (atype))
                                return true;
 
                        Report_SymbolRelatedToPreviousError ();
@@ -1612,7 +1704,7 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               bool HasDefaultConstructor (Type containerType, Type atype)
+               bool HasDefaultConstructor (Type atype)
                {
                        if (atype.IsAbstract)
                                return false;
@@ -1640,8 +1732,12 @@ namespace Mono.CSharp {
                        }
 
                        TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
-                       if (tparam != null)
-                               return tparam.HasConstructorConstraint;
+                       if (tparam != null) {
+                               if (tparam.GenericConstraints == null)
+                                       return false;
+                               else
+                                       return tparam.GenericConstraints.HasConstructorConstraint;
+                       }
 
                        MemberList list = TypeManager.FindMembers (
                                atype, MemberTypes.Constructor,
@@ -1783,8 +1879,10 @@ namespace Mono.CSharp {
                                        Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
                                        return false;
                                }
+
+                               // FIXME: This is wrong, since it only looks at the outermost set of variables
                                if (block != null) {
-                                       LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
+                                       LocalInfo li = (LocalInfo)block.Variables [type_argument_name];
                                        if (li != null) {
                                                Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
                                                return false;
@@ -1871,6 +1969,16 @@ namespace Mono.CSharp {
                public override string DocCommentHeader {
                        get { return "M:"; }
                }
+
+               public new void VerifyClsCompliance ()
+               {
+                       foreach (TypeParameter tp in TypeParameters) {
+                               if (tp.Constraints == null)
+                                       continue;
+
+                               tp.Constraints.VerifyClsCompliance ();
+                       }
+               }
        }
 
        public class DefaultValueExpression : Expression
@@ -1891,20 +1999,44 @@ namespace Mono.CSharp {
 
                        type = texpr.Type;
 
+                       if (type == TypeManager.void_type) {
+                               Error_VoidInvalidInTheContext (loc);
+                               return null;
+                       }
+
+                       if (type.IsGenericParameter)
+                       {
+                               GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
+                               if (constraints != null && constraints.IsReferenceType)
+                                       return new NullDefault (new NullLiteral (Location), type);
+                       }
+                       else
+                       {
+                               Constant c = New.Constantify(type);
+                               if (c != null)
+                                       return new NullDefault (c, type);
+
+                               if (!TypeManager.IsValueType (type))
+                                       return new NullDefault (new NullLiteral (Location), type);
+                       }
                        eclass = ExprClass.Variable;
                        return this;
                }
 
                public override void Emit (EmitContext ec)
                {
-                       if (type.IsGenericParameter || TypeManager.IsValueType (type)) {
-                               LocalTemporary temp_storage = new LocalTemporary (type);
+                       LocalTemporary temp_storage = new LocalTemporary(type);
 
-                               temp_storage.AddressOf (ec, AddressOp.LoadStore);
-                               ec.ig.Emit (OpCodes.Initobj, type);
-                               temp_storage.Emit (ec);
-                       } else
-                               ec.ig.Emit (OpCodes.Ldnull);
+                       temp_storage.AddressOf(ec, AddressOp.LoadStore);
+                       ec.ig.Emit(OpCodes.Initobj, type);
+                       temp_storage.Emit(ec);
+               }
+               
+               protected override void CloneTo (CloneContext clonectx, Expression t)
+               {
+                       DefaultValueExpression target = (DefaultValueExpression) t;
+                       
+                       target.expr = expr.Clone (clonectx);
                }
        }
 
@@ -1954,26 +2086,11 @@ namespace Mono.CSharp {
                static public Type generic_ienumerable_type;
                static public Type generic_nullable_type;
 
-               // <remarks>
-               //   Tracks the generic parameters.
-               // </remarks>
-               static PtrHashtable builder_to_type_param;
-
                //
                // These methods are called by code generated by the compiler
                //
                static public MethodInfo activator_create_instance;
 
-               static void InitGenerics ()
-               {
-                       builder_to_type_param = new PtrHashtable ();
-               }
-
-               static void CleanUpGenerics ()
-               {
-                       builder_to_type_param = null;
-               }
-
                static void InitGenericCoreTypes ()
                {
                        activator_type = CoreLookupType ("System", "Activator");
@@ -1993,9 +2110,8 @@ namespace Mono.CSharp {
                static void InitGenericCodeHelpers ()
                {
                        // Activator
-                       Type [] type_arg = { type_type };
                        activator_create_instance = GetMethod (
-                               activator_type, "CreateInstance", type_arg);
+                               activator_type, "CreateInstance", Type.EmptyTypes);
                }
 
                static Type CoreLookupType (string ns, string name, int arity)
@@ -2003,23 +2119,12 @@ namespace Mono.CSharp {
                        return CoreLookupType (ns, MemberName.MakeName (name, arity));
                }
 
-               public static void AddTypeParameter (Type t, TypeParameter tparam)
-               {
-                       if (!builder_to_type_param.Contains (t))
-                               builder_to_type_param.Add (t, tparam);
-               }
-
                public static TypeContainer LookupGenericTypeContainer (Type t)
                {
                        t = DropGenericTypeArguments (t);
                        return LookupTypeContainer (t);
                }
 
-               public static TypeParameter LookupTypeParameter (Type t)
-               {
-                       return (TypeParameter) builder_to_type_param [t];
-               }
-
                public static GenericConstraints GetTypeParameterConstraints (Type t)
                {
                        if (!t.IsGenericParameter)
@@ -2032,161 +2137,12 @@ namespace Mono.CSharp {
                        return ReflectionConstraints.GetConstraints (t);
                }
 
-               public static bool HasGenericArguments (Type t)
-               {
-                       return GetNumberOfTypeArguments (t) > 0;
-               }
-
-               public static int GetNumberOfTypeArguments (Type t)
-               {
-                       if (t.IsGenericParameter)
-                               return 0;
-                       DeclSpace tc = LookupDeclSpace (t);
-                       if (tc != null)
-                               return tc.IsGeneric ? tc.CountTypeParameters : 0;
-                       else
-                               return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
-               }
-
-               public static Type[] GetTypeArguments (Type t)
-               {
-                       DeclSpace tc = LookupDeclSpace (t);
-                       if (tc != null) {
-                               if (!tc.IsGeneric)
-                                       return Type.EmptyTypes;
-
-                               TypeParameter[] tparam = tc.TypeParameters;
-                               Type[] ret = new Type [tparam.Length];
-                               for (int i = 0; i < tparam.Length; i++) {
-                                       ret [i] = tparam [i].Type;
-                                       if (ret [i] == null)
-                                               throw new InternalErrorException ();
-                               }
-
-                               return ret;
-                       } else
-                               return t.GetGenericArguments ();
-               }
-
-               public static Type DropGenericTypeArguments (Type t)
-               {
-                       if (!t.IsGenericType)
-                               return t;
-                       // Micro-optimization: a generic typebuilder is always a generic type definition
-                       if (t is TypeBuilder)
-                               return t;
-                       return t.GetGenericTypeDefinition ();
-               }
-
-               public static MethodBase DropGenericMethodArguments (MethodBase m)
-               {
-                       if (m.IsGenericMethodDefinition)
-                               return m;
-                       if (m.IsGenericMethod)
-                               return ((MethodInfo) m).GetGenericMethodDefinition ();
-                       if (!m.DeclaringType.IsGenericType)
-                               return m;
-
-                       Type t = m.DeclaringType.GetGenericTypeDefinition ();
-                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
-                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-                       if (m is ConstructorInfo) {
-                               foreach (ConstructorInfo c in t.GetConstructors (bf))
-                                       if (c.MetadataToken == m.MetadataToken)
-                                               return c;
-                       } else {
-                               foreach (MethodBase mb in t.GetMethods (bf))
-                                       if (mb.MetadataToken == m.MetadataToken)
-                                               return mb;
-                       }
-
-                       return m;
-               }
-
-               public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
-               {
-                       if (fi.DeclaringType.IsGenericTypeDefinition ||
-                           !fi.DeclaringType.IsGenericType)
-                               return fi;
-
-                       Type t = fi.DeclaringType.GetGenericTypeDefinition ();
-                       BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
-                               BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-                       foreach (FieldInfo f in t.GetFields (bf))
-                               if (f.MetadataToken == fi.MetadataToken)
-                                       return f;
-
-                       return fi;
-               }
-
-               public static bool IsEqual (Type a, Type b)
-               {
-                       if (a.Equals (b))
-                               return true;
-
-                       if (a.IsGenericParameter && b.IsGenericParameter) {
-                               if (a.DeclaringMethod != b.DeclaringMethod &&
-                                   (a.DeclaringMethod == null || b.DeclaringMethod == null))
-                                       return false;
-                               return a.GenericParameterPosition == b.GenericParameterPosition;
-                       }
-
-                       if (a.IsArray && b.IsArray) {
-                               if (a.GetArrayRank () != b.GetArrayRank ())
-                                       return false;
-                               return IsEqual (a.GetElementType (), b.GetElementType ());
-                       }
-
-                       if (a.IsByRef && b.IsByRef)
-                               return IsEqual (a.GetElementType (), b.GetElementType ());
-
-                       if (a.IsGenericType && b.IsGenericType) {
-                               if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
-                                       return false;
-
-                               Type[] aargs = a.GetGenericArguments ();
-                               Type[] bargs = b.GetGenericArguments ();
-
-                               if (aargs.Length != bargs.Length)
-                                       return false;
-
-                               for (int i = 0; i < aargs.Length; i++) {
-                                       if (!IsEqual (aargs [i], bargs [i]))
-                                               return false;
-                               }
-
-                               return true;
-                       }
-
-                       //
-                       // This is to build with the broken circular dependencies between
-                       // System and System.Configuration in the 2.x profile where we
-                       // end up with a situation where:
-                       //
-                       // System on the second build is referencing the System.Configuration
-                       // that has references to the first System build.
-                       //
-                       // Point in case: NameValueCollection built on the first pass, vs
-                       // NameValueCollection build on the second one.  The problem is that
-                       // we need to override some methods sometimes, or we need to 
-                       //
-                       if (RootContext.BrokenCircularDeps){
-                               if (a.Name == b.Name && a.Namespace == b.Namespace){
-                                       Console.WriteLine ("GonziMatch: {0}.{1}", a.Namespace, a.Name);
-                                       return true;
-                               }
-                       }
-                       return false;
-               }
-
                /// <summary>
                ///   Check whether `a' and `b' may become equal generic types.
                ///   The algorithm to do that is a little bit complicated.
                /// </summary>
-               public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
-                                                              Type[] method_infered)
+               public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
+                                                              Type[] method_inferred)
                {
                        if (a.IsGenericParameter) {
                                //
@@ -2208,7 +2164,7 @@ namespace Mono.CSharp {
                                // 
                                if (b.IsGenericParameter || !b.IsGenericType) {
                                        int pos = a.GenericParameterPosition;
-                                       Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
+                                       Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
                                        if (args [pos] == null) {
                                                args [pos] = b;
                                                return true;
@@ -2240,7 +2196,7 @@ namespace Mono.CSharp {
                        }
 
                        if (b.IsGenericParameter)
-                               return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
+                               return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
 
                        //
                        // At this point, neither a nor b are a type parameter.
@@ -2252,7 +2208,7 @@ namespace Mono.CSharp {
                        //
 
                        if (a.IsGenericType || b.IsGenericType)
-                               return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
+                               return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
 
                        //
                        // If both of them are arrays.
@@ -2265,7 +2221,7 @@ namespace Mono.CSharp {
                                a = a.GetElementType ();
                                b = b.GetElementType ();
 
-                               return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
+                               return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
                        }
 
                        //
@@ -2280,8 +2236,8 @@ namespace Mono.CSharp {
                // particular instantiation (26.3.1).
                //
                public static bool MayBecomeEqualGenericInstances (Type a, Type b,
-                                                                  Type[] class_infered,
-                                                                  Type[] method_infered)
+                                                                  Type[] class_inferred,
+                                                                  Type[] method_inferred)
                {
                        if (!a.IsGenericType || !b.IsGenericType)
                                return false;
@@ -2289,18 +2245,18 @@ namespace Mono.CSharp {
                                return false;
 
                        return MayBecomeEqualGenericInstances (
-                               GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
+                               GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
                }
 
                public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
-                                                                  Type[] class_infered,
-                                                                  Type[] method_infered)
+                                                                  Type[] class_inferred,
+                                                                  Type[] method_inferred)
                {
                        if (aargs.Length != bargs.Length)
                                return false;
 
                        for (int i = 0; i < aargs.Length; i++) {
-                               if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
+                               if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
                                        return false;
                        }
 
@@ -2308,81 +2264,230 @@ namespace Mono.CSharp {
                }
 
                /// <summary>
-               ///   Check whether `type' and `parent' are both instantiations of the same
-               ///   generic type.  Note that we do not check the type parameters here.
+               ///   Type inference.  Try to infer the type arguments from the params method
+               ///   `method', which is invoked with the arguments `arguments'.  This is used
+               ///   when resolving an Invocation or a DelegateInvocation and the user
+               ///   did not explicitly specify type arguments.
                /// </summary>
-               public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
+               public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
+                                                            ref MethodBase method)
                {
-                       int tcount = GetNumberOfTypeArguments (type);
-                       int pcount = GetNumberOfTypeArguments (parent);
+                       if (!TypeManager.IsGenericMethod (method))
+                               return true;
+
+                       // if there are no arguments, there's no way to infer the type-arguments
+                       if (arguments == null || arguments.Count == 0)
+                               return false;
+
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       int pd_count = pd.Count;
+                       int arg_count = arguments.Count;
+
+                       if (pd_count == 0)
+                               return false;
+
+                       if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
+                               return false;
 
-                       if (tcount != pcount)
+                       if (pd_count - 1 > arg_count)
                                return false;
 
-                       type = DropGenericTypeArguments (type);
-                       parent = DropGenericTypeArguments (parent);
+                       Type[] method_args = method.GetGenericArguments ();
+                       Type[] inferred_types = new Type [method_args.Length];
 
-                       return type.Equals (parent);
-               }
+                       //
+                       // If we have come this far, the case which
+                       // remains is when the number of parameters is
+                       // less than or equal to the argument count.
+                       //
+                       for (int i = 0; i < pd_count - 1; ++i) {
+                               Argument a = (Argument) arguments [i];
+
+                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                                       continue;
+
+                               Type pt = pd.ParameterType (i);
+                               Type at = a.Type;
+
+                               if (!TypeInferenceV2.UnifyType (pt, at, inferred_types))
+                                       return false;
+                       }
+
+                       Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
+
+                       for (int i = pd_count - 1; i < arg_count; i++) {
+                               Argument a = (Argument) arguments [i];
+
+                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                                       continue;
+
+                               if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
+                                       return false;
+                       }
+
+                       for (int i = 0; i < inferred_types.Length; i++)
+                               if (inferred_types [i] == null)
+                                       return false;
 
+                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
+                       return true;
+               }
+       
                /// <summary>
-               ///   Whether `mb' is a generic method definition.
+               ///   Type inference.  Try to infer the type arguments from `method',
+               ///   which is invoked with the arguments `arguments'.  This is used
+               ///   when resolving an Invocation or a DelegateInvocation and the user
+               ///   did not explicitly specify type arguments.
                /// </summary>
-               public static bool IsGenericMethodDefinition (MethodBase mb)
+               public static bool InferTypeArguments (EmitContext ec,
+                                                      ArrayList arguments,
+                                                      ref MethodBase method)
                {
-                       if (mb.DeclaringType is TypeBuilder) {
-                               IMethodData method = (IMethodData) builder_to_method [mb];
-                               if (method == null)
-                                       return false;
+                       if (!TypeManager.IsGenericMethod (method))
+                               return true;
 
-                               return method.GenericMethod != null;
-                       }
+                       ATypeInference ti = ATypeInference.CreateInstance (arguments);
+                       Type[] i_args = ti.InferMethodArguments (ec, method);
+                       if (i_args == null)
+                               return false;
 
-                       return mb.IsGenericMethodDefinition;
+                       method = ((MethodInfo) method).MakeGenericMethod (i_args);
+                       return true;
                }
 
                /// <summary>
-               ///   Whether `mb' is a generic method definition.
+               ///   Type inference.
                /// </summary>
-               public static bool IsGenericMethod (MethodBase mb)
+               public static bool InferTypeArguments (ParameterData apd,
+                                                      ref MethodBase method)
                {
-                       if (mb.DeclaringType is TypeBuilder) {
-                               IMethodData method = (IMethodData) builder_to_method [mb];
-                               if (method == null)
-                                       return false;
+                       if (!TypeManager.IsGenericMethod (method))
+                               return true;
 
-                               return method.GenericMethod != null;
-                       }
+                       ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
+                       Type[] i_args = ti.InferDelegateArguments (method);
+                       if (i_args == null)
+                               return false;
 
-                       return mb.IsGenericMethod;
+                       method = ((MethodInfo) method).MakeGenericMethod (i_args);
+                       return true;
                }
+       }
 
-               //
-               // Type inference.
-               //
+       abstract class ATypeInference
+       {
+               protected readonly ArrayList arguments;
+               protected readonly int arg_count;
 
-               static bool InferType (Type pt, Type at, Type[] infered)
+               protected ATypeInference (ArrayList arguments)
                {
-                       if (pt.IsGenericParameter) {
-                               if (pt.DeclaringMethod == null)
-                                       return pt == at;
+                       this.arguments = arguments;
+                       if (arguments != null)
+                               arg_count = arguments.Count;
+               }
 
-                               int pos = pt.GenericParameterPosition;
+               public static ATypeInference CreateInstance (ArrayList arguments)
+               {
+                       if (RootContext.Version == LanguageVersion.LINQ)
+                               return new TypeInferenceV3 (arguments);
 
-                               if (infered [pos] == null) {
-                                       infered [pos] = at;
-                                       return true;
-                               }
+                       return new TypeInferenceV2 (arguments);
+               }
+
+               public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
+               public abstract Type[] InferDelegateArguments (MethodBase method);
+       }
+
+       //
+       // Implements C# 2.0 type inference
+       //
+       class TypeInferenceV2 : ATypeInference
+       {
+               public TypeInferenceV2 (ArrayList arguments)
+                       : base (arguments)
+               {
+               }
+
+               public override Type[] InferDelegateArguments (MethodBase method)
+               {
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       if (arg_count != pd.Count)
+                               return null;
+
+                       Type[] method_args = method.GetGenericArguments ();
+                       Type[] inferred_types = new Type[method_args.Length];
+
+                       Type[] param_types = new Type[pd.Count];
+                       Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
+
+                       for (int i = 0; i < arg_count; i++) {
+                               param_types[i] = pd.ParameterType (i);
+                       }
+
+                       if (!InferTypeArguments (param_types, arg_types, inferred_types))
+                               return null;
+
+                       return inferred_types;
+               }
+
+               public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
+               {
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       if (arg_count != pd.Count)
+                               return null;
+
+                       Type[] method_generic_args = method.GetGenericArguments ();
+                       Type[] arg_types = new Type[pd.Count];
+                       for (int i = 0; i < arg_count; i++) {
+                               Argument a = (Argument) arguments[i];
+                               if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
+                                       continue;
+
+                               arg_types[i] = a.Type;
+                       }
+
+                       Type[] inferred_types = new Type [method_generic_args.Length];
+                       if (!InferTypeArguments (pd.Types, arg_types, inferred_types))
+                               return null;
+
+                       return inferred_types;
+               }
+
+               static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
+                               Type[] inferred_types)
+               {
+                       for (int i = 0; i < arg_types.Length; i++) {
+                               if (arg_types[i] == null)
+                                       continue;
 
-                               if (infered [pos] != at)
+                               if (!UnifyType (param_types[i], arg_types[i], inferred_types))
                                        return false;
+                       }
 
-                               return true;
+                       for (int i = 0; i < inferred_types.Length; ++i)
+                               if (inferred_types[i] == null)
+                                       return false;
+
+                       return true;
+               }
+
+               public static bool UnifyType (Type pt, Type at, Type[] inferred)
+               {
+                       if (pt.IsGenericParameter) {
+                               if (pt.DeclaringMethod == null)
+                                       return pt == at;
+
+                               int pos = pt.GenericParameterPosition;
+
+                               if (inferred [pos] == null)
+                                       inferred [pos] = at;
+
+                               return inferred [pos] == at;
                        }
 
                        if (!pt.ContainsGenericParameters) {
                                if (at.ContainsGenericParameters)
-                                       return InferType (at, pt, infered);
+                                       return UnifyType (at, pt, inferred);
                                else
                                        return true;
                        }
@@ -2392,31 +2497,31 @@ namespace Mono.CSharp {
                                        if (at.GetArrayRank () != pt.GetArrayRank ())
                                                return false;
 
-                                       return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                                       return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
                                }
 
                                if (!pt.IsGenericType)
                                        return false;
 
                                Type gt = pt.GetGenericTypeDefinition ();
-                               if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
-                                   (gt != generic_ienumerable_type))
+                               if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
+                                       (gt != TypeManager.generic_ienumerable_type))
                                        return false;
 
-                               Type[] args = GetTypeArguments (pt);
-                               return InferType (args [0], at.GetElementType (), infered);
+                               Type[] args = TypeManager.GetTypeArguments (pt);
+                               return UnifyType (args[0], at.GetElementType (), inferred);
                        }
 
                        if (pt.IsArray) {
                                if (!at.IsArray ||
-                                   (pt.GetArrayRank () != at.GetArrayRank ()))
+                                       (pt.GetArrayRank () != at.GetArrayRank ()))
                                        return false;
 
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
                        }
 
                        if (pt.IsByRef && at.IsByRef)
-                               return InferType (pt.GetElementType (), at.GetElementType (), infered);
+                               return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
                        ArrayList list = new ArrayList ();
                        if (at.IsGenericType)
                                list.Add (at);
@@ -2425,254 +2530,535 @@ namespace Mono.CSharp {
 
                        list.AddRange (TypeManager.GetInterfaces (at));
 
-                       bool found_one = false;
-
                        foreach (Type type in list) {
                                if (!type.IsGenericType)
                                        continue;
 
-                               Type[] infered_types = new Type [infered.Length];
-
-                               if (!InferGenericInstance (pt, type, infered_types))
+                               if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
                                        continue;
 
-                               for (int i = 0; i < infered_types.Length; i++) {
-                                       if (infered [i] == null) {
-                                               infered [i] = infered_types [i];
-                                               continue;
-                                       }
+                               if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
+                                       return false;
+                       }
 
-                                       if (infered [i] != infered_types [i])
-                                               return false;
-                               }
+                       return true;
+               }
 
-                               found_one = true;
+               static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
+               {
+                       for (int i = 0; i < ats.Length; i++) {
+                               if (!UnifyType (pts [i], ats [i], inferred))
+                                       return false;
                        }
+                       return true;
+               }
+       }
 
-                       return found_one;
+       //
+       // Implements C# 3.0 type inference
+       //
+       class TypeInferenceV3 : ATypeInference
+       {
+               public TypeInferenceV3 (ArrayList arguments)
+                       : base (arguments)
+               {
                }
 
-               static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
+               public override Type[] InferDelegateArguments (MethodBase method)
                {
-                       Type[] at_args = at.GetGenericArguments ();
-                       Type[] pt_args = pt.GetGenericArguments ();
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       if (arg_count != pd.Count)
+                               return null;
 
-                       if (at_args.Length != pt_args.Length)
-                               return false;
+                       Type[] d_gargs = method.GetGenericArguments ();
+                       TypeInferenceContext context = new TypeInferenceContext (d_gargs);
 
-                       for (int i = 0; i < at_args.Length; i++) {
-                               if (!InferType (pt_args [i], at_args [i], infered_types))
-                                       return false;
-                       }
+                       // 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;
 
-                       for (int i = 0; i < infered_types.Length; i++) {
-                               if (infered_types [i] == null)
-                                       return false;
+                               context.LowerBoundInference ((Type)arguments[i], t);
                        }
 
-                       return true;
+                       if (!context.FixAllTypes ())
+                               return null;
+
+                       return context.InferredTypeArguments;
                }
 
-               /// <summary>
-               ///   Type inference.  Try to infer the type arguments from the params method
-               ///   `method', which is invoked with the arguments `arguments'.  This is used
-               ///   when resolving an Invocation or a DelegateInvocation and the user
-               ///   did not explicitly specify type arguments.
-               /// </summary>
-               public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
-                                                            ref MethodBase method)
+               public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       if (arg_count != pd.Count)
+                               return null;
 
-                       // if there are no arguments, there's no way to infer the type-arguments
-                       if (arguments == null || arguments.Count == 0)
-                               return false;
+                       Type[] method_generic_args = method.GetGenericArguments ();
+                       TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
+                       if (!InferInPhases (ec, context, pd))
+                               return null;
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       int pd_count = pd.Count;
-                       int arg_count = arguments.Count;
+                       return context.InferredTypeArguments;
+               }
 
-                       if (pd_count == 0)
-                               return false;
+               //
+               // Implements method type arguments inference
+               //
+               bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
+               {
+                       //
+                       // The first inference phase
+                       //
+                       for (int i = 0; i < arg_count; i++) {
+                               Type method_parameter = methodParameters.ParameterType (i);
 
-                       if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
-                               return false;
+                               Argument a = (Argument) arguments[i];
 
-                       if (pd_count - 1 > arg_count)
-                               return false;
+                               //
+                               // When a lambda expression, an anonymous method
+                               // is used an explicit argument type inference takes a place
+                               //
+                               AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
+                               if (am != null) {
+                                       am.ExplicitTypeInference (tic, method_parameter);
+                                       continue;
+                               }
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                               if (a.Expr.Type == TypeManager.null_type)
+                                       continue;
+
+                               //
+                               // Otherwise an output type inference is made
+                               //
+                               tic.OutputTypeInference (ec, a.Expr, method_parameter);
+                       }
 
                        //
-                       // If we have come this far, the case which
-                       // remains is when the number of parameters is
-                       // less than or equal to the argument count.
+                       // Part of the second phase but because it happens only once
+                       // we don't need to call it in cycle
                        //
-                       for (int i = 0; i < pd_count - 1; ++i) {
-                               Argument a = (Argument) arguments [i];
+                       bool fixed_any = false;
+                       if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
+                               return false;
 
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                       return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
+               }
+
+               bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
+               {
+                       bool fixed_any = false;
+                       if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
+                               return false;
+
+                       // If no further unfixed type variables exist, type inference succeeds
+                       if (!tic.UnfixedVariableExists)
+                               return true;
+
+                       if (!fixed_any && fixDependent)
+                               return false;
+
+                       // For all arguments where the corresponding argument output types
+                       // contain unfixed type variables but the input types do not,
+                       // an output type inference is made
+                       for (int i = 0; i < arg_count; i++) {
+                               Type t_i = methodParameters.ParameterType (i);
+                               if (!TypeManager.IsDelegateType (t_i))
                                        continue;
 
-                               Type pt = pd.ParameterType (i);
-                               Type at = a.Type;
+                               MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
+                               Type rtype = mi.ReturnType;
 
-                               if (!InferType (pt, at, infered_types))
-                                       return false;
+#if MS_COMPATIBLE
+                               // Blablabla, because reflection does not work with dynamic types
+                               Type[] g_args = t_i.GetGenericArguments ();
+                               rtype = g_args[rtype.GenericParameterPosition];
+#endif
+
+                               bool all_params_fixed = false;
+                               if (rtype.IsGenericParameter) {
+                                       all_params_fixed = tic.IsTypeNonDependent (mi, rtype);
+                               } else if (rtype.IsGenericType) {
+                                       all_params_fixed = true;
+                                       foreach (Type t in rtype.GetGenericArguments ())
+                                               if (!tic.IsTypeNonDependent (mi, t)) {
+                                                       all_params_fixed = false;
+                                                       break;
+                                               }
+                               }
+
+                               if (all_params_fixed)
+                                       tic.OutputTypeInference (ec, ((Argument) arguments[i]).Expr, t_i);
                        }
 
-                       Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
 
-                       for (int i = pd_count - 1; i < arg_count; i++) {
-                               Argument a = (Argument) arguments [i];
+                       return DoSecondPhase (ec, tic, methodParameters, true);
+               }
+       }
 
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
-                                       continue;
+       public class TypeInferenceContext
+       {
+               readonly Type[] unfixed_types;
+               readonly Type[] fixed_types;
+               readonly ArrayList[] bounds;
 
-                               if (!InferType (element_type, a.Type, infered_types))
-                                       return false;
+               public TypeInferenceContext (Type[] typeArguments)
+               {
+                       if (typeArguments.Length == 0)
+                               throw new ArgumentException ("Empty generic arguments");
+
+                       unfixed_types = new Type[typeArguments.Length];
+                       Array.Copy (typeArguments, unfixed_types, unfixed_types.Length);
+                       bounds = new ArrayList[typeArguments.Length];
+                       fixed_types = new Type[typeArguments.Length];
+               }
+
+               public Type[] InferredTypeArguments {
+                       get {
+                               return fixed_types;
                        }
+               }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
-                                       return false;
+               void AddToBounds (Type t, int index)
+               {
+                       ArrayList a = bounds[index];
+                       if (a == null) {
+                               a = new ArrayList ();
+                               a.Add (t);
+                               bounds[index] = a;
+                               return;
+                       }
 
-                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
-                       return true;
+                       if (a.Contains (t))
+                               return;
+
+                       a.Add (t);
                }
 
-               static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
-                                               Type[] infered_types)
+               //
+               // 26.3.3.8 Exact Inference
+               //
+               public void ExactInference (Type u, Type v)
                {
-                       if (infered_types == null)
-                               return false;
+                       // If V is an array type
+                       if (v.IsArray) {
+                               if (!u.IsArray)
+                                       return;
 
-                       for (int i = 0; i < arg_types.Length; i++) {
-                               if (arg_types [i] == null)
-                                       continue;
+                               if (u.GetArrayRank () != v.GetArrayRank ())
+                                       return;
 
-                               if (!InferType (param_types [i], arg_types [i], infered_types))
-                                       return false;
+                               ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
+                               return;
                        }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
+                       // If V is constructed type and U is constructed type
+                       if (v.IsGenericType && !v.IsGenericTypeDefinition) {
+                               if (!u.IsGenericType)
+                                       return;
+
+                               Type [] ga_u = u.GetGenericArguments ();
+                               Type [] ga_v = v.GetGenericArguments ();
+                               if (ga_u.Length != ga_v.Length)
+                                       return;
+
+                               for (int i = 0; i < ga_u.Length; ++i)
+                                       ExactInference (ga_u [i], ga_v [i]);
+
+                               return;
+                       }
+
+                       // If V is one of the unfixed type arguments
+                       int pos = IsUnfixed (v);
+                       if (pos == -1)
+                               return;
+
+                       AddToBounds (u, pos);
+               }
+
+               public bool FixAllTypes ()
+               {
+                       for (int i = 0; i < unfixed_types.Length; ++i) {
+                               if (!FixType (i))
                                        return false;
+                       }
+                       return true;
+               }
+
+               //
+               // All unfixed type variables Xi are fixed for which all of the following hold:
+               // a, There is at least one type variable Xj that depends on Xi
+               // b, Xi has a non-empty set of bounds
+               // 
+               public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
+               {
+                       for (int i = 0; i < unfixed_types.Length; ++i) {
+                               if (unfixed_types[i] == null)
+                                       continue;
 
+                               if (bounds[i] == null)
+                                       continue;
+
+                               if (!FixType (i))
+                                       return false;
+                               fixed_any = true;
+                       }
                        return true;
                }
 
-               /// <summary>
-               ///   Type inference.  Try to infer the type arguments from `method',
-               ///   which is invoked with the arguments `arguments'.  This is used
-               ///   when resolving an Invocation or a DelegateInvocation and the user
-               ///   did not explicitly specify type arguments.
-               /// </summary>
-               public static bool InferTypeArguments (ArrayList arguments,
-                                                      ref MethodBase method)
+               //
+               // All unfixed type variables Xi which depend on no Xj are fixed
+               //
+               public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       ArrayList types_to_fix = new ArrayList (unfixed_types);
+                       foreach (Type t in methodParameters.Types) {
+                               if (t.IsGenericParameter)
+                                       continue;
 
-                       int arg_count;
-                       if (arguments != null)
-                               arg_count = arguments.Count;
-                       else
-                               arg_count = 0;
+                               if (!TypeManager.IsDelegateType (t))
+                                       continue;
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       if (arg_count != pd.Count)
-                               return false;
+                               MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
+                               Type rtype = invoke.ReturnType;
+                               if (!rtype.IsGenericParameter && !rtype.IsGenericType)
+                                       continue;
 
-                       Type[] method_args = method.GetGenericArguments ();
+#if MS_COMPATIBLE
+                               // Blablabla, because reflection does not work with dynamic types
+                               Type [] g_args = t.GetGenericArguments ();
+                               if (!rtype.IsGenericParameter)
+                                       continue;
+
+                               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) {
+                               if (t == null)
+                                       continue;
 
-                       bool is_open = false;
-                       for (int i = 0; i < method_args.Length; i++) {
-                               if (method_args [i].IsGenericParameter) {
-                                       is_open = true;
-                                       break;
+                               if (!FixType (IsUnfixed (t))) {
+                                       return false;
                                }
                        }
 
-                       // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
-                       if (!is_open)
-                               return !TypeManager.IsGenericMethodDefinition (method);
+                       fixed_any = types_to_fix.Count > 0;
+                       return true;
+               }
 
-                       Type[] infered_types = new Type [method_args.Length];
+               //
+               // 26.3.3.10 Fixing
+               //
+               public bool FixType (int i)
+               {
+                       // It's already fixed
+                       if (unfixed_types[i] == null)
+                               throw new InternalErrorException ("Type argument has been already fixed");
 
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+                       ArrayList candidates = (ArrayList)bounds [i];
+                       if (candidates == null)
+                               return false;
 
-                       for (int i = 0; i < arg_count; i++) {
-                               param_types [i] = pd.ParameterType (i);
+                       if (candidates.Count == 1) {
+                               unfixed_types[i] = null;
+                               fixed_types[i] = (Type)candidates[0];
+                               return true;
+                       }
 
-                               Argument a = (Argument) arguments [i];
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
-                                   (a.Expr is AnonymousMethodExpression))
+                       // TODO: Review, I think it is still wrong
+                       Type best_candidate = null;
+                       for (int ci = 0; ci < candidates.Count; ++ci) {
+                               TypeExpr candidate = new TypeExpression ((Type)candidates[ci], Location.Null);
+                               bool failed = false;
+                               for (int cii = 0; cii < candidates.Count; ++cii) {
+                                       if (cii == ci)
+                                               continue;
+
+                                       if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
+                                               failed = true;
+                                       }
+                               }
+
+                               if (failed)
                                        continue;
 
-                               arg_types [i] = a.Type;
+                               if (best_candidate != null)
+                                       return false;
+
+                               best_candidate = candidate.Type;
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, infered_types))
+                       if (best_candidate == null)
                                return false;
 
-                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
+                       unfixed_types[i] = null;
+                       fixed_types[i] = best_candidate;
                        return true;
                }
 
-               /// <summary>
-               ///   Type inference.
-               /// </summary>
-               public static bool InferTypeArguments (ParameterData apd,
-                                                      ref MethodBase method)
+               public bool IsTypeNonDependent (MethodInfo mi, Type type)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
-
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       if (apd.Count != pd.Count)
+                       if (IsUnfixed (type) < 0)
                                return false;
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
-
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+                       ParameterData d_parameters = TypeManager.GetParameterData (mi);
+                       foreach (Type t in d_parameters.Types) {
+                               if (!t.IsGenericParameter)
+                                       continue;
 
-                       for (int i = 0; i < apd.Count; i++) {
-                               param_types [i] = pd.ParameterType (i);
-                               arg_types [i] = apd.ParameterType (i);
+                               if (IsUnfixed (t) >= 0)
+                                       return false;
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, infered_types))
-                               return false;
-
-                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
                        return true;
                }
 
-               public static bool IsNullableType (Type t)
+               public int IsUnfixed (Type type)
                {
-                       return generic_nullable_type == DropGenericTypeArguments (t);
+                       if (!type.IsGenericParameter)
+                               return -1;
+
+                       //return unfixed_types[type.GenericParameterPosition] != null;
+                       for (int i = 0; i < unfixed_types.Length; ++i) {
+                               if (unfixed_types [i] == type)
+                                       return i;
+                       }
+
+                       return -1;
                }
 
-               public static bool IsNullableTypeOf (Type t, Type nullable)
+               //
+               // 26.3.3.9 Lower-bound Inference
+               //
+               public void LowerBoundInference (Type u, Type v)
                {
-                       if (!IsNullableType (t))
-                               return false;
+                       // If U is an array type
+                       if (u.IsArray) {
+                               int u_dim = u.GetArrayRank ();
+                               Type v_e;
+                               Type u_e = TypeManager.GetElementType (u);
+
+                               if (v.IsArray) {
+                                       if (u_dim != v.GetArrayRank ())
+                                               return;
+
+                                       v_e = TypeManager.GetElementType (v);
+
+                                       if (u.IsByRef) {
+                                               LowerBoundInference (u_e, v_e);
+                                               return;
+                                       }
+                                       ExactInference (u_e, v_e);
+                                       return;
+                               }
+
+                               if (u_dim != 1)
+                                       return;
+
+                               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))
+                                               return;
+
+                                       v_e = TypeManager.GetTypeArguments (v)[0];
+
+                                       if (u.IsByRef) {
+                                               LowerBoundInference (u_e, v_e);
+                                               return;
+                                       }
+                                       ExactInference (u_e, v_e);
+                                       return;
+                               }
+                       // If V is a constructed type C<V1..Vk>
+                       } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
+                               Type[] ga_u = u.GetGenericArguments ();
+                               Type[] ga_v = v.GetGenericArguments ();
+                               if (ga_u.Length != ga_v.Length)
+                                       return;
+
+                               v = v.GetGenericTypeDefinition ().MakeGenericType (ga_u);
+
+                               // And standard implicit conversion exists from U to C<U1..Uk>
+                               if (!Convert.ImplicitStandardConversionExists (new TypeExpression (u, Location.Null), v))
+                                       return;
+
+                               for (int i = 0; i < ga_u.Length; ++i)
+                                       ExactInference (ga_u[i], ga_v[i]);
+
+                               return;
+                       }
+
+                       // Remove ref, out modifiers
+                       if (v.HasElementType)
+                               v = v.GetElementType ();
+
+                       // If V is one of the unfixed type arguments
+                       int pos = IsUnfixed (v);
+                       if (pos == -1)
+                               return;
 
-                       return GetTypeArguments (t) [0] == nullable;
+                       AddToBounds (u, pos);
                }
 
-               public static bool IsNullableValueType (Type t)
+               //
+               // 26.3.3.6 Output Type Inference
+               //
+               public void OutputTypeInference (EmitContext ec, Expression e, Type 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);
+                               if (rt != null) {
+                                       MethodInfo invoke = Delegate.GetInvokeMethod (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
+                                       LowerBoundInference (rt, rtype);
+                               }
+                               return;
+                       }
+
+                       if (e is MethodGroupExpr) {
+                               throw new NotImplementedException ();
+                       }
+
+                       //
+                       // if e is an expression with type U, then
+                       // a lower-bound inference is made from U for T
+                       //
+                       LowerBoundInference (e.Type, t);
+               }
+
+               static void RemoveDependentTypes (ArrayList types, Type returnType)
                {
-                       if (!IsNullableType (t))
-                               return false;
+                       if (returnType.IsGenericParameter) {
+                               types [returnType.GenericParameterPosition] = null;
+                               return;
+                       }
 
-                       return GetTypeArguments (t) [0].IsValueType;
+                       if (returnType.IsGenericType) {
+                               foreach (Type t in returnType.GetGenericArguments ()) {
+                                       RemoveDependentTypes (types, t);
+                               }
+                       }
+               }
+
+               public bool UnfixedVariableExists {
+                       get {
+                               foreach (Type ut in unfixed_types)
+                                       if (ut != null)
+                                               return true;
+                               return false;
+                       }
                }
        }
 
@@ -3415,14 +3801,13 @@ namespace Mono.CSharp {
                                        return this;
                                }
 
-                               if (unwrap != null) {
-                                       expr = Convert.ImplicitConversion (ec, unwrap, rtype, loc);
-                                       if (expr != null) {
-                                               left = expr;
-                                               expr = right;
-                                               type = expr.Type;
-                                               return this;
-                                       }
+                               Expression left_null = unwrap != null ? unwrap : left;
+                               expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
+                               if (expr != null) {
+                                       left = expr;
+                                       expr = right;
+                                       type = rtype;
+                                       return this;
                                }
 
                                Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);