2007-08-29 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / gmcs / generic.cs
index 1ba9fb80e8d73d9918782a380cab9162f8333864..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
 //
@@ -620,10 +621,6 @@ namespace Mono.CSharp {
                        get { return constraints; }
                }
 
-               public bool HasConstructorConstraint {
-                       get { return constraints != null && constraints.HasConstructorConstraint; }
-               }
-
                public DeclSpace DeclSpace {
                        get { return decl; }
                }
@@ -930,9 +927,6 @@ namespace Mono.CSharp {
                                MemberList list = TypeManager.FindMembers (
                                        gc.ClassConstraint, mt, bf, filter, criteria);
 
-                               Report.Debug (128, "TPARAM FIND MEMBERS #1", Name, mt, bf,
-                                             filter, criteria, gc.ClassConstraint, list.Count);
-
                                members.AddRange (list);
                        }
 
@@ -1010,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) {
@@ -1142,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;
@@ -1271,9 +1271,9 @@ namespace Mono.CSharp {
                                }
 
                                atypes[i] = te.Type;
-
-                               if (te is TypeParameterExpr) {
-                                       has_type_args = true;
+                               if (te.Type.IsGenericParameter) {
+                                       if (te is TypeParameterExpr)
+                                               has_type_args = true;
                                        continue;
                                }
 
@@ -1655,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 ();
@@ -1704,7 +1704,7 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               bool HasDefaultConstructor (Type containerType, Type atype)
+               bool HasDefaultConstructor (Type atype)
                {
                        if (atype.IsAbstract)
                                return false;
@@ -1732,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,
@@ -1875,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;
@@ -2025,6 +2031,13 @@ namespace Mono.CSharp {
                        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);
+               }
        }
 
        public class NullableType : TypeExpr
@@ -2097,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)
@@ -2251,7 +2263,215 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               static bool UnifyType (Type pt, Type at, Type[] inferred)
+               /// <summary>
+               ///   Type inference.  Try to infer the type arguments from the params method
+               ///   `method', which is invoked with the arguments `arguments'.  This is used
+               ///   when resolving an Invocation or a DelegateInvocation and the user
+               ///   did not explicitly specify type arguments.
+               /// </summary>
+               public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
+                                                            ref MethodBase method)
+               {
+                       if (!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 (pd_count - 1 > arg_count)
+                               return false;
+
+                       Type[] method_args = method.GetGenericArguments ();
+                       Type[] inferred_types = new Type [method_args.Length];
+
+                       //
+                       // 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>
+               ///   Type inference.  Try to infer the type arguments from `method',
+               ///   which is invoked with the arguments `arguments'.  This is used
+               ///   when resolving an Invocation or a DelegateInvocation and the user
+               ///   did not explicitly specify type arguments.
+               /// </summary>
+               public static bool InferTypeArguments (EmitContext ec,
+                                                      ArrayList arguments,
+                                                      ref MethodBase method)
+               {
+                       if (!TypeManager.IsGenericMethod (method))
+                               return true;
+
+                       ATypeInference ti = ATypeInference.CreateInstance (arguments);
+                       Type[] i_args = ti.InferMethodArguments (ec, method);
+                       if (i_args == null)
+                               return false;
+
+                       method = ((MethodInfo) method).MakeGenericMethod (i_args);
+                       return true;
+               }
+
+               /// <summary>
+               ///   Type inference.
+               /// </summary>
+               public static bool InferTypeArguments (ParameterData apd,
+                                                      ref MethodBase method)
+               {
+                       if (!TypeManager.IsGenericMethod (method))
+                               return true;
+
+                       ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
+                       Type[] i_args = ti.InferDelegateArguments (method);
+                       if (i_args == null)
+                               return false;
+
+                       method = ((MethodInfo) method).MakeGenericMethod (i_args);
+                       return true;
+               }
+       }
+
+       abstract class ATypeInference
+       {
+               protected readonly ArrayList arguments;
+               protected readonly int arg_count;
+
+               protected ATypeInference (ArrayList arguments)
+               {
+                       this.arguments = arguments;
+                       if (arguments != null)
+                               arg_count = arguments.Count;
+               }
+
+               public static ATypeInference CreateInstance (ArrayList arguments)
+               {
+                       if (RootContext.Version == LanguageVersion.LINQ)
+                               return new TypeInferenceV3 (arguments);
+
+                       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 (!UnifyType (param_types[i], arg_types[i], inferred_types))
+                                       return false;
+                       }
+
+                       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)
@@ -2284,17 +2504,17 @@ namespace Mono.CSharp {
                                        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 UnifyType (args [0], at.GetElementType (), inferred);
+                               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 UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
@@ -2314,7 +2534,7 @@ namespace Mono.CSharp {
                                if (!type.IsGenericType)
                                        continue;
 
-                               if (DropGenericTypeArguments (pt) != DropGenericTypeArguments (type))
+                               if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
                                        continue;
 
                                if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
@@ -2324,7 +2544,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               static bool UnifyTypes (Type[] pts, Type [] ats, Type [] inferred)
+               static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
                {
                        for (int i = 0; i < ats.Length; i++) {
                                if (!UnifyType (pts [i], ats [i], inferred))
@@ -2332,304 +2552,513 @@ namespace Mono.CSharp {
                        }
                        return true;
                }
+       }
 
-               /// <summary>
-               ///   Type inference.  Try to infer the type arguments from the params method
-               ///   `method', which is invoked with the arguments `arguments'.  This is used
-               ///   when resolving an Invocation or a DelegateInvocation and the user
-               ///   did not explicitly specify type arguments.
-               /// </summary>
-               public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
-                                                            ref MethodBase method)
+       //
+       // Implements C# 3.0 type inference
+       //
+       class TypeInferenceV3 : ATypeInference
+       {
+               public TypeInferenceV3 (ArrayList arguments)
+                       : base (arguments)
                {
-                       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;
+               }
 
+               public override Type[] InferDelegateArguments (MethodBase method)
+               {
                        ParameterData pd = TypeManager.GetParameterData (method);
-                       int pd_count = pd.Count;
-                       int arg_count = arguments.Count;
+                       if (arg_count != pd.Count)
+                               return null;
 
-                       if (pd_count == 0)
-                               return false;
+                       Type[] d_gargs = method.GetGenericArguments ();
+                       TypeInferenceContext context = new TypeInferenceContext (d_gargs);
 
-                       if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
-                               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;
 
-                       if (pd_count - 1 > arg_count)
-                               return false;
+                               context.LowerBoundInference ((Type)arguments[i], t);
+                       }
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] inferred_types = new Type [method_args.Length];
+                       if (!context.FixAllTypes ())
+                               return null;
+
+                       return context.InferredTypeArguments;
+               }
 
+               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 ();
+                       TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
+                       if (!InferInPhases (ec, context, pd))
+                               return null;
+
+                       return context.InferredTypeArguments;
+               }
+
+               //
+               // Implements method type arguments inference
+               //
+               bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
+               {
                        //
-                       // 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.
+                       // The first inference phase
                        //
-                       for (int i = 0; i < pd_count - 1; ++i) {
-                               Argument a = (Argument) arguments [i];
+                       for (int i = 0; i < arg_count; i++) {
+                               Type method_parameter = methodParameters.ParameterType (i);
 
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                               Argument a = (Argument) arguments[i];
+
+                               //
+                               // 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 pt = pd.ParameterType (i);
-                               Type at = a.Type;
+                               if (a.Expr.Type == TypeManager.null_type)
+                                       continue;
 
-                               if (!UnifyType (pt, at, inferred_types))
-                                       return false;
+                               //
+                               // Otherwise an output type inference is made
+                               //
+                               tic.OutputTypeInference (ec, a.Expr, method_parameter);
                        }
 
-                       Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
+                       //
+                       // Part of the second phase but because it happens only once
+                       // we don't need to call it in cycle
+                       //
+                       bool fixed_any = false;
+                       if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
+                               return false;
 
-                       for (int i = pd_count - 1; i < arg_count; i++) {
-                               Argument a = (Argument) arguments [i];
+                       return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
+               }
 
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+               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;
 
-                               if (!UnifyType (element_type, a.Type, inferred_types))
-                                       return false;
+                               MethodInfo mi = Delegate.GetInvokeMethod (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
+
+                               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);
                        }
 
-                       for (int i = 0; i < inferred_types.Length; i++)
-                               if (inferred_types [i] == null)
-                                       return false;
 
-                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
-                       return true;
+                       return DoSecondPhase (ec, tic, methodParameters, true);
                }
