2002-08-06 Martin Baulig <martin@gnome.org>
[mono.git] / mcs / mcs / delegate.cs
index 1c74b729b2e21a12a188e6e6d40a255b45e28cdf..11d9cfad90dfac6f5d34d885204777f9ace70b10 100644 (file)
@@ -15,81 +15,84 @@ using System.Reflection;
 using System.Reflection.Emit;\r
 using System.Text;\r
 \r
-namespace CIR {\r
-       \r
-       public class Delegate {\r
+namespace Mono.CSharp {\r
 \r
-               public readonly string Name;\r
-               public readonly string ReturnType;\r
-               public int             mod_flags;\r
+       /// <summary>\r
+       ///   Holds Delegates\r
+       /// </summary>\r
+       public class Delegate : DeclSpace {\r
+               public Expression ReturnType;\r
                public Parameters      Parameters;\r
                public Attributes      OptAttributes;\r
-               public TypeBuilder     TypeBuilder;\r
 \r
                public ConstructorBuilder ConstructorBuilder;\r
                public MethodBuilder      InvokeBuilder;\r
                public MethodBuilder      BeginInvokeBuilder;\r
                public MethodBuilder      EndInvokeBuilder;\r
                \r
-               public readonly RootContext RootContext;\r
-\r
                Type [] param_types;\r
                Type ret_type;\r
                \r
                Expression instance_expr;\r
                MethodBase delegate_method;\r
        \r
-               Location loc;\r
-\r
                const int AllowedModifiers =\r
                        Modifiers.NEW |\r
                        Modifiers.PUBLIC |\r
                        Modifiers.PROTECTED |\r
                        Modifiers.INTERNAL |\r
+                       Modifiers.UNSAFE |\r
                        Modifiers.PRIVATE;\r
 \r
-               public Delegate (RootContext rc, string type, int mod_flags, string name, Parameters param_list,\r
-                                Attributes attrs, Location loc)\r
+               public Delegate (TypeContainer parent, Expression type, int mod_flags,\r
+                                string name, Parameters param_list,\r
+                                Attributes attrs, Location l)\r
+                       : base (parent, name, l)\r
                {\r
-                       this.RootContext = rc;\r
-                       this.Name       = name;\r
                        this.ReturnType = type;\r
-                       this.mod_flags  = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);\r
+                       ModFlags        = Modifiers.Check (AllowedModifiers, mod_flags,\r
+                                                          IsTopLevel ? Modifiers.INTERNAL :\r
+                                                          Modifiers.PRIVATE, l);\r
                        Parameters      = param_list;\r
                        OptAttributes   = attrs;\r
-                       this.loc        = loc;\r
                }\r
 \r
-               public void DefineDelegate (object parent_builder)\r
+               public override TypeBuilder DefineType ()\r
                {\r
                        TypeAttributes attr;\r
+\r
+                       if (TypeBuilder != null)\r
+                               return TypeBuilder;\r
                        \r
-                       if (parent_builder is ModuleBuilder) {\r
-                               ModuleBuilder builder = (ModuleBuilder) parent_builder;\r
-                               \r
+                       if (IsTopLevel) {\r
+                               ModuleBuilder builder = CodeGen.ModuleBuilder;\r
                                attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;\r
 \r
-                               TypeBuilder = builder.DefineType (Name, attr, TypeManager.delegate_type);\r
-                                                                 \r
+                               TypeBuilder = builder.DefineType (\r
+                                       Name, attr, TypeManager.multicast_delegate_type);\r
                        } else {\r
-                               TypeBuilder builder = (TypeBuilder) parent_builder;\r
-                               \r
-                               attr = TypeAttributes.NestedPublic | TypeAttributes.Class | TypeAttributes.Sealed;\r
-\r
-                               TypeBuilder = builder.DefineNestedType (Name, attr, TypeManager.delegate_type);\r
+                               TypeBuilder builder = Parent.TypeBuilder;\r
+                               attr = TypeAttributes.NestedPublic | TypeAttributes.Class |\r
+                                       TypeAttributes.Sealed;\r
 \r
+                               string name = Name.Substring (1 + Name.LastIndexOf ('.'));\r
+                               TypeBuilder = builder.DefineNestedType (\r
+                                       name, attr, TypeManager.multicast_delegate_type);\r
                        }\r
 \r
-                       RootContext.TypeManager.AddDelegateType (Name, TypeBuilder, this);\r
+                       TypeManager.AddDelegateType (Name, TypeBuilder, this);\r
+\r
+                       return TypeBuilder;\r
                }\r
 \r
-               public void Populate (TypeContainer parent)\r
+               public override bool Define (TypeContainer container)\r
                {\r
-\r
                        MethodAttributes mattr;\r
-                       \r
-                       Type [] const_arg_types = new Type [2];\r
+                       int i;\r
 \r
+                       // FIXME: POSSIBLY make this static, as it is always constant\r
+                       //\r
+                       Type [] const_arg_types = new Type [2];\r
                        const_arg_types [0] = TypeManager.object_type;\r
                        const_arg_types [1] = TypeManager.intptr_type;\r
 \r
@@ -99,13 +102,72 @@ namespace CIR {
                        ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,\r
                                                                            CallingConventions.Standard,\r
                                                                            const_arg_types);\r
+\r
+                       ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");\r
+                       ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");\r
+                       //\r
+                       // HACK because System.Reflection.Emit is lame\r
+                       //\r
+                       //\r
+                       // FIXME: POSSIBLY make these static, as they are always the same\r
+                       Parameter [] fixed_pars = new Parameter [2];\r
+                       fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);\r
+                       fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);\r
+                       Parameters const_parameters = new Parameters (fixed_pars, null, Location);\r
                        \r
-                       ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
+                       TypeManager.RegisterMethod (\r
+                               ConstructorBuilder,\r
+                               new InternalParameters (const_arg_types, const_parameters),\r
+                               const_arg_types);\r
+                               \r
                        \r
+                       ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
+\r
+                       //\r
                        // Here the various methods like Invoke, BeginInvoke etc are defined\r
+                       //\r
+                       // First, call the `out of band' special method for\r
+                       // defining recursively any types we need:\r
+                       \r
+                       if (!Parameters.ComputeAndDefineParameterTypes (this))\r
+                               return false;\r
+                       \r
+                       param_types = Parameters.GetParameterInfo (this);\r
+                       if (param_types == null)\r
+                               return false;\r
+\r
+                       //\r
+                       // Invoke method\r
+                       //\r
+\r
+                       // Check accessibility\r
+                       foreach (Type partype in param_types)\r
+                               if (!container.AsAccessible (partype, ModFlags)) {\r
+                                       Report.Error (59, Location,\r
+                                                     "Inconsistent accessibility: parameter type `" +\r
+                                                     TypeManager.CSharpName (partype) + "` is less " +\r
+                                                     "accessible than delegate `" + Name + "'");\r
+                                       return false;\r
+                               }\r
+                       \r
+                       ReturnType = ResolveTypeExpr (ReturnType, false, Location);\r
+                       ret_type = ReturnType.Type;\r
+                       if (ret_type == null)\r
+                               return false;\r
 \r
-                       param_types = Parameters.GetParameterInfo (parent);\r
-                       ret_type = parent.LookupType (ReturnType, false);\r
+                       if (!container.AsAccessible (ret_type, ModFlags)) {\r
+                               Report.Error (58, Location,\r
+                                             "Inconsistent accessibility: return type `" +\r
+                                             TypeManager.CSharpName (ret_type) + "` is less " +\r
+                                             "accessible than delegate `" + Name + "'");\r
+                               return false;\r
+                       }\r
+\r
+                       //\r
+                       // We don't have to check any others because they are all\r
+                       // guaranteed to be accessible - they are standard types.\r
+                       //\r
+                       \r
                        CallingConventions cc = Parameters.GetCallingConvention ();\r
 \r
                        mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;\r
@@ -115,9 +177,35 @@ namespace CIR {
                                                                  cc,\r
                                                                  ret_type,                  \r
                                                                  param_types);\r
+\r
+                       i = 0;\r
+                       if (Parameters.FixedParameters != null){\r
+                               int top = Parameters.FixedParameters.Length;\r
+                               Parameter p;\r
+                               \r
+                               for (; i < top; i++) {\r
+                                       p = Parameters.FixedParameters [i];\r
+\r
+                                       InvokeBuilder.DefineParameter (\r
+                                               i+1, p.Attributes, p.Name);\r
+                               }\r
+                       }\r
+                       if (Parameters.ArrayParameter != null){\r
+                               Parameter p = Parameters.ArrayParameter;\r
+                               \r
+                               InvokeBuilder.DefineParameter (\r
+                                       i+1, p.Attributes, p.Name);\r
+                       }\r
                        \r
                        InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
 \r
+                       TypeManager.RegisterMethod (InvokeBuilder,\r
+                                                   new InternalParameters (container, Parameters),\r
+                                                   param_types);\r
+\r
+                       //\r
+                       // BeginInvoke\r
+                       //\r
                        int params_num = param_types.Length;\r
                        Type [] async_param_types = new Type [params_num + 2];\r
 \r
@@ -126,19 +214,67 @@ namespace CIR {
                        async_param_types [params_num] = TypeManager.asynccallback_type;\r
                        async_param_types [params_num + 1] = TypeManager.object_type;\r
 \r
-                       mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |\r
-                               MethodAttributes.NewSlot;\r
+                       mattr = MethodAttributes.Public | MethodAttributes.HideBySig |\r
+                               MethodAttributes.Virtual | MethodAttributes.NewSlot;\r
                        \r
                        BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",\r
                                                                       mattr,\r
                                                                       cc,\r
                                                                       TypeManager.iasyncresult_type,\r
                                                                       async_param_types);\r
+\r
+                       i = 0;\r
+                       if (Parameters.FixedParameters != null){\r
+                               int top = Parameters.FixedParameters.Length;\r
+                               Parameter p;\r
+                               \r
+                               for (i = 0 ; i < top; i++) {\r
+                                       p = Parameters.FixedParameters [i];\r
+\r
+                                       BeginInvokeBuilder.DefineParameter (\r
+                                               i+1, p.Attributes, p.Name);\r
+                               }\r
+                       }\r
+                       if (Parameters.ArrayParameter != null){\r
+                               Parameter p = Parameters.ArrayParameter;\r
+                               \r
+                               BeginInvokeBuilder.DefineParameter (\r
+                                       i+1, p.Attributes, p.Name);\r
+                               i++;\r
+                       }\r
+\r
+                       BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");\r
+                       BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");\r
                        \r
                        BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
 \r
+                       Parameter [] async_params = new Parameter [params_num + 2];\r
+                       int n = 0;\r
+                       if (Parameters.FixedParameters != null){\r
+                               Parameters.FixedParameters.CopyTo (async_params, 0);\r
+                               n = Parameters.FixedParameters.Length;\r
+                       }\r
+                       if (Parameters.ArrayParameter != null)\r
+                               async_params [n] = Parameters.ArrayParameter;\r
+                       \r
+                       async_params [params_num] = new Parameter (\r
+                               TypeManager.system_asynccallback_expr, "callback",\r
+                                                                  Parameter.Modifier.NONE, null);\r
+                       async_params [params_num + 1] = new Parameter (\r
+                               TypeManager.system_object_expr, "object",\r
+                                                                  Parameter.Modifier.NONE, null);\r
+\r
+                       Parameters async_parameters = new Parameters (async_params, null, Location);\r
+                       \r
+                       async_parameters.ComputeAndDefineParameterTypes (this);\r
+                       TypeManager.RegisterMethod (BeginInvokeBuilder,\r
+                                                   new InternalParameters (container, async_parameters),\r
+                                                   async_param_types);\r
+\r
+                       //\r
+                       // EndInvoke\r
+                       //\r
                        Type [] end_param_types = new Type [1];\r
-\r
                        end_param_types [0] = TypeManager.iasyncresult_type;\r
                        \r
                        EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",\r
@@ -146,48 +282,74 @@ namespace CIR {
                                                                     cc,\r
                                                                     ret_type,\r
                                                                     end_param_types);\r
-\r
-                       EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
+                       EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");\r
                        \r
+                       EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);\r
+\r
+                       Parameter [] end_params = new Parameter [1];\r
+                       end_params [0] = new Parameter (\r
+                               TypeManager.system_iasyncresult_expr, "result",\r
+                                                       Parameter.Modifier.NONE, null);\r
+\r
+                       TypeManager.RegisterMethod (\r
+                               EndInvokeBuilder, new InternalParameters (\r
+                                       container,\r
+                                       new Parameters (\r
+                                               end_params, null, Location)),\r
+                                                   end_param_types);\r
+\r
+                       return true;\r
                }\r
 \r
-               public MethodBase VerifyMethod (MethodBase mb, Location loc)\r
+               /// <summary>\r
+               ///  Verifies whether the method in question is compatible with the delegate\r
+               ///  Returns the method itself if okay and null if not.\r
+               /// </summary>\r
+               public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,\r
+                                                      Location loc)\r
                {\r
                        ParameterData pd = Invocation.GetParameterData (mb);\r
 \r
-                       bool mismatch = false;\r
-                       for (int i = param_types.Length; i > 0; ) {\r
-                               i--;\r
+                       int pd_count = pd.Count;\r
 \r
-                               if (param_types [i] == pd.ParameterType (i))\r
-                                       continue;\r
-                               else {\r
-                                       mismatch = true;\r
-                                       break;\r
-                               }\r
-                       }\r
+                       Expression ml = Expression.MemberLookup (\r
+                               ec, delegate_type, "Invoke", loc);\r
 \r
-                       if (mismatch) {\r
-                               Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
-                                             "delegate '" + FullDelegateDesc () + "'");\r
+                       if (!(ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error : could not find Invoke method!");\r
                                return null;\r
                        }\r
 \r
-                       if (ret_type == ((MethodInfo) mb).ReturnType)\r
-                               return mb;\r
-                       else\r
-                               mismatch = true;\r
+                       MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];\r
+\r
+                       ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);\r
 \r
