2007-08-29 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / gmcs / generic.cs
index 3e8cbc7e615e0a146160bfbca0f2202e9dafa799..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
 //
@@ -600,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)
@@ -619,10 +621,6 @@ namespace Mono.CSharp {
                        get { return constraints; }
                }
 
-               public bool HasConstructorConstraint {
-                       get { return constraints != null && constraints.HasConstructorConstraint; }
-               }
-
                public DeclSpace DeclSpace {
                        get { return decl; }
                }
@@ -882,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)
@@ -894,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 ();
@@ -987,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) {
@@ -1119,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;
@@ -1246,14 +1269,20 @@ 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));
@@ -1264,11 +1293,18 @@ namespace Mono.CSharp {
                                        Expression.Error_VoidInvalidInTheContext (Location);
                                        return false;
                                }
-
-                               atypes [i] = te.Type;
                        }
                        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
@@ -1453,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);
                }
 
@@ -1614,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 ();
@@ -1663,7 +1704,7 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               bool HasDefaultConstructor (Type containerType, Type atype)
+               bool HasDefaultConstructor (Type atype)
                {
                        if (atype.IsAbstract)
                                return false;
@@ -1691,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,
@@ -1834,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;
@@ -1984,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
@@ -2056,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)
@@ -2088,8 +2141,8 @@ namespace Mono.CSharp {
                ///   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) {
                                //
@@ -2111,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;
@@ -2143,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.
@@ -2155,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.
@@ -2168,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);
                        }
 
                        //
@@ -2183,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;
@@ -2192,29 +2245,233 @@ 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;
                        }
 
                        return true;
                }
 
-               //
-               // Type inference.
-               //
+               /// <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;
 
-               static bool InferType (Type pt, Type at, Type[] infered)
+                       // 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)
@@ -2222,20 +2479,15 @@ namespace Mono.CSharp {
 
                                int pos = pt.GenericParameterPosition;
 
-                               if (infered [pos] == null) {
-                                       infered [pos] = at;
-                                       return true;
-                               }
+                               if (inferred [pos] == null)
+                                       inferred [pos] = at;
 
-                               if (infered [pos] != at)
-                                       return false;
-
-                               return true;
+                               return inferred [pos] == at;
                        }
 
                        if (!pt.ContainsGenericParameters) {
                                if (at.ContainsGenericParameters)
-                                       return InferType (at, pt, infered);
+                                       return UnifyType (at, pt, inferred);
                                else
                                        return true;
                        }
@@ -2245,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);
@@ -2278,233 +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 (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
+                                       continue;
+
+                               if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
+                                       return false;
+                       }
 
-                               if (!InferGenericInstance (pt, type, infered_types))
+                       return 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;
+               }
+       }
+
+       //
+       // Implements C# 3.0 type inference
+       //
+       class TypeInferenceV3 : ATypeInference
+       {
+               public TypeInferenceV3 (ArrayList arguments)
+                       : base (arguments)
+               {
+               }
+
+               public override Type[] InferDelegateArguments (MethodBase method)
+               {
+                       ParameterData pd = TypeManager.GetParameterData (method);
+                       if (arg_count != pd.Count)
+                               return null;
+
+                       Type[] d_gargs = method.GetGenericArguments ();
+                       TypeInferenceContext context = new TypeInferenceContext (d_gargs);
+
+                       // A lower-bound inference is made from each argument type Uj of D
+                       // to the corresponding parameter type Tj of M
+                       for (int i = 0; i < arg_count; ++i) {
+                               Type t = pd.Types [i];
+                               if (!t.IsGenericParameter)
                                        continue;
 
-                               for (int i = 0; i < infered_types.Length; i++) {
-                                       if (infered [i] == null) {
-                                               infered [i] = infered_types [i];
-                                               continue;
-                                       }
+                               context.LowerBoundInference ((Type)arguments[i], t);
+                       }
 
-                                       if (infered [i] != infered_types [i])
-                                               return false;
+                       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)
+               {
+                       //
+                       // The first inference phase
+                       //
+                       for (int i = 0; i < arg_count; i++) {
+                               Type method_parameter = methodParameters.ParameterType (i);
+
+                               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;
                                }
 
-                               found_one = true;
+                               if (a.Expr.Type == TypeManager.null_type)
+                                       continue;
+
+                               //
+                               // Otherwise an output type inference is made
+                               //
+                               tic.OutputTypeInference (ec, a.Expr, method_parameter);
                        }
 
-                       return found_one;
+                       //
+                       // 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;
+
+                       return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
                }
 
-               static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
+               bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
                {
-                       Type[] at_args = at.GetGenericArguments ();
-                       Type[] pt_args = pt.GetGenericArguments ();
+                       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 (at_args.Length != pt_args.Length)
+                       if (!fixed_any && fixDependent)
                                return false;
 
-                       for (int i = 0; i < at_args.Length; i++) {
-                               if (!InferType (pt_args [i], at_args [i], infered_types))
-                                       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;
+
+                               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 < infered_types.Length; i++) {
-                               if (infered_types [i] == null)
-                                       return false;
+
+                       return DoSecondPhase (ec, tic, methodParameters, true);
+               }
+       }
+
+       public class TypeInferenceContext
+       {
+               readonly Type[] unfixed_types;
+               readonly Type[] fixed_types;
+               readonly ArrayList[] bounds;
+
+               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;
                        }
+               }
 
