2008-03-27 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / mcs / delegate.cs
index bd6f03e290100cf97e4734a840a19943cff89e30..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 |
@@ -78,18 +85,6 @@ namespace Mono.CSharp {
                        if (TypeBuilder != null)
                                return TypeBuilder;
 
-                       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.Type;
-                       }
-
-                       if (TypeManager.multicast_delegate_type == null)
-                               Report.Error (-100, Location, "Internal error: delegate used before " +
-                                             "System.MulticastDelegate is resolved.  This can only " +
-                                             "happen during corlib compilation, when using a delegate " +
-                                             "in any of the `core' classes.  See bug #72015 for details.");
-
                        if (IsTopLevel) {
                                if (TypeManager.NamespaceClash (Name, Location))
                                        return null;
@@ -159,6 +154,7 @@ namespace Mono.CSharp {
                                }
                        }
 #endif
+                       member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
 
                        // FIXME: POSSIBLY make this static, as it is always constant
                        //
@@ -187,7 +183,7 @@ namespace Mono.CSharp {
                        const_parameters.Resolve (null);
                        
                        TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
-                               
+                       member_cache.AddMember (ConstructorBuilder, this);
                        
                        ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
 
@@ -206,11 +202,12 @@ 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;
                                }
                        }
@@ -221,14 +218,17 @@ namespace Mono.CSharp {
 
                        ret_type = ReturnType.Type;
             
-                       if (!Parent.AsAccessible (ret_type, ModFlags)) {
+                       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;
                        }
 
+                       CheckProtectedModifier ();
+
                        if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
                                Method.Error1599 (Location, ret_type);
                                return false;
@@ -241,8 +241,6 @@ namespace Mono.CSharp {
                        
                        CallingConventions cc = Parameters.CallingConvention;
 
-                       const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
-
                        InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", 
                                                                  mattr,                     
                                                                  cc,
@@ -252,21 +250,30 @@ namespace Mono.CSharp {
                        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
                        //
-                       
-                       Parameters async_parameters = Parameters.MergeGenerated (Parameters, 
+                       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));
-                       
+
                        BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
                                mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
 
                        BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
-                       async_parameters.ApplyAttributes (BeginInvokeBuilder);
                        TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
+                       member_cache.AddMember (BeginInvokeBuilder, this);
 
                        //
                        // EndInvoke is a bit more interesting, all the parameters labeled as
@@ -286,27 +293,26 @@ namespace Mono.CSharp {
 
                        if (out_params > 0) {
                                Type [] end_param_types = new Type [out_params];
-                               Parameter [] end_params = new Parameter [out_params ];
+                               Parameter [] end_params = new Parameter [out_params];
 
-                               int param = 0; 
+                               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] = p.ExternalType();
+                                       end_param_types [param] = p.ExternalType ();
                                        end_params [param] = p;
                                        ++param;
                                }
-                               end_parameters = new Parameters (end_params, end_param_types);
-                       }
-                       else {
+                               end_parameters = Parameters.CreateFullyResolved (end_params, end_param_types);
+                       } else {
                                end_parameters = Parameters.EmptyReadOnlyParameters;
                        }
 
                        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
                        //
@@ -315,14 +321,18 @@ namespace Mono.CSharp {
 
                        end_parameters.ApplyAttributes (EndInvokeBuilder);
                        TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
-
-                       return true;
+                       member_cache.AddMember (EndInvokeBuilder, this);
                }
 
                public override void Emit ()
                {
                        Parameters.ApplyAttributes (InvokeBuilder);
 
+                       if (BeginInvokeBuilder != null) {
+                               Parameters p = (Parameters) TypeManager.GetParameterData (BeginInvokeBuilder);
+                               p.ApplyAttributes (BeginInvokeBuilder);
+                       }
+
                        if (OptAttributes != null) {
                                OptAttributes.Emit ();
                        }
@@ -359,22 +369,97 @@ 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 MethodGroupExpr GetInvokeMethod (Type container_type, Type delegate_type, Location loc)
+               public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
                {
-                       Expression ml = Expression.MemberLookup (container_type, null, 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;
+                       }
+
+                       Expression ml = Expression.MemberLookup (container_type, null, dt,
+                               "Invoke", Location.Null);
 
                        MethodGroupExpr mg = ml as MethodGroupExpr;
                        if (mg == null) {
-                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");
+                               Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
+                               // FIXME: null will cause a crash later
                                return null;
                        }
 
-                       return mg;
+                       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>
@@ -385,18 +470,14 @@ namespace Mono.CSharp {
                                                       MethodGroupExpr old_mg, MethodBase mb,
                                                       Location loc)
                {
-                       MethodGroupExpr mg = GetInvokeMethod (container_type, delegate_type, loc);
-                       if (mg == null)
+                       MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
+                       if (invoke_mb == null)
                                return null;
 
-                       if (old_mg.HasTypeArguments)
-                               mg.HasTypeArguments = true;
-
-                       MethodBase invoke_mb = mg.Methods [0];
                        ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
 
 #if GMCS_SOURCE
-                       if (!mg.HasTypeArguments &&
+                       if (old_mg.type_arguments == null &&
                            !TypeManager.InferTypeArguments (invoke_pd, ref mb))
                                return null;
 #endif
@@ -417,35 +498,31 @@ namespace Mono.CSharp {
                                invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
                                pd_type_mod &= ~Parameter.Modifier.PARAMS;
 
-                               if (invoke_pd_type == pd_type &&
-                                   invoke_pd_type_mod == pd_type_mod)
+                               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>
@@ -471,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, me, args, arg_count, ref mb);
-
-                       if (!is_applicable && params_method &&
-                           Invocation.IsParamsMethodApplicable (ec, me, args, arg_count, ref 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",
@@ -490,98 +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);
+                                       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, Location loc)
+               public static string FullDelegateDesc (MethodBase invoke_method)
                {
-                       Expression ml = Expression.MemberLookup (
-                               ec.ContainerType, 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.ContainerType, 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;
-               }
-               
-               public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
-               {
-                       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 (2);
-
-                       if ((mt & MemberTypes.Constructor) != 0) {
-                               if (ConstructorBuilder != null && filter (ConstructorBuilder, criteria))
-                                       members.Add (ConstructorBuilder);
-                       }
-
-                       if ((mt & MemberTypes.Method) != 0) {
-                               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;
                        }
                }
 
@@ -622,187 +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;
 
-               protected DelegateCreation () {}
-
-               public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
+               ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method)
                {
-                       string method_desc;
-                       MethodBase found_method = mg.Methods [0];
+                       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;
+               }
 
-                       if (mg.Methods.Length > 1)
-                               method_desc = found_method.Name;
-                       else
-                               method_desc = Invocation.FullMethodDesc (found_method);
+               public override Expression DoResolve (EmitContext ec)
+               {
+                       constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
 
-                       Expression invoke_method = Expression.MemberLookup (
-                               ec.ContainerType, 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 GMCS_SOURCE
-                       if (!mg.HasTypeArguments &&
-                           !TypeManager.InferTypeArguments (param, ref found_method)) {
-                               Report.Error (411, loc, "The type arguments for " +
-                                             "method `{0}' cannot be infered from " +
-                                             "the usage. Try specifying the type " +
-                                             "arguments explicitly.", method_desc);
-                               return;
+                       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));
+                               }
                        }
-#endif
-                       if (method.ReturnType != ((MethodInfo) 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);
+
+                       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.MemberLookupFinal(ec, 
-                               null, type, ".ctor", MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, 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));
                }
 
-               public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type targetType)
+               public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
                {
+                       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, targetType, mg, mi, Location.Null);
+                               MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
                                if (mb != null)
                                        return mb;
                        }
                        return null;
                }
 