-                       if (mismatch) {\r
-                               Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +\r
-                                             "delegate '" + FullDelegateDesc () + "'");\r
+                       if (invoke_pd.Count != pd_count)\r
                                return null;\r
+\r
+                       for (int i = pd_count; i > 0; ) {\r
+                               i--;\r
+\r
+                               if (invoke_pd.ParameterType (i) == pd.ParameterType (i))\r
+                                       continue;\r
+                               else\r
+                                       return null;\r
                        }\r
 \r
-                       return null;\r
+                       if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)\r
+                               return mb;\r
+                       else\r
+                               return null;\r
                }\r
 \r
-               public bool VerifyApplicability (EmitContext ec, ArrayList args, Location loc)\r
+               // <summary>\r
+               //  Verifies whether the invocation arguments are compatible with the\r
+               //  delegate's target method\r
+               // </summary>\r
+               public static bool VerifyApplicability (EmitContext ec,\r
+                                                       Type delegate_type,\r
+                                                       ArrayList args,\r
+                                                       Location loc)\r
                {\r
                        int arg_count;\r
 \r
@@ -195,56 +357,91 @@ namespace CIR {
                                arg_count = 0;\r
                        else\r
                                arg_count = args.Count;\r
+\r
+                       Expression ml = Expression.MemberLookup (\r
+                               ec, delegate_type, "Invoke", loc);\r
+                       \r
+                       if (!(ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error : could not find Invoke method!");\r
+                               return false;\r
+                       }\r
                        \r
-                       if (param_types.Length != arg_count) {\r
+                       MethodBase mb = ((MethodGroupExpr) ml).Methods [0];\r
+                       ParameterData pd = Invocation.GetParameterData (mb);\r
+\r
+                       int pd_count = pd.Count;\r
+\r
+                       bool not_params_method = (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);\r
+\r
+                       if (not_params_method && pd_count != arg_count) {\r
                                Report.Error (1593, loc,\r
-                                             "Delegate '" + Name + "' does not take '" + arg_count + "' arguments");\r
+                                             "Delegate '" + delegate_type.ToString ()\r
+                                             + "' does not take '" + arg_count + "' arguments");\r
                                return false;\r
                        }\r
 \r
-                       for (int i = arg_count; i > 0;) {\r
-                               i--;\r
-                               Expression conv;\r
-                               Argument a = (Argument) args [i];\r
-                               Expression a_expr = a.Expr;\r
-                               \r
-                               if (param_types [i] != a_expr.Type) {\r
-                                       \r
-                                       conv = Expression.ConvertImplicitStandard (ec, a_expr, param_types [i], loc);\r
-\r
-                                       if (conv == null) {\r
-                                               Report.Error (1594, loc,\r
-                                                             "Delegate '" + Name + "' has some invalid arguments.");\r
-\r
-                                               Report.Error (1503, loc,\r
-                                                      "Argument " + (i+1) +\r
-                                                      ": Cannot convert from '" +\r
-                                                      TypeManager.CSharpName (a_expr.Type)\r
-                                                      + "' to '" + TypeManager.CSharpName (param_types [i]) + "'");\r
-                                               return false;\r
-                                       }\r
-\r
-                                       if (a_expr != conv)\r
-                                               a.Expr = conv;\r
-                               }\r
+                       return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,\r
+                                                                delegate_type, loc);\r
+               }\r
+               \r
+               /// <summary>\r
+               ///  Verifies whether the delegate in question is compatible with this one in\r
+               ///  order to determine if instantiation from the same is possible.\r
+               /// </summary>\r
+               public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)\r
+               {\r
+                       Expression ml = Expression.MemberLookup (\r
+                               ec, delegate_type, "Invoke", loc);\r
+                       \r
+                       if (!(ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error : could not find Invoke method!");\r
+                               return false;\r
                        }\r
+                       \r
+                       MethodBase mb = ((MethodGroupExpr) ml).Methods [0];\r
+                       ParameterData pd = Invocation.GetParameterData (mb);\r
 \r
+                       Expression probe_ml = Expression.MemberLookup (\r
+                               ec, delegate_type, "Invoke", loc);\r
+                       \r
+                       if (!(probe_ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error : could not find Invoke method!");\r
+                               return false;\r
+                       }\r
+                       \r
+                       MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];\r
+                       ParameterData probe_pd = Invocation.GetParameterData (probe_mb);\r
+                       \r
+                       if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)\r
+                               return false;\r
+\r
+                       if (pd.Count != probe_pd.Count)\r
+                               return false;\r
+\r
+                       for (int i = pd.Count; i > 0; ) {\r
+                               i--;\r
+\r
+                               if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||\r
+                                   pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))\r
+                                       return false;\r
+                       }\r
+                       \r
                        return true;\r
                }\r