-                       return true;
+               void AddToBounds (Type t, int index)
+               {
+                       ArrayList a = bounds[index];
+                       if (a == null) {
+                               a = new ArrayList ();
+                               a.Add (t);
+                               bounds[index] = a;
+                               return;
+                       }
+
+                       if (a.Contains (t))
+                               return;
+
+                       a.Add (t);
                }
 
-               /// <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)
+               //
+               // 26.3.3.8 Exact Inference
+               //
+               public void ExactInference (Type u, Type v)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       // If V is an array type
+                       if (v.IsArray) {
+                               if (!u.IsArray)
+                                       return;
 
-                       // if there are no arguments, there's no way to infer the type-arguments
-                       if (arguments == null || arguments.Count == 0)
-                               return false;
+                               if (u.GetArrayRank () != v.GetArrayRank ())
+                                       return;
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       int pd_count = pd.Count;
-                       int arg_count = arguments.Count;
+                               ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
+                               return;
+                       }
 
-                       if (pd_count == 0)
-                               return false;
+                       // If V is constructed type and U is constructed type
+                       if (v.IsGenericType && !v.IsGenericTypeDefinition) {
+                               if (!u.IsGenericType)
+                                       return;
 
-                       if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
-                               return false;
+                               Type [] ga_u = u.GetGenericArguments ();
+                               Type [] ga_v = v.GetGenericArguments ();
+                               if (ga_u.Length != ga_v.Length)
+                                       return;
 
-                       if (pd_count - 1 > arg_count)
-                               return false;
+                               for (int i = 0; i < ga_u.Length; ++i)
+                                       ExactInference (ga_u [i], ga_v [i]);
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                               return;
+                       }
 
-                       //
-                       // 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 V is one of the unfixed type arguments
+                       int pos = IsUnfixed (v);
+                       if (pos == -1)
+                               return;
 
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                       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;
 
-                               Type pt = pd.ParameterType (i);
-                               Type at = a.Type;
+                               if (bounds[i] == null)
+                                       continue;
 
-                               if (!InferType (pt, at, infered_types))
+                               if (!FixType (i))
                                        return false;
+                               fixed_any = true;
                        }
+                       return true;
+               }
 
-                       Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
+               //
+               // 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;
 
-                       for (int i = pd_count - 1; i < arg_count; i++) {
-                               Argument a = (Argument) arguments [i];
+                               if (!TypeManager.IsDelegateType (t))
+                                       continue;
 
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
+                               MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
+                               Type rtype = invoke.ReturnType;
+                               if (!rtype.IsGenericParameter && !rtype.IsGenericType)
                                        continue;
 
-                               if (!InferType (element_type, a.Type, infered_types))
-                                       return false;
+#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);
                        }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
+                       foreach (Type t in types_to_fix) {
+                               if (t == null)
+                                       continue;
+
+                               if (!FixType (IsUnfixed (t))) {
                                        return false;
+                               }
+                       }
 
-                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
+                       fixed_any = types_to_fix.Count > 0;
                        return true;
                }
 
-               static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
-                                               Type[] infered_types)
+               //
+               // 26.3.3.10 Fixing
+               //
+               public bool FixType (int i)
                {
-                       if (infered_types == null)
+                       // It's already fixed
+                       if (unfixed_types[i] == null)
+                               throw new InternalErrorException ("Type argument has been already fixed");
+
+                       ArrayList candidates = (ArrayList)bounds [i];
+                       if (candidates == null)
                                return false;
 
-                       for (int i = 0; i < arg_types.Length; i++) {
-                               if (arg_types [i] == null)
+                       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;
+
+                                       if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
+                                               failed = true;
+                                       }
+                               }
+
+                               if (failed)
                                        continue;
 
-                               if (!InferType (param_types [i], arg_types [i], infered_types))
+                               if (best_candidate != null)
                                        return false;
+
+                               best_candidate = candidate.Type;
                        }
 
-                       for (int i = 0; i < infered_types.Length; i++)
-                               if (infered_types [i] == null)
+                       if (best_candidate == null)
+                               return false;
+
+                       unfixed_types[i] = null;
+                       fixed_types[i] = best_candidate;
+                       return true;
+               }
+
+               public bool IsTypeNonDependent (MethodInfo mi, Type type)
+               {
+                       if (IsUnfixed (type) < 0)
+                               return false;
+
+                       ParameterData d_parameters = TypeManager.GetParameterData (mi);
+                       foreach (Type t in d_parameters.Types) {
+                               if (!t.IsGenericParameter)
+                                       continue;
+
+                               if (IsUnfixed (t) >= 0)
                                        return false;
+                       }
 
                        return true;
                }
 