+       }
 
-               static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
-                                               Type[] inferred_types)
+       public class TypeInferenceContext
+       {
+               readonly Type[] unfixed_types;
+               readonly Type[] fixed_types;
+               readonly ArrayList[] bounds;
+
+               public TypeInferenceContext (Type[] typeArguments)
                {
-                       for (int i = 0; i < arg_types.Length; i++) {
-                               if (arg_types [i] == null)
-                                       continue;
+                       if (typeArguments.Length == 0)
+                               throw new ArgumentException ("Empty generic arguments");
 
-                               if (!UnifyType (param_types [i], arg_types [i], inferred_types))
-                                       return false;
+                       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;
+                       }
+               }
+
+               void AddToBounds (Type t, int index)
+               {
+                       ArrayList a = bounds[index];
+                       if (a == null) {
+                               a = new ArrayList ();
+                               a.Add (t);
+                               bounds[index] = a;
+                               return;
                        }
 
-                       for (int i = 0; i < inferred_types.Length; i++)
-                               if (inferred_types [i] == null)
-                                       return false;
+                       if (a.Contains (t))
+                               return;
 
-                       return true;
+                       a.Add (t);
                }
 
                //
-               // Infers the remaining inferred_types from lambda expressions contained in the 
-               // invocation call.
+               // 26.3.3.8 Exact Inference
                //
-               static bool LambdaInfer (EmitContext ec, ArrayList arguments,
-                                        Type[] param_types, Type[] arg_types, Type[] inferred_types)
+               public void ExactInference (Type u, Type v)
                {
-                       int arg_count = arg_types.Length;
-                       
-                       for (int i = 0; i < arg_count; i++){
-                               Argument a = (Argument) arguments [i];
-                               
-                               LambdaExpression le = a.Expr as LambdaExpression;
-                               
-                               if (a == null)
+                       // If V is an array type
+                       if (v.IsArray) {
+                               if (!u.IsArray)
+                                       return;
+
+                               if (u.GetArrayRank () != v.GetArrayRank ())
+                                       return;
+
+                               ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
+                               return;
+                       }
+
+                       // 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;
-                               
-                               //
-                               // TODO: "The argument is a lambda expression, in
-                               // the following called L, from which no inferences
-                               // have yet been made."
-                               //
-                               
-                               //
-                               // "The corresponding parameter’s type, in the
-                               // following called P, is a delegate type with a
-                               // return type that involves one or more method type
-                               // parameters."
-                               //
-                               // 
-                               if (!TypeManager.IsDelegateType (param_types [i]))
+
+                               if (bounds[i] == null)
                                        continue;
-                               
-                               Type p_type = param_types [i];
-                               MethodGroupExpr method_group = Expression.MemberLookup (
-                                       ec.ContainerType, p_type, "Invoke", MemberTypes.Method,
-                                       Expression.AllBindingFlags, Location.Null) as MethodGroupExpr;
-                               
-                               if (method_group == null){
-                                       // This we report elsewhere as -200, but here we can ignore
+
+                               if (!FixType (i))
+                                       return false;
+                               fixed_any = true;
+                       }
+                       return true;
+               }
+
+               //
+               // All unfixed type variables Xi which depend on no Xj are fixed
+               //
+               public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
+               {
+                       ArrayList types_to_fix = new ArrayList (unfixed_types);
+                       foreach (Type t in methodParameters.Types) {
+                               if (t.IsGenericParameter)
                                        continue;
-                               }
-                               MethodInfo delegate_method = method_group.Methods [0] as MethodInfo;
-                               if (delegate_method == null){
-                                       // This should not happen.
+
+                               if (!TypeManager.IsDelegateType (t))
                                        continue;
-                               }
-                               
-                               Type return_type = delegate_method.ReturnType;
-                               if (!return_type.IsGenericParameter)
+
+                               MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
+                               Type rtype = invoke.ReturnType;
+                               if (!rtype.IsGenericParameter && !rtype.IsGenericType)
                                        continue;
-                               
-                               //
-                               // P and L have the same number of parameters, and
-                               // each parameter in P has the same modifiers as the
-                               // corresponding parameter in L, or no modifiers if
-                               // L has an implicitly typed parameter list.
-                               //
-                               ParameterData delegate_pd = TypeManager.GetParameterData (delegate_method);
-                               int delegate_pc = delegate_pd.Count;
-                               if (delegate_pc != le.Parameters.Count)
+
+#if MS_COMPATIBLE
+                               // Blablabla, because reflection does not work with dynamic types
+                               Type [] g_args = t.GetGenericArguments ();
+                               if (!rtype.IsGenericParameter)
                                        continue;
 
-#if false
-                               //FIXME
-                               if (le.HasExplicitParameters){
-                                       for (int j = 0; j < delegate_pc; j++){
-                                               if (delegate_pd.ParameterModifier [j] !=
-                                                   le.Parameters.ParameterModifier[j])
-                                                       goto do_continue;
-                                       }
-                               } else {
-                                       for (int j = 0; j < delegate_pc; j++)
-                                               if (le.Parameters.ParameterModifier [j] != Parameter.Modifier.NONE)
-                                                       goto do_continue;
-                               }
+                               rtype = g_args [rtype.GenericParameterPosition];
 #endif
-                               
-                               //
-                               // TODO: P’s parameter types involve no method type
-                               // parameters or involve only method type parameters
-                               // for which a consistent set of inferences have
-                               // already been made.
-                               //
+                               // Remove dependent types, they cannot be fixed yet
+                               RemoveDependentTypes (types_to_fix, rtype);
+                       }
 
-                               if (le.HasExplicitParameters){
-                                       //
-                                       // TODO: If L has an explicitly typed parameter
-                                       // list, when inferred types are substituted for
-                                       // method type parameters in P, each parameter in P
-                                       // has the same type as the corresponding parameter
-                                       // in L.
-                                       //
-                               } else {
-                                       //
-                                       // TODO: If L has an implicitly typed parameter
-                                       // list, when inferred types are substituted for
-                                       // method type parameters in P and the resulting
-                                       // parameter types are given to the parameters of L,
-                                       // the body of L is a valid expression or statement
-                                       // block.
+                       foreach (Type t in types_to_fix) {
+                               if (t == null)
+                                       continue;
+
+                               if (!FixType (IsUnfixed (t))) {
+                                       return false;
                                }
-                               
-                       do_continue:
-                               ;
                        }
 
+                       fixed_any = types_to_fix.Count > 0;
                        return true;
                }
-       
-               /// <summary>
-               ///   Type inference.  Try to infer the type arguments from `method',
-               ///   which is invoked with the arguments `arguments'.  This is used
-               ///   when resolving an Invocation or a DelegateInvocation and the user
-               ///   did not explicitly specify type arguments.
-               /// </summary>
-               public static bool InferTypeArguments (EmitContext ec,
-                                                      ArrayList arguments,
-                                                      ref MethodBase method)
-               {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
 
-                       int arg_count;
-                       if (arguments != null)
-                               arg_count = arguments.Count;
-                       else
-                               arg_count = 0;
+               //
+               // 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");
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       if (arg_count != pd.Count)
+                       ArrayList candidates = (ArrayList)bounds [i];
+                       if (candidates == null)
                                return false;
 
-                       Type[] method_args = method.GetGenericArguments ();
+                       if (candidates.Count == 1) {
+                               unfixed_types[i] = null;
+                               fixed_types[i] = (Type)candidates[0];
+                               return true;
+                       }
+
+                       // 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;
 
-                       bool is_open = false;
-                       for (int i = 0; i < method_args.Length; i++) {
-                               if (method_args [i].IsGenericParameter) {
-                                       is_open = true;
-                                       break;
+                                       if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
+                                               failed = true;
+                                       }
                                }
-                       }
 
-                       // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
-                       if (!is_open)
-                               return !TypeManager.IsGenericMethodDefinition (method);
+                               if (failed)
+                                       continue;
 
-                       Type[] inferred_types = new Type [method_args.Length];
+                               if (best_candidate != null)
+                                       return false;
 
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+                               best_candidate = candidate.Type;
+                       }
 
-                       int lambdas = 0;
-                       for (int i = 0; i < arg_count; i++) {
-                               param_types [i] = pd.ParameterType (i);
+                       if (best_candidate == null)
+                               return false;
 
-                               Argument a = (Argument) arguments [i];
-                               if (a.Expr is LambdaExpression)
-                                       lambdas++;
-                               
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
-                                   (a.Expr is AnonymousMethodExpression))
-                                       continue;
+                       unfixed_types[i] = null;
+                       fixed_types[i] = best_candidate;
+                       return true;
+               }
 