-               \r
-               public string FullDelegateDesc ()\r
+               \r
+               public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)\r
                {\r
-                       StringBuilder sb = new StringBuilder (TypeManager.CSharpName (System.Type.GetType (ReturnType)));\r
+                       StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));\r
                        \r
-                       sb.Append (" " + Name);\r
+                       sb.Append (" " + del_type.ToString ());\r
                        sb.Append (" (");\r
 \r
-                       int length = param_types.Length;\r
+                       int length = pd.Count;\r
                        \r
                        for (int i = length; i > 0; ) {\r
                                i--;\r
                                \r
-                               sb.Append (TypeManager.CSharpName (param_types [length - i - 1]));\r
+                               sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));\r
                                if (i != 0)\r
                                        sb.Append (", ");\r
                        }\r
@@ -254,17 +451,45 @@ namespace CIR {
                        \r
                }\r
                \r
+               // Hack around System.Reflection as found everywhere else\r
+               public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)\r
+               {\r
+                       ArrayList members = new ArrayList ();\r
+\r
+                       if ((mt & MemberTypes.Method) != 0) {\r
+                               if (ConstructorBuilder != null)\r
+                               if (filter (ConstructorBuilder, criteria))\r
+                                       members.Add (ConstructorBuilder);\r
+\r
+                               if (InvokeBuilder != null)\r
+                               if (filter (InvokeBuilder, criteria))\r
+                                       members.Add (InvokeBuilder);\r
+\r
+                               if (BeginInvokeBuilder != null)\r
+                               if (filter (BeginInvokeBuilder, criteria))\r
+                                       members.Add (BeginInvokeBuilder);\r
+\r
+                               if (EndInvokeBuilder != null)\r
+                               if (filter (EndInvokeBuilder, criteria))\r
+                                       members.Add (EndInvokeBuilder);\r
+                       }\r
+\r
+                       int count = members.Count;\r
+\r
+                       if (count > 0) {\r
+                               MemberInfo [] mi = new MemberInfo [count];\r
+                               members.CopyTo (mi, 0);\r
+                               return mi;\r
+                       }\r
+\r
+                       return null;\r
+               }\r
+               \r
                public void CloseDelegate ()\r
                {\r
                        TypeBuilder.CreateType ();\r
                }\r
                \r