-               protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
-               {
-                       delegate_method = ImplicitStandardConversionExists (mg, type);
+               #region IErrorHandler Members
 
-                       if (delegate_method == null) {
-                               Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
-                               return null;
-                       }
-                       
-                       //
-                       // 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.SymbolRelatedToPreviousError (delegate_method);
-                                       Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
-                                       return null;
-                               }
-                       } else {
-                               md.SetMemberIsUsed ();
-                               if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type) != null) {
-                                       Report.SymbolRelatedToPreviousError (delegate_method);
-                                       Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
-                                       return null;
-                               }
-                       }
-                       
-                       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);
+               public bool NoExactMatch (EmitContext ec, MethodBase method)
+               {
+                       if (TypeManager.IsGenericMethod (method))
+                               return false;
 
-                       method_group = mg;
-                       eclass = ExprClass.Value;
-                       return this;
+                       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, Location loc)
                {
-                       ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
-                       if (!d.ResolveConstructorMethod (ec))
-                               return null;
-
-                       return d.ResolveMethodGroupExpr (ec, mge);
+                       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;
 
                //
@@ -817,63 +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))
                                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 AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1)
-                               return ((AnonymousMethodExpression) e).Compatible (ec, type);
-
-                       MethodGroupExpr mg = e as MethodGroupExpr;
-                       if (mg != null)
-                               return ResolveMethodGroupExpr (ec, mg);
+                       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.ContainerType, 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, 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;
                
@@ -925,14 +958,9 @@ namespace Mono.CSharp {
                        if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
                                return null;
 
-                       Expression lookup = Expression.MemberLookup (ec.ContainerType, 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;
@@ -944,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)