2008-03-27 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / delegate.cs
index 2fb7adb02c6f83587eab7fc5f8031b45c622579f..dd583045f0aaa4ad2e95acc872433aff423b8d88 100644 (file)
@@ -4,6 +4,7 @@
 // Authors:
 //     Ravi Pratap (ravi@ximian.com)
 //     Miguel de Icaza (miguel@ximian.com)
+//     Marek Safar (marek.safar@gmail.com)
 //
 // Licensed under the terms of the GNU GPL
 //
@@ -22,7 +23,8 @@ namespace Mono.CSharp {
        /// <summary>
        ///   Holds Delegates
        /// </summary>
-       public class Delegate : DeclSpace {
+       public class Delegate : DeclSpace, IMemberContainer
+       {
                public Expression ReturnType;
                public Parameters      Parameters;
 
@@ -38,7 +40,12 @@ namespace Mono.CSharp {
                Expression instance_expr;
                MethodBase delegate_method;
                ReturnParameter return_attributes;
-       
+
+               MemberCache member_cache;
+
+               const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
+                       MethodAttributes.Virtual | MethodAttributes.NewSlot;
+
                const int AllowedModifiers =
                        Modifiers.NEW |
                        Modifiers.PUBLIC |
@@ -47,7 +54,7 @@ namespace Mono.CSharp {
                        Modifiers.UNSAFE |
                        Modifiers.PRIVATE;
 
-               public Delegate (NamespaceEntry ns, TypeContainer parent, Expression type,
+               public Delegate (NamespaceEntry ns, DeclSpace parent, Expression type,
                                 int mod_flags, MemberName name, Parameters param_list,
                                 Attributes attrs)
                        : base (ns, parent, name, attrs)
@@ -78,17 +85,6 @@ namespace Mono.CSharp {
                        if (TypeBuilder != null)
                                return TypeBuilder;
 
-                       ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
-
-                       if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
-                               Namespace system = RootNamespace.Global.GetNamespace ("System", true);
-                               TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
-                               TypeManager.multicast_delegate_type = expr.ResolveType (ec);
-                       }
-
-                       if (TypeManager.multicast_delegate_type == null)
-                               throw new InternalErrorException ("System.MulticastDelegate unresolved");
-
                        if (IsTopLevel) {
                                if (TypeManager.NamespaceClash (Name, Location))
                                        return null;
@@ -107,16 +103,58 @@ namespace Mono.CSharp {
 
                        TypeManager.AddUserType (this);
 
+#if GMCS_SOURCE
+                       if (IsGeneric) {
+                               string[] param_names = new string [TypeParameters.Length];
+                               for (int i = 0; i < TypeParameters.Length; i++)
+                                       param_names [i] = TypeParameters [i].Name;
+
+                               GenericTypeParameterBuilder[] gen_params;
+                               gen_params = TypeBuilder.DefineGenericParameters (param_names);
+
+                               int offset = CountTypeParameters - CurrentTypeParameters.Length;
+                               for (int i = offset; i < gen_params.Length; i++)
+                                       CurrentTypeParameters [i - offset].Define (gen_params [i]);
+
+                               foreach (TypeParameter type_param in CurrentTypeParameters) {
+                                       if (!type_param.Resolve (this))
+                                               return null;
+                               }
+
+                               Expression current = new SimpleName (
+                                       MemberName.Basename, TypeParameters, Location);
+                               current = current.ResolveAsTypeTerminal (this, false);
+                               if (current == null)
+                                       return null;
+
+                               CurrentType = current.Type;
+                       }
+#endif
+
                        return TypeBuilder;
                }
 
                public override bool Define ()
                {
-                       MethodAttributes mattr;
-                       int i;
+#if GMCS_SOURCE
+                       if (IsGeneric) {
+                               foreach (TypeParameter type_param in TypeParameters) {
+                                       if (!type_param.Resolve (this))
+                                               return false;
+                               }
 
-                       if (ec == null)
-                               throw new InternalErrorException ("Define called before DefineType?");
+                               foreach (TypeParameter type_param in TypeParameters) {
+                                       if (!type_param.DefineType (this))
+                                               return false;
+                               }
+
+                               foreach (TypeParameter type_param in TypeParameters) {
+                                       if (!type_param.CheckDependencies ())
+                                               return false;
+                               }
+                       }
+#endif
+                       member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
 
                        // FIXME: POSSIBLY make this static, as it is always constant
                        //
@@ -124,10 +162,10 @@ namespace Mono.CSharp {
                        const_arg_types [0] = TypeManager.object_type;
                        const_arg_types [1] = TypeManager.intptr_type;
 
-                       mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
+                       const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
                                MethodAttributes.HideBySig | MethodAttributes.Public;
 
-                       ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
+                       ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
                                                                            CallingConventions.Standard,
                                                                            const_arg_types);
 
@@ -145,7 +183,7 @@ namespace Mono.CSharp {
                        const_parameters.Resolve (null);
                        
                        TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
-                               
+                       member_cache.AddMember (ConstructorBuilder, this);
                        
                        ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
 
@@ -155,7 +193,7 @@ namespace Mono.CSharp {
                        // First, call the `out of band' special method for
                        // defining recursively any types we need:
                        
-                       if (!Parameters.Resolve (ec))
+                       if (!Parameters.Resolve (this))
                                return false;
 
                        //
@@ -164,37 +202,32 @@ namespace Mono.CSharp {
 
                        // Check accessibility
                        foreach (Type partype in Parameters.Types){
-                               if (!Parent.AsAccessible (partype, ModFlags)) {
+                               if (!IsAccessibleAs (partype)) {
+                                       Report.SymbolRelatedToPreviousError (partype);
                                        Report.Error (59, Location,
                                                      "Inconsistent accessibility: parameter type `" +
                                                      TypeManager.CSharpName (partype) + "' is less " +
-                                                     "accessible than delegate `" + Name + "'");
+                                                         "accessible than delegate `" + GetSignatureForError () + "'");
                                        return false;
                                }
-                               if (partype.IsPointer && !UnsafeOK (Parent))
-                                       return false;
                        }
                        
-                       ReturnType = ReturnType.ResolveAsTypeTerminal (ec, false);
+                       ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
                        if (ReturnType == null)
                                return false;
-                        
-                       ret_type = ReturnType.Type;
-                       if (ret_type == null)
-                               return false;
-
-                       CheckObsoleteType (ReturnType);
 
-                       if (!Parent.AsAccessible (ret_type, ModFlags)) {
+                       ret_type = ReturnType.Type;
+            
+                       if (!IsAccessibleAs (ret_type)) {
+                               Report.SymbolRelatedToPreviousError (ret_type);
                                Report.Error (58, Location,
                                              "Inconsistent accessibility: return type `" +
                                              TypeManager.CSharpName (ret_type) + "' is less " +
-                                             "accessible than delegate `" + Name + "'");
+                                             "accessible than delegate `" + GetSignatureForError () + "'");
                                return false;
                        }
 
-                       if (ret_type.IsPointer && !UnsafeOK (Parent))
-                               return false;
+                       CheckProtectedModifier ();
 
                        if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
                                Method.Error1599 (Location, ret_type);
@@ -208,121 +241,100 @@ namespace Mono.CSharp {
                        
                        CallingConventions cc = Parameters.CallingConvention;
 
-                       mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
-
                        InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
                                                                  mattr,                     
                                                                  cc,
                                                                  ret_type,                  
                                                                  Parameters.Types);
-
-                       //
-                       // Define parameters, and count out/ref parameters
-                       //
-                       int out_params = 0;
-                       foreach (Parameter p in Parameters.FixedParameters) {
-                               if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
-                                       out_params++;
-                       }
                        
                        InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
 
                        TypeManager.RegisterMethod (InvokeBuilder, Parameters);
+                       member_cache.AddMember (InvokeBuilder, this);
+
+                       if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null) {
+                               DefineAsyncMethods (cc);
+                       }
+
+                       return true;
+               }
 
+               void DefineAsyncMethods (CallingConventions cc)
+               {
                        //
                        // BeginInvoke
                        //
-                       int params_num = Parameters.Count;
-                       Type [] async_param_types = new Type [params_num + 2];
-
-                       Parameters.Types.CopyTo (async_param_types, 0);
-
-                       async_param_types [params_num] = TypeManager.asynccallback_type;
-                       async_param_types [params_num + 1] = TypeManager.object_type;
+                       Parameters async_parameters = Parameters.MergeGenerated (Parameters,
+                               new Parameter (TypeManager.asynccallback_type, "callback", Parameter.Modifier.NONE, null, Location),
+                               new Parameter (TypeManager.object_type, "object", Parameter.Modifier.NONE, null, Location));
 
-                       mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
-                               MethodAttributes.Virtual | MethodAttributes.NewSlot;
-                       
                        BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
-                                                                      mattr,
-                                                                      cc,
-                                                                      TypeManager.iasyncresult_type,
-                                                                      async_param_types);
-
-                       i = Parameters.Count;
-                       Parameters.ApplyAttributes (ec, BeginInvokeBuilder);
-                       BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
-                       BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
-                       
-                       BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
-
-                       Parameter [] async_params = new Parameter [params_num + 2];
-                       Parameters.FixedParameters.CopyTo (async_params, 0);
-                       
-                       async_params [params_num] = new Parameter (
-                               TypeManager.asynccallback_type, "callback",
-                                                                  Parameter.Modifier.NONE, null, Location);
-                       async_params [params_num + 1] = new Parameter (
-                               TypeManager.object_type, "object",
-                                                                  Parameter.Modifier.NONE, null, Location);
-
-                       Parameters async_parameters = new Parameters (async_params);
-                       async_parameters.Resolve (ec);
-                       async_parameters.ApplyAttributes (ec, BeginInvokeBuilder);
+                               mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
 
+                       BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
                        TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
+                       member_cache.AddMember (BeginInvokeBuilder, this);
 
                        //
                        // EndInvoke is a bit more interesting, all the parameters labeled as
                        // out or ref have to be duplicated here.
                        //
-                       
-                       Type [] end_param_types = new Type [out_params + 1];
-                       Parameter [] end_params = new Parameter [out_params + 1];
-                       int param = 0; 
-                       if (out_params > 0){
-                               int top = Parameters.FixedParameters.Length;
-                               for (i = 0; i < top; i++){
+
+                       //
+                       // Define parameters, and count out/ref parameters
+                       //
+                       Parameters end_parameters;
+                       int out_params = 0;
+
+                       foreach (Parameter p in Parameters.FixedParameters) {
+                               if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
+                                       ++out_params;
+                       }
+
+                       if (out_params > 0) {
+                               Type [] end_param_types = new Type [out_params];
+                               Parameter [] end_params = new Parameter [out_params];
+
+                               int param = 0;
+                               for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
                                        Parameter p = Parameters.FixedParameters [i];
                                        if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
                                                continue;
 
-                                       end_param_types [param] = Parameters.Types [i];
+                                       end_param_types [param] = p.ExternalType ();
                                        end_params [param] = p;
-                                       param++;
+                                       ++param;
                                }
+                               end_parameters = Parameters.CreateFullyResolved (end_params, end_param_types);
+                       } else {
+                               end_parameters = Parameters.EmptyReadOnlyParameters;
                        }
-                       end_param_types [out_params] = TypeManager.iasyncresult_type;
-                       end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null, Location);
+
+                       end_parameters = Parameters.MergeGenerated (end_parameters,
+                               new Parameter (TypeManager.iasyncresult_type, "result", Parameter.Modifier.NONE, null, Location));
 
                        //
                        // Create method, define parameters, register parameters with type system
                        //
-                       EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
+                       EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.Types);
                        EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
 
-                       //
-                       // EndInvoke: Label the parameters
-                       //
-                       EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
-                       for (i = 0; i < end_params.Length-1; i++){
-                               EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
-                       }
-
-                       Parameters end_parameters = new Parameters (end_params);
-                       end_parameters.Resolve (ec);
-
+                       end_parameters.ApplyAttributes (EndInvokeBuilder);
                        TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
-
-                       return true;
+                       member_cache.AddMember (EndInvokeBuilder, this);
                }
 
                public override void Emit ()
                {
-                       Parameters.ApplyAttributes (ec, InvokeBuilder);
+                       Parameters.ApplyAttributes (InvokeBuilder);
+
+                       if (BeginInvokeBuilder != null) {
+                               Parameters p = (Parameters) TypeManager.GetParameterData (BeginInvokeBuilder);
+                               p.ApplyAttributes (BeginInvokeBuilder);
+                       }
 
                        if (OptAttributes != null) {
-                               OptAttributes.Emit (ec, this);
+                               OptAttributes.Emit ();
                        }
 
                        base.Emit ();
@@ -343,9 +355,9 @@ namespace Mono.CSharp {
                }
 
                //TODO: duplicate
-               protected override bool VerifyClsCompliance (DeclSpace ds)
+               protected override bool VerifyClsCompliance ()
                {
-                       if (!base.VerifyClsCompliance (ds)) {
+                       if (!base.VerifyClsCompliance ()) {
                                return false;
                        }
 
@@ -357,44 +369,125 @@ namespace Mono.CSharp {
                        return true;
                }
 
+
+               public static ConstructorInfo GetConstructor (Type container_type, Type delegate_type)
+               {
+                       Type dt = delegate_type;
+#if GMCS_SOURCE
+                       Type[] g_args = null;
+                       if (delegate_type.IsGenericType) {
+                               g_args = delegate_type.GetGenericArguments ();
+                               delegate_type = delegate_type.GetGenericTypeDefinition ();
+                       }
+#endif
+
+                       Delegate d = TypeManager.LookupDelegate (delegate_type);
+                       if (d != null) {
+#if GMCS_SOURCE
+                               if (g_args != null)
+                                       return TypeBuilder.GetConstructor (dt, d.ConstructorBuilder);
+#endif
+                               return d.ConstructorBuilder;
+                       }
+
+                       Expression ml = Expression.MemberLookup (container_type,
+                               null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
+                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
+
+                       MethodGroupExpr mg = ml as MethodGroupExpr;
+                       if (mg == null) {
+                               Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
+                               // FIXME: null will cause a crash later
+                               return null;
+                       }
+
+                       return (ConstructorInfo) mg.Methods[0];
+               }
+
                //
                // Returns the MethodBase for "Invoke" from a delegate type, this is used
                // to extract the signature of a delegate.
                //
-               public static MethodInfo GetInvokeMethod (EmitContext ec, Type delegate_type, Location loc)
+               public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
                {
-                       Expression ml = Expression.MemberLookup (
-                               ec, delegate_type, "Invoke", loc);
+                       Type dt = delegate_type;
+#if GMCS_SOURCE
+                       Type[] g_args = null;
+                       if (delegate_type.IsGenericType) {
+                               g_args = delegate_type.GetGenericArguments ();
+                               delegate_type = delegate_type.GetGenericTypeDefinition ();
+                       }
+#endif
+                       Delegate d = TypeManager.LookupDelegate (delegate_type);
+                       if (d != null) {
+#if GMCS_SOURCE
+                               if (g_args != null) {
+                                       MethodInfo invoke = TypeBuilder.GetMethod (dt, d.InvokeBuilder);
+#if MS_COMPATIBLE
+                                       Parameters p = (Parameters) d.Parameters.InflateTypes (g_args, g_args);
+                                       TypeManager.RegisterMethod (invoke, p);
+#endif
+                                       return invoke;
+                               }
+#endif
+                               return d.InvokeBuilder;
+                       }
 
-                       if (!(ml is MethodGroupExpr)) {
-                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");
+                       Expression ml = Expression.MemberLookup (container_type, null, dt,
+                               "Invoke", Location.Null);
+
+                       MethodGroupExpr mg = ml as MethodGroupExpr;
+                       if (mg == null) {
+                               Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
+                               // FIXME: null will cause a crash later
                                return null;
                        }
 
-                       return (MethodInfo) (((MethodGroupExpr) ml).Methods [0]);
+                       return (MethodInfo) mg.Methods[0];
+               }
+
+               public static bool IsTypeCovariant (Expression a, Type b)
+               {
+                       Type a_type = a.Type;
+                       if (a_type == b)
+                               return true;
+
+                       if (RootContext.Version == LanguageVersion.ISO_1)
+                               return false;
+
+                       if (a.Type.IsValueType)
+                               return false;
+
+                       return Convert.ImplicitReferenceConversionCore (
+                               a, b);
                }
                
                /// <summary>
                ///  Verifies whether the method in question is compatible with the delegate
                ///  Returns the method itself if okay and null if not.
                /// </summary>
-               public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
+               public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
+                                                      MethodGroupExpr old_mg, MethodBase mb,
                                                       Location loc)
                {
-                       ParameterData pd = TypeManager.GetParameterData (mb);
-
-                       int pd_count = pd.Count;
-
-                       MethodBase invoke_mb = GetInvokeMethod (ec, delegate_type, loc);
+                       MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
                        if (invoke_mb == null)
                                return null;
 
                        ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
 
-                       if (invoke_pd.Count != pd_count)
+#if GMCS_SOURCE
+                       if (old_mg.type_arguments == null &&
+                           !TypeManager.InferTypeArguments (invoke_pd, ref mb))
+                               return null;
+#endif
+
+                       ParameterData pd = TypeManager.GetParameterData (mb);
+
+                       if (invoke_pd.Count != pd.Count)
                                return null;
 
-                       for (int i = pd_count; i > 0; ) {
+                       for (int i = pd.Count; i > 0; ) {
                                i--;
 
                                Type invoke_pd_type = invoke_pd.ParameterType (i);
@@ -402,35 +495,34 @@ namespace Mono.CSharp {
                                Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
                                Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
 
-                               if (invoke_pd_type == pd_type &&
-                                   invoke_pd_type_mod == pd_type_mod)
+                               invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
+                               pd_type_mod &= ~Parameter.Modifier.PARAMS;
+
+                               if (invoke_pd_type_mod != pd_type_mod)
+                                       return null;
+
+                               if (invoke_pd_type == pd_type)
                                        continue;
-                               
-                               if (invoke_pd_type.IsSubclassOf (pd_type) && 
-                                               invoke_pd_type_mod == pd_type_mod)
-                                       if (RootContext.Version == LanguageVersion.ISO_1) {
-                                               Report.FeatureIsNotStandardized (loc, "contravariance");
-                                               return null;
-                                       } else
-                                               continue;
-                                       
-                               return null;
+
+                               //if (!IsTypeCovariant (invoke_pd_type, pd_type))
+                               //      return null;
+
+                               if (RootContext.Version == LanguageVersion.ISO_1)
+                                       return null;
                        }
 
                        Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
                        Type mb_retval = ((MethodInfo) mb).ReturnType;
-                       if (invoke_mb_retval == mb_retval)
+                       if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
                                return mb;
-                       
-                       if (mb_retval.IsSubclassOf (invoke_mb_retval))
-                               if (RootContext.Version == LanguageVersion.ISO_1) {
-                                       Report.FeatureIsNotStandardized (loc, "covariance");
-                                       return null;
-                               }
-                               else
-                                       return mb;
-                       
-                       return null;
+
+                       //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
+                       //      return null;
+
+                       if (RootContext.Version == LanguageVersion.ISO_1) 
+                               return null;
+
+                       return mb;
                }
 
                // <summary>
@@ -448,7 +540,7 @@ namespace Mono.CSharp {
                                arg_count = args.Count;
 
                        Expression ml = Expression.MemberLookup (
-                               ec, delegate_type, "Invoke", loc);
+                               ec.ContainerType, delegate_type, "Invoke", loc);
 
                        MethodGroupExpr me = ml as MethodGroupExpr;
                        if (me == null) {
@@ -456,18 +548,15 @@ namespace Mono.CSharp {
                                return false;
                        }
                        
-                       MethodBase mb = me.Methods [0];
+                       MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
                        ParameterData pd = TypeManager.GetParameterData (mb);
 
                        int pd_count = pd.Count;
 
                        bool params_method = pd.HasParams;
                        bool is_params_applicable = false;
-                       bool is_applicable = Invocation.IsApplicable (ec, args, arg_count, mb);
-
-                       if (!is_applicable && params_method &&
-                           Invocation.IsParamsMethodApplicable (ec, args, arg_count, mb))
-                               is_applicable = is_params_applicable = true;
+                       me.DelegateType = delegate_type;
+                       bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
 
                        if (!is_applicable && !params_method && arg_count != pd_count) {
                                Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
@@ -475,97 +564,20 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       return Invocation.VerifyArgumentsCompat (
-                                       ec, args, arg_count, mb, 
+                       return me.VerifyArgumentsCompat (
+                                       ec, ref args, arg_count, mb, 
                                        is_params_applicable || (!is_applicable && params_method),
-                                       delegate_type, false, loc);
-               }
-               
-               /// <summary>
-               ///  Verifies whether the delegate in question is compatible with this one in
-               ///  order to determine if instantiation from the same is possible.
-               /// </summary>
-               public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
-               {
-                       Expression ml = Expression.MemberLookup (
-                               ec, delegate_type, "Invoke", loc);
-                       
-                       if (!(ml is MethodGroupExpr)) {
-                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");
-                               return false;
-                       }
-                       
-                       MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
-                       ParameterData pd = TypeManager.GetParameterData (mb);
-
-                       Expression probe_ml = Expression.MemberLookup (
-                               ec, delegate_type, "Invoke", loc);
-                       
-                       if (!(probe_ml is MethodGroupExpr)) {
-                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");
-                               return false;
-                       }
-                       
-                       MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
-                       ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
-                       
-                       if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
-                               return false;
-
-                       if (pd.Count != probe_pd.Count)
-                               return false;
-
-                       for (int i = pd.Count; i > 0; ) {
-                               i--;
-
-                               if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
-                                   pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
-                                       return false;
-                       }
-                       
-                       return true;
+                                       false, loc);
                }
                
-               public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
+               public static string FullDelegateDesc (MethodBase invoke_method)
                {
-                       StringBuilder sb = new StringBuilder ();
-                       sb.Append (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
-                       sb.Append (" ");
-                       sb.Append (TypeManager.CSharpName (del_type));
-                       sb.Append (pd.GetSignatureForError ());
-                       return sb.ToString ();                  
+                       return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
                }
                
-               // Hack around System.Reflection as found everywhere else
-               public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                                       MemberFilter filter, object criteria)
-               {
-                       ArrayList members = new ArrayList ();
-
-                       if ((mt & MemberTypes.Method) != 0) {
-                               if (ConstructorBuilder != null)
-                               if (filter (ConstructorBuilder, criteria))
-                                       members.Add (ConstructorBuilder);
-
-                               if (InvokeBuilder != null)
-                               if (filter (InvokeBuilder, criteria))
-                                       members.Add (InvokeBuilder);
-
-                               if (BeginInvokeBuilder != null)
-                               if (filter (BeginInvokeBuilder, criteria))
-                                       members.Add (BeginInvokeBuilder);
-
-                               if (EndInvokeBuilder != null)
-                               if (filter (EndInvokeBuilder, criteria))
-                                       members.Add (EndInvokeBuilder);
-                       }
-
-                       return new MemberList (members);
-               }
-
                public override MemberCache MemberCache {
                        get {
-                               return null;
+                               return member_cache;
                        }
                }
 
@@ -606,170 +618,222 @@ namespace Mono.CSharp {
                        get { return "T:"; }
                }
 
+               #region IMemberContainer Members
+
+               string IMemberContainer.Name
+               {
+                       get { throw new NotImplementedException (); }
+               }
+
+               Type IMemberContainer.Type
+               {
+                       get { throw new NotImplementedException (); }
+               }
+
+               MemberCache IMemberContainer.BaseCache
+               {
+                       get { throw new NotImplementedException (); }
+               }
+
+               bool IMemberContainer.IsInterface {
+                       get {
+                               return false;
+                       }
+               }
+
+               MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               #endregion
        }
 
        //
        // Base class for `NewDelegate' and `ImplicitDelegateCreation'
        //
-       public abstract class DelegateCreation : Expression {
-               protected MethodBase constructor_method;
-               protected MethodBase delegate_method;
+       public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
+       {
+               protected ConstructorInfo constructor_method;
+               protected MethodInfo delegate_method;
+               // We keep this to handle IsBase only
                protected MethodGroupExpr method_group;
                protected Expression delegate_instance_expression;
 
-               public DelegateCreation () {}
+               ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method)
+               {
+                       ParameterData pd = TypeManager.GetParameterData (invoke_method);
+                       ArrayList delegate_arguments = new ArrayList (pd.Count);
+                       for (int i = 0; i < pd.Count; ++i) {
+                               Argument.AType atype_modifier;
+                               Type atype = pd.Types [i];
+                               switch (pd.ParameterModifier (i)) {
+                                       case Parameter.Modifier.REF:
+                                               atype_modifier = Argument.AType.Ref;
+                                               atype = atype.GetElementType ();
+                                               break;
+                                       case Parameter.Modifier.OUT:
+                                               atype_modifier = Argument.AType.Out;
+                                               atype = atype.GetElementType ();
+                                               break;
+                                       case Parameter.Modifier.ARGLIST:
+                                               // __arglist is not valid
+                                               throw new InternalErrorException ("__arglist modifier");
+                                       default:
+                                               atype_modifier = Argument.AType.Expression;
+                                               break;
+                               }
+                               delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
+                       }
+                       return delegate_arguments;
+               }
 
-               public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
+               public override Expression DoResolve (EmitContext ec)
                {
-                       string method_desc;
-                       MethodInfo found_method = (MethodInfo)mg.Methods [0];
-                       
-                       if (mg.Methods.Length > 1)
-                               method_desc = found_method.Name;
-                       else
-                               method_desc = Invocation.FullMethodDesc (found_method);
+                       constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
 
-                       Expression invoke_method = Expression.MemberLookup (
-                               ec, type, "Invoke", MemberTypes.Method,
-                               Expression.AllBindingFlags, loc);
-                       MethodInfo method = ((MethodGroupExpr) invoke_method).Methods [0] as MethodInfo;
+                       MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
+                       method_group.DelegateType = type;
+                       method_group.CustomErrorHandler = this;
 
-                       ParameterData param = TypeManager.GetParameterData (method);
-                       string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
+                       ArrayList arguments = CreateDelegateMethodArguments (invoke_method);
+                       method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
+                       if (method_group == null)
+                               return null;
 
-                       if (method.ReturnType != found_method.ReturnType) {
-                               Report.Error (407, loc, "`{0}' has the wrong return type to match the delegate `{1}'", method_desc, delegate_desc);
-                       } else {
-                               Report.Error (123, loc, "Method `{0}' does not match delegate `{1}'", method_desc, delegate_desc);
+                       delegate_method = (MethodInfo) method_group;
+                       ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
+                       if (emg != null) {
+                               delegate_instance_expression = emg.ExtensionExpression;
+                               Type e_type = delegate_instance_expression.Type;
+                               if (TypeManager.IsValueType (e_type)) {
+                                       Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
+                                               TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
+                               }
                        }
+
+                       Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
+                       Expression ret_expr = new TypeExpression (rt, loc);
+                       if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
+                               Error_ConversionFailed (ec, delegate_method, ret_expr);
+                       }
+
+                       DoResolveInstanceExpression (ec);
+                       eclass = ExprClass.Value;
+                       return this;
+               }
+
+               void DoResolveInstanceExpression (EmitContext ec)
+               {
+                       //
+                       // Argument is another delegate
+                       //
+                       if (delegate_instance_expression != null)
+                               return;
+                       
+                       if (method_group.InstanceExpression != null)
+                               delegate_instance_expression = method_group.InstanceExpression;
+                       else if (!delegate_method.IsStatic && !ec.IsStatic)
+                               delegate_instance_expression = ec.GetThis (loc);
+
+                       if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
+                               delegate_instance_expression = new BoxedCast (
+                                       delegate_instance_expression, TypeManager.object_type);
                }
                
                public override void Emit (EmitContext ec)
                {
-                       if (delegate_instance_expression == null || delegate_method.IsStatic)
+                       if (delegate_instance_expression == null)
                                ec.ig.Emit (OpCodes.Ldnull);
                        else
                                delegate_instance_expression.Emit (ec);
-                       
-                       if (delegate_method.IsVirtual && !method_group.IsBase) {
+
+                       if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
                                ec.ig.Emit (OpCodes.Dup);
                                ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
                        } else
                                ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
-                       ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
+                       ec.ig.Emit (OpCodes.Newobj, constructor_method);
                }
 
-               protected bool ResolveConstructorMethod (EmitContext ec)
+               void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
                {
-                       Expression ml = Expression.MemberLookup (
-                               ec, type, ".ctor", loc);
-
-                       if (!(ml is MethodGroupExpr)) {
-                               Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
-                               return false;
+                       MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
+                       string member_name = delegate_instance_expression != null ?
+                               Delegate.FullDelegateDesc (method) :
+                               TypeManager.GetFullNameSignature (method);
+
+                       Report.SymbolRelatedToPreviousError (type);
+                       Report.SymbolRelatedToPreviousError (method);
+                       if (RootContext.Version == LanguageVersion.ISO_1) {
+                               Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
+                                       TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
+                                       TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
+                               return;
+                       }
+                       if (return_type == null) {
+                               Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
+                                       member_name, Delegate.FullDelegateDesc (invoke_method));
+                               return;
                        }
 
-                       constructor_method = ((MethodGroupExpr) ml).Methods [0];
-                       return true;
+                       Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
+                               return_type.GetSignatureForError (), member_name,
+                               TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
                }
 
-               protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg,
-                                                            bool check_only)
+               public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
                {
-                       foreach (MethodInfo mi in mg.Methods){
-                               delegate_method  = Delegate.VerifyMethod (ec, type, mi, loc);
-                               
-                               if (delegate_method != null)
-                                       break;
-                       }
-                       
-                       if (delegate_method == null) {
-                               if (!check_only)
-                                       Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
+                       if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
                                return null;
+
+                       foreach (MethodInfo mi in mg.Methods){
+                               MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
+                               if (mb != null)
+                                       return mb;
                        }
-                       
-                       //
-                       // Check safe/unsafe of the delegate
-                       //
-                       if (!ec.InUnsafe){
-                               ParameterData param = TypeManager.GetParameterData (delegate_method);
-                               int count = param.Count;
-                               
-                               for (int i = 0; i < count; i++){
-                                       if (param.ParameterType (i).IsPointer){
-                                               Expression.UnsafeError (loc);
-                                               return null;
-                                       }
-                               }
-                       }
-                       
-                       //TODO: implement caching when performance will be low
-                       IMethodData md = TypeManager.GetMethod (delegate_method);
-                       if (md == null) {
-                               if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
-                                       Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
-                               }
-                       } else {
-                               md.SetMemberIsUsed ();
-                               if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
-                                       Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
-                               }
-                       }
-                       
-                       if (mg.InstanceExpression != null)
-                               delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
-                       else if (ec.IsStatic) {
-                               if (!delegate_method.IsStatic) {
-                                       Report.Error (120, loc, "`{0}': An object reference is required for the nonstatic field, method or property",
-                                                     TypeManager.CSharpSignature (delegate_method));
-                                       return null;
-                               }
-                               delegate_instance_expression = null;
-                       } else
-                               delegate_instance_expression = ec.GetThis (loc);
-                       
-                       if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
-                               delegate_instance_expression = new BoxedCast (
-                                       delegate_instance_expression, TypeManager.object_type);
-                       
-                       method_group = mg;
-                       eclass = ExprClass.Value;
-                       return this;
+                       return null;
+               }
+
+               #region IErrorHandler Members
+
+               public bool NoExactMatch (EmitContext ec, MethodBase method)
+               {
+                       if (TypeManager.IsGenericMethod (method))
+                               return false;
+
+                       Error_ConversionFailed (ec, method, null);
+                       return true;
                }
+
+               #endregion
        }
 
        //
        // Created from the conversion code
        //
-       public class ImplicitDelegateCreation : DelegateCreation {
-
-               ImplicitDelegateCreation (Type t, Location l)
+       public class ImplicitDelegateCreation : DelegateCreation
+       {
+               ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
                {
                        type = t;
+                       this.method_group = mg;
                        loc = l;
                }
 
-               public override Expression DoResolve (EmitContext ec)
-               {
-                       return this;
-               }
-
                static public Expression Create (EmitContext ec, MethodGroupExpr mge,
-                                                Type target_type, bool check_only, Location loc)
+                                                Type target_type, Location loc)
                {
-                       ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
-                       if (d.ResolveConstructorMethod (ec))
-                               return d.ResolveMethodGroupExpr (ec, mge, check_only);
-                       else
-                               return null;
+                       ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
+                       return d.DoResolve (ec);
                }
        }
-
+       
        //
        // A delegate-creation-expression, invoked from the `New' class 
        //
-       public class NewDelegate : DelegateCreation {
+       public class NewDelegate : DelegateCreation
+       {
                public ArrayList Arguments;
 
                //
@@ -784,65 +848,65 @@ namespace Mono.CSharp {
 
                public override Expression DoResolve (EmitContext ec)
                {
-                       if (Arguments == null || Arguments.Count != 1) {
-                               Report.Error (149, loc,
-                                             "Method name expected");
+                       if (Arguments == null) {
+                               Error_InvalidDelegateArgument ();
                                return null;
                        }
 
-                       if (!ResolveConstructorMethod (ec))
-                               return null;
-
                        Argument a = (Argument) Arguments [0];
-
-                       if (!a.ResolveMethodGroup (ec, loc))
+                       if (!a.ResolveMethodGroup (ec))
                                return null;
                        
                        Expression e = a.Expr;
+                       if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1) {
+                               e = ((AnonymousMethodExpression) e).Compatible (ec, type);
+                               if (e == null)
+                                       return null;
+                               return e.Resolve (ec);
+                       }
 
-                       if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
-                               return ((AnonymousMethod) e).Compatible (ec, type, false);
-
-                       MethodGroupExpr mg = e as MethodGroupExpr;
-                       if (mg != null)
-                               return ResolveMethodGroupExpr (ec, mg, false);
-
-                       Type e_type = e.Type;
+                       method_group = e as MethodGroupExpr;
+                       if (method_group == null) {
+                               if (!TypeManager.IsDelegateType (e.Type)) {
+                                       Report.Error (149, loc, "Method name expected");
+                                       return null;
+                               }
 
-                       if (!TypeManager.IsDelegateType (e_type)) {
-                               Report.Error (149, loc, "Method name expected");
-                               return null;
+                               //
+                               // An argument is not a method but another delegate
+                               //
+                               delegate_instance_expression = e;
+                               method_group = new MethodGroupExpr (new MemberInfo [] { 
+                                       Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
                        }
 
-                       method_group = Expression.MemberLookup (
-                               ec, type, "Invoke", MemberTypes.Method,
-                               Expression.AllBindingFlags, loc) as MethodGroupExpr;
-
-                       if (method_group == null) {
-                               Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
+                       if (base.DoResolve (ec) == null)
                                return null;
+
+                       if (TypeManager.IsNullableType (method_group.DeclaringType)) {
+                               Report.Error (1728, loc, "Cannot use method `{0}' as delegate creation expression because it is member of Nullable type",
+                                       TypeManager.GetFullNameSignature (delegate_method));
                        }
 
-                       // This is what MS' compiler reports. We could always choose
-                       // to be more verbose and actually give delegate-level specifics                        
-                       if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
-                               Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
-                                             "to type '" + type + "'");
-                               return null;
+                       if (Invocation.IsMethodExcluded (delegate_method)) {
+                               Report.SymbolRelatedToPreviousError (delegate_method);
+                               Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
+                                       TypeManager.CSharpSignature (delegate_method));
                        }
-                               
-                       delegate_instance_expression = e;
-                       delegate_method = method_group.Methods [0];
-                       
-                       eclass = ExprClass.Value;
+
                        return this;
                }
+
+               void Error_InvalidDelegateArgument ()
+               {
+                       Report.Error (149, loc, "Method name expected");
+               }
        }
 
        public class DelegateInvocation : ExpressionStatement {
 
-               public Expression InstanceExpr;
-               public ArrayList  Arguments;
+               readonly Expression InstanceExpr;
+               readonly ArrayList  Arguments;
 
                MethodBase method;
                
@@ -860,7 +924,7 @@ namespace Mono.CSharp {
                                EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
                                
                                Expression ml = MemberLookup (
-                                       ec, ec.ContainerType, ei.Name,
+                                       ec.ContainerType, ec.ContainerType, ei.Name,
                                        MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
 
                                if (ml == null) {
@@ -894,14 +958,9 @@ namespace Mono.CSharp {
                        if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
                                return null;
 
-                       Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
-                       if (!(lookup is MethodGroupExpr)) {
-                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");
-                               return null;
-                       }
-                       
-                       method = ((MethodGroupExpr) lookup).Methods [0];
+                       method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
                        type = ((MethodInfo) method).ReturnType;
+                       type = TypeManager.TypeToCoreType (type);
                        eclass = ExprClass.Value;
                        
                        return this;
@@ -913,7 +972,7 @@ namespace Mono.CSharp {
                        // Invocation on delegates call the virtual Invoke member
                        // so we are always `instance' calls
                        //
-                       Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
+                       Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
                }
 
                public override void EmitStatement (EmitContext ec)
@@ -923,7 +982,8 @@ namespace Mono.CSharp {
                        // Pop the return value if there is one
                        //
                        if (method is MethodInfo){
-                               if (((MethodInfo) method).ReturnType != TypeManager.void_type)
+                               Type ret = ((MethodInfo)method).ReturnType;
+                               if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
                                        ec.ig.Emit (OpCodes.Pop);
                        }
                }