-               public int ModFlags {\r
-                       get {\r
-                               return mod_flags;\r
-                       }\r
-               }\r
-\r
                public Expression InstanceExpression {\r
                        get {\r
                                return instance_expr;\r
@@ -282,6 +507,19 @@ namespace CIR {
                                delegate_method = value;\r
                        }\r
                }\r
+\r
+               public Type TargetReturnType {\r
+                       get {\r
+                               return ret_type;\r
+                       }\r
+               }\r
+\r
+               public Type [] ParameterTypes {\r
+                       get {\r
+                               return param_types;\r
+                       }\r
+               }\r
+               \r
        }\r
 \r
        public class NewDelegate : Expression {\r
@@ -292,71 +530,124 @@ namespace CIR {
                MethodBase delegate_method;\r
                Expression delegate_instance_expr;\r
 \r
-               Location Location;\r
-               \r
                public NewDelegate (Type type, ArrayList Arguments, Location loc)\r
                {\r
                        this.type = type;\r
                        this.Arguments = Arguments;\r
-                       this.Location  = loc; \r
+                       this.loc  = loc; \r
                }\r
 \r
                public override Expression DoResolve (EmitContext ec)\r
                {\r
-                       Delegate del = TypeManager.LookupDelegate (type);\r
-                       constructor_method = del.ConstructorBuilder;\r
-                       \r
                        if (Arguments == null) {\r
-                               Report.Error (-11, Location,\r
+                               Report.Error (-11, loc,\r
                                              "Delegate creation expression takes only one argument");\r
                                return null;\r
                        }\r
-                       \r
+\r
                        if (Arguments.Count != 1) {\r
-                               Report.Error (-11, Location,\r
+                               Report.Error (-11, loc,\r
                                              "Delegate creation expression takes only one argument");\r
                                return null;\r
                        }\r
-                       \r
+\r
+                       Expression ml = Expression.MemberLookup (\r
+                               ec, type, ".ctor", loc);\r
+\r
+                       if (!(ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error : Could not find delegate constructor!");\r
+                               return null;\r
+                       }\r
+\r
+                       constructor_method = ((MethodGroupExpr) ml).Methods [0];\r
                        Argument a = (Argument) Arguments [0];\r
                        \r
-                       if (!a.Resolve (ec))\r
+                       if (!a.ResolveMethodGroup (ec, Location))\r
                                return null;\r
                        \r
                        Expression e = a.Expr;\r
-                       \r
+\r
+                       Expression invoke_method = Expression.MemberLookup (\r
+                               ec, type, "Invoke", MemberTypes.Method,\r
+                               Expression.AllBindingFlags, loc);\r
+\r
+                       if (invoke_method == null) {\r
+                               Report.Error (-200, loc, "Internal error ! COuld not find Invoke method!");\r
+                               return null;\r
+                       }\r
+\r
                        if (e is MethodGroupExpr) {\r
                                MethodGroupExpr mg = (MethodGroupExpr) e;\r
-                               \r
-                               delegate_method  = del.VerifyMethod (mg.Methods [0], Location);\r
-                               \r
-                               if (delegate_method == null)\r
+\r
+                               foreach (MethodInfo mi in mg.Methods){\r
+                                       delegate_method  = Delegate.VerifyMethod (ec, type, mi, loc);\r
+\r
+                                       if (delegate_method != null)\r
+                                               break;\r
+                               }\r
+                                       \r
+                               if (delegate_method == null) {\r
+                                       string method_desc;\r
+                                       if (mg.Methods.Length > 1)\r
+                                               method_desc = mg.Methods [0].Name;\r
+                                       else\r
+                                               method_desc = Invocation.FullMethodDesc (mg.Methods [0]);\r
+\r
+                                       MethodBase dm = ((MethodGroupExpr) invoke_method).Methods [0];\r
+                                       ParameterData param = Invocation.GetParameterData (dm);\r
+                                       string delegate_desc = Delegate.FullDelegateDesc (type, dm, param);\r
+\r
+                                       Report.Error (123, loc, "Method '" + method_desc + "' does not " +\r
+                                                     "match delegate '" + delegate_desc + "'");\r
+\r
                                        return null;\r
-                               \r
+                               }\r
+                                               \r
                                if (mg.InstanceExpression != null)\r
                                        delegate_instance_expr = mg.InstanceExpression.Resolve (ec);\r
-                               else\r
-                                       delegate_instance_expr = null;\r
-                               \r
+                               else {\r
+                                       if (!ec.IsStatic)\r
+                                               delegate_instance_expr = ec.This;\r
+                                       else\r
+                                               delegate_instance_expr = null;\r
+                               }\r
+\r
                                if (delegate_instance_expr != null)\r
                                        if (delegate_instance_expr.Type.IsValueType)\r
                                                delegate_instance_expr = new BoxedCast (delegate_instance_expr);\r
                                \r
-                               \r
-                               del.InstanceExpression = delegate_instance_expr;\r
-                               del.TargetMethod = delegate_method;\r
-                               \r
                                eclass = ExprClass.Value;\r
                                return this;\r
-                       } else {\r
-                               Report.Error (-200, Location, "Cannot handle delegate instantiation from other delegates");\r
+                       }\r
+\r
+                       Type e_type = e.Type;\r
+\r
+                       if (!TypeManager.IsDelegateType (e_type)) {\r
+                               Report.Error (-12, loc, "Cannot create a delegate from something " +\r
+                                             "not a delegate or a method.");\r
+                               return null;\r
+                       }\r
+\r
+                       // This is what MS' compiler reports. We could always choose\r
+                       // to be more verbose and actually give delegate-level specifics\r
+                       \r
+                       if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {\r
+                               Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +\r
+                                             "to type '" + type + "'");\r
                                return null;\r
                        }\r
+                               \r
+                       delegate_instance_expr = e;\r
+                       delegate_method        = ((MethodGroupExpr) invoke_method).Methods [0];\r
+                       \r
+                       eclass = ExprClass.Value;\r
+                       return this;\r
                }\r
                \r
                public override void Emit (EmitContext ec)\r
                {\r
-                       if (delegate_instance_expr == null)\r
+                       if (delegate_instance_expr == null ||\r
+                           delegate_method.IsStatic)\r
                                ec.ig.Emit (OpCodes.Ldnull);\r
                        else\r
                                delegate_instance_expr.Emit (ec);\r
@@ -366,11 +657,10 @@ namespace CIR {
                }\r
        }\r
 \r
-       public class DelegateInvocation : Expression {\r
+       public class DelegateInvocation : ExpressionStatement {\r
 \r
                public Expression InstanceExpr;\r
                public ArrayList  Arguments;\r
-               public Location   Location;\r
 \r
                MethodBase method;\r
                \r
@@ -378,35 +668,33 @@ namespace CIR {
                {\r
                        this.InstanceExpr = instance_expr;\r
                        this.Arguments = args;\r
-                       this.Location = loc;\r
+                       this.loc = loc;\r
                }\r
 \r
                public override Expression DoResolve (EmitContext ec)\r
                {\r
-                       Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
-\r
-                       if (del == null)\r
-                               return null;\r
-\r
-                       if (del.TargetMethod == null)\r
+                       Type del_type = InstanceExpr.Type;\r
+                       if (del_type == null)\r
                                return null;\r
                        \r
                        if (Arguments != null){\r
-                               for (int i = Arguments.Count; i > 0;){\r
-                                       --i;\r
-                                       Argument a = (Argument) Arguments [i];\r
-                                       \r
-                                       if (!a.Resolve (ec))\r
+                               foreach (Argument a in Arguments){\r
+                                       if (!a.Resolve (ec, loc))\r
                                                return null;\r
                                }\r
                        }\r
                        \r
-                       if (!del.VerifyApplicability (ec, Arguments, Location))\r
+                       if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))\r
                                return null;\r
+\r
+                       Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", loc);\r
+                       if (!(ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error : could not find Invoke method!");\r
+                               return null;\r
+                       }\r
                        \r
-                       method = del.InvokeBuilder;\r
+                       method = ((MethodGroupExpr) ml).Methods [0];\r
                        type = ((MethodInfo) method).ReturnType;\r
-                       \r
                        eclass = ExprClass.Value;\r
                        \r
                        return this;\r
@@ -415,7 +703,24 @@ namespace CIR {
                public override void Emit (EmitContext ec)\r
                {\r
                        Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\r
-                       Invocation.EmitCall (ec, del.TargetMethod.IsStatic, InstanceExpr, method, Arguments);\r
+\r
+                       //\r
+                       // Invocation on delegates call the virtual Invoke member\r
+                       // so we are always `instance' calls\r
+                       //\r
+                       Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);\r
+               }\r
+\r
+               public override void EmitStatement (EmitContext ec)\r
+               {\r
+                       Emit (ec);\r
+                       // \r
+                       // Pop the return value if there is one\r
+                       //\r
+                       if (method is MethodInfo){\r
+                               if (((MethodInfo) method).ReturnType != TypeManager.void_type)\r
+                                       ec.ig.Emit (OpCodes.Pop);\r
+                       }\r
                }\r
 \r
        }\r