-               /// <summary>
-               ///   Type inference.  Try to infer the type arguments from `method',
-               ///   which is invoked with the arguments `arguments'.  This is used
-               ///   when resolving an Invocation or a DelegateInvocation and the user
-               ///   did not explicitly specify type arguments.
-               /// </summary>
-               public static bool InferTypeArguments (ArrayList arguments,
-                                                      ref MethodBase method)
+               public int IsUnfixed (Type type)
                {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+                       if (!type.IsGenericParameter)
+                               return -1;
 
-                       int arg_count;
-                       if (arguments != null)
-                               arg_count = arguments.Count;
-                       else
-                               arg_count = 0;
+                       //return unfixed_types[type.GenericParameterPosition] != null;
+                       for (int i = 0; i < unfixed_types.Length; ++i) {
+                               if (unfixed_types [i] == type)
+                                       return i;
+                       }
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       if (arg_count != pd.Count)
-                               return false;
+                       return -1;
+               }
 
-                       Type[] method_args = method.GetGenericArguments ();
+               //
+               // 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);
+
+                               if (v.IsArray) {
+                                       if (u_dim != v.GetArrayRank ())
+                                               return;
 
-                       bool is_open = false;
-                       for (int i = 0; i < method_args.Length; i++) {
-                               if (method_args [i].IsGenericParameter) {
-                                       is_open = true;
-                                       break;
+                                       v_e = TypeManager.GetElementType (v);
+
+                                       if (u.IsByRef) {
+                                               LowerBoundInference (u_e, v_e);
+                                               return;
+                                       }
+                                       ExactInference (u_e, v_e);
+                                       return;
                                }
-                       }
 
-                       // 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 (u_dim != 1)
+                                       return;
 
-                       Type[] infered_types = new Type [method_args.Length];
+                               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;
 
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+                                       v_e = TypeManager.GetTypeArguments (v)[0];
 
-                       for (int i = 0; i < arg_count; i++) {
-                               param_types [i] = pd.ParameterType (i);
+                                       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;
 
-                               Argument a = (Argument) arguments [i];
-                               if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
-                                   (a.Expr is AnonymousMethodExpression))
-                                       continue;
+                               v = v.GetGenericTypeDefinition ().MakeGenericType (ga_u);
 
-                               arg_types [i] = a.Type;
+                               // 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, infered_types))
-                               return false;
+                       // Remove ref, out modifiers
+                       if (v.HasElementType)
+                               v = v.GetElementType ();
 
-                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
-                       return true;
+                       // If V is one of the unfixed type arguments
+                       int pos = IsUnfixed (v);
+                       if (pos == -1)
+                               return;
+
+                       AddToBounds (u, pos);
                }
 
-               /// <summary>
-               ///   Type inference.
-               /// </summary>
-               public static bool InferTypeArguments (ParameterData apd,
-                                                      ref MethodBase method)
-               {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
+               //
+               // 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;
+                       }
 
-                       ParameterData pd = TypeManager.GetParameterData (method);
-                       if (apd.Count != pd.Count)
-                               return false;
+                       if (e is MethodGroupExpr) {
+                               throw new NotImplementedException ();
+                       }
 
-                       Type[] method_args = method.GetGenericArguments ();
-                       Type[] infered_types = new Type [method_args.Length];
+                       //
+                       // if e is an expression with type U, then
+                       // a lower-bound inference is made from U for T
+                       //
+                       LowerBoundInference (e.Type, t);
+               }
 
-                       Type[] param_types = new Type [pd.Count];
-                       Type[] arg_types = new Type [pd.Count];
+               static void RemoveDependentTypes (ArrayList types, Type returnType)
+               {
+                       if (returnType.IsGenericParameter) {
+                               types [returnType.GenericParameterPosition] = null;
+                               return;
+                       }
 
-                       for (int i = 0; i < apd.Count; i++) {
-                               param_types [i] = pd.ParameterType (i);
-                               arg_types [i] = apd.ParameterType (i);
+                       if (returnType.IsGenericType) {
+                               foreach (Type t in returnType.GetGenericArguments ()) {
+                                       RemoveDependentTypes (types, t);
+                               }
                        }
+               }
 
-                       if (!InferTypeArguments (param_types, arg_types, infered_types))
+               public bool UnfixedVariableExists {
+                       get {
+                               foreach (Type ut in unfixed_types)
+                                       if (ut != null)
+                                               return true;
                                return false;
-
-                       method = ((MethodInfo)method).MakeGenericMethod (infered_types);
-                       return true;
+                       }
                }
        }