-                               arg_types [i] = a.Type;
-                       }
+               public bool IsTypeNonDependent (MethodInfo mi, Type type)
+               {
+                       if (IsUnfixed (type) < 0)
+                               return false;
 
-                       if (!InferTypeArguments (param_types, arg_types, inferred_types)){
-                               Type it;
-                               if (lambdas == 0)
-                                       return false;
-                               
-                               if (!LambdaInfer (ec, arguments, param_types, arg_types, inferred_types))
+                       ParameterData d_parameters = TypeManager.GetParameterData (mi);
+                       foreach (Type t in d_parameters.Types) {
+                               if (!t.IsGenericParameter)
+                                       continue;
+
+                               if (IsUnfixed (t) >= 0)
                                        return false;
                        }
 
-                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
                        return true;
                }
 
-               /// <summary>
-               ///   Type inference.
-               /// </summary>
-               public static bool InferTypeArguments (ParameterData apd,
-                                                      ref MethodBase method)
+               public int IsUnfixed (Type type)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       if (!type.IsGenericParameter)
+                               return -1;
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       if (apd.Count != pd.Count)
-                               return false;
+                       //return unfixed_types[type.GenericParameterPosition] != null;
+                       for (int i = 0; i < unfixed_types.Length; ++i) {
+                               if (unfixed_types [i] == type)
+                                       return i;
+                       }
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] inferred_types = new Type [method_args.Length];
+                       return -1;
+               }
+
+               //
+               // 26.3.3.9 Lower-bound Inference
+               //
+               public void LowerBoundInference (Type u, Type v)
+               {
+                       // If U is an array type
+                       if (u.IsArray) {
+                               int u_dim = u.GetArrayRank ();
+                               Type v_e;
+                               Type u_e = TypeManager.GetElementType (u);
 
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+                               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;
 
-                       for (int i = 0; i < apd.Count; i++) {
-                               param_types [i] = pd.ParameterType (i);
-                               arg_types [i] = apd.ParameterType (i);
+                               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;
                        }
 
-                       if (!InferTypeArguments (param_types, arg_types, inferred_types))
-                               return false;
+                       // Remove ref, out modifiers
+                       if (v.HasElementType)
+                               v = v.GetElementType ();
 
-                       method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
-                       return true;
+                       // If V is one of the unfixed type arguments
+                       int pos = IsUnfixed (v);
+                       if (pos == -1)
+                               return;
+
+                       AddToBounds (u, pos);
+               }
+
+               //
+               // 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 (returnType.IsGenericParameter) {
+                               types [returnType.GenericParameterPosition] = null;
+                               return;
+                       }
+
+                       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;
+                       }
                }
        }