2002-11-14 Martin Baulig <martin@ximian.com>
[mono.git] / mcs / mcs / delegate.cs
index ee920ca6aa7fb4602be79a453f8b5cd16cd65174..e78c6e1dbfdb9a4083874c889ae4c35083d00b7b 100644 (file)
@@ -13,63 +13,760 @@ using System;
 using System.Collections;\r
 using System.Reflection;\r
 using System.Reflection.Emit;\r
+using System.Text;\r
 \r
-namespace CIR {\r
-       \r
-       public class Delegate : DeclSpace {\r
+namespace Mono.CSharp {\r
 \r
-               public string name;\r
-               public string type;\r
-               public int    mod_flags;\r
-               public Parameters Parameters;\r
-               public Attributes OptAttributes;\r
-               public TypeBuilder DelegateBuilder;\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
 \r
+               public ConstructorBuilder ConstructorBuilder;\r
+               public MethodBuilder      InvokeBuilder;\r
+               public MethodBuilder      BeginInvokeBuilder;\r
+               public MethodBuilder      EndInvokeBuilder;\r
+               \r
+               Type [] param_types;\r
+               Type ret_type;\r
+               \r
+               Expression instance_expr;\r
+               MethodBase delegate_method;\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 (string type, int mod_flags, string name, Parameters param_list,\r
-                                Attributes attrs) : base (name)\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.name       = name;\r
-                       this.type       = type;\r
-                       this.mod_flags  = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);\r
+                       this.ReturnType = type;\r
+                       ModFlags        = Modifiers.Check (AllowedModifiers, mod_flags,\r
+                                                          IsTopLevel ? Modifiers.INTERNAL :\r
+                                                          Modifiers.PRIVATE, l);\r
                        Parameters      = param_list;\r
                        OptAttributes   = attrs;\r
                }\r
 \r
-               public void Define (TypeContainer parent)\r
+               public override TypeBuilder DefineType ()\r
+               {\r
+                       TypeAttributes attr;\r
+\r
+                       if (TypeBuilder != null)\r
+                               return TypeBuilder;\r
+                       \r
+                       if (IsTopLevel) {\r
+                               ModuleBuilder builder = CodeGen.ModuleBuilder;\r
+                               attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;\r
+\r
+                               TypeBuilder = builder.DefineType (\r
+                                       Name, attr, TypeManager.multicast_delegate_type);\r
+                       } else {\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
+                       TypeManager.AddDelegateType (Name, TypeBuilder, this);\r
+\r
+                       return TypeBuilder;\r
+               }\r
+\r
+               public override bool DefineMembers (TypeContainer container)\r
+               {\r
+                       return true;\r
+               }\r
+\r
+               public override bool Define (TypeContainer container)\r
+               {\r
+                       MethodAttributes mattr;\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
+                       mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |\r
+                               MethodAttributes.HideBySig | MethodAttributes.Public;\r
+\r
+                       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
+                       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
+                       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
+\r
+                       InvokeBuilder = TypeBuilder.DefineMethod ("Invoke", \r
+                                                                 mattr,                     \r
+                                                                 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
+                       param_types.CopyTo (async_param_types, 0);\r
+\r
+                       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 |\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
+                       end_param_types [0] = TypeManager.iasyncresult_type;\r
+                       \r
+                       EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",\r
+                                                                    mattr,\r
+                                                                    cc,\r
+                                                                    ret_type,\r
+                                                                    end_param_types);\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
+               /// <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
-                       TypeAttributes attr = Modifiers.TypeAttr (ModFlags, parent);\r
+                       ParameterData pd = Invocation.GetParameterData (mb);\r
 \r
-                       Type t = parent.LookupType (type, false);\r
-                       Type [] param_types = Parameters.GetParameterInfo (parent);\r
-                       Type base_type = System.Type.GetType ("System.MulticastDelegate");\r
+                       int pd_count = pd.Count;\r
 \r
-                       DelegateBuilder = parent.TypeBuilder.DefineNestedType (name, attr, base_type);\r
+                       Expression ml = Expression.MemberLookup (\r
+                               ec, delegate_type, "Invoke", loc);\r
 \r
-                       // FIXME : Need to figure out how to proceed from here. \r
+                       if (!(ml is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");\r
+                               return null;\r
+                       }\r
+\r
+                       MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];\r
+\r
+                       ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);\r
 \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
+                                   invoke_pd.ParameterModifier (i) == pd.ParameterModifier (i))\r
+                                       continue;\r
+                               else\r
+                                       return null;\r
+                       }\r
+\r
+                       if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)\r
+                               return mb;\r
+                       else\r
+                               return null;\r
+               }\r
+\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
+                       if (args == null)\r
+                               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!" + delegate_type);\r
+                               return false;\r
+                       }\r
+                       \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_count == 0) ||\r
+                               (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 '" + delegate_type.ToString ()\r
+                                             + "' does not take '" + arg_count + "' arguments");\r
+                               return false;\r
+                       }\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 static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)\r
+               {\r
+                       StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));\r
+                       \r
+                       sb.Append (" " + del_type.ToString ());\r
+                       sb.Append (" (");\r
+\r
+                       int length = pd.Count;\r
+                       \r
+                       for (int i = length; i > 0; ) {\r
+                               i--;\r
+\r
+                               sb.Append (pd.ParameterDesc (length - i - 1));\r
+                               if (i != 0)\r
+                                       sb.Append (", ");\r
+                       }\r
+                       \r
+                       sb.Append (")");\r
+                       return sb.ToString ();\r
+                       \r
+               }\r
                \r
-               public string Type {\r
+               // Hack around System.Reflection as found everywhere else\r
+               public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,\r
+                                                       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
+                       return new MemberList (members);\r
+               }\r
+\r
+               public override MemberCache MemberCache {\r
                        get {\r
-                               return type;\r
+                               return null;\r
                        }\r
                }\r
 \r
-               public int ModFlags {\r
+               public Expression InstanceExpression {\r
                        get {\r
-                               return mod_flags;\r
+                               return instance_expr;\r
+                       }\r
+                       set {\r
+                               instance_expr = value;\r
+                       }\r
+               }\r
+\r
+               public MethodBase TargetMethod {\r
+                       get {\r
+                               return delegate_method;\r
+                       }\r
+                       set {\r
+                               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
+\r
+               public ArrayList Arguments;\r
+\r
+               MethodBase constructor_method;\r
+               MethodBase delegate_method;\r
+               Expression delegate_instance_expr;\r
+\r
+               public NewDelegate (Type type, ArrayList Arguments, Location loc)\r
+               {\r
+                       this.type = type;\r
+                       this.Arguments = Arguments;\r
+                       this.loc  = loc; \r
+               }\r
+\r
+               public override Expression DoResolve (EmitContext ec)\r
+               {\r
+                       if (Arguments == null) {\r
+                               Report.Error (-11, loc,\r
+                                             "Delegate creation expression takes only one argument");\r
+                               return null;\r
+                       }\r
+\r
+                       if (Arguments.Count != 1) {\r
+                               Report.Error (-11, loc,\r
+                                             "Delegate creation expression takes only one argument");\r
+                               return null;\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.ResolveMethodGroup (ec, Location))\r
+                               return null;\r
+                       \r
+                       Expression e = a.Expr;\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
+                               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
+                               // Check safe/unsafe of the delegate\r
+                               //\r
+                               if (!ec.InUnsafe){\r
+                                       ParameterData param = Invocation.GetParameterData (delegate_method);\r
+                                       int count = param.Count;\r
+                                       \r
+                                       for (int i = 0; i < count; i++){\r
+                                               if (param.ParameterType (i).IsPointer){\r
+                                                       Expression.UnsafeError (loc);\r
+                                                       return null;\r
+                                               }\r
+                                       }\r
+                               }\r
+                                               \r
+                               if (mg.InstanceExpression != null)\r
+                                       delegate_instance_expr = mg.InstanceExpression.Resolve (ec);\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
+                               eclass = ExprClass.Value;\r
+                               return this;\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
+                           delegate_method.IsStatic)\r
+                               ec.ig.Emit (OpCodes.Ldnull);\r
+                       else\r
+                               delegate_instance_expr.Emit (ec);\r
+                       \r
+                       if (delegate_method.IsVirtual) {\r
+                               ec.ig.Emit (OpCodes.Dup);\r
+                               ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);\r
+                       } else\r
+                               ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);\r
+                       ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);\r
+               }\r
+       }\r
+\r
+       public class DelegateInvocation : ExpressionStatement {\r
+\r
+               public Expression InstanceExpr;\r
+               public ArrayList  Arguments;\r
+\r
+               MethodBase method;\r
+               \r
+               public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)\r
+               {\r
+                       this.InstanceExpr = instance_expr;\r
+                       this.Arguments = args;\r
+                       this.loc = loc;\r
+               }\r
+\r
+               public override Expression DoResolve (EmitContext ec)\r
+               {\r
+                       if (InstanceExpr is EventExpr) {\r
+                               \r
+                               EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;\r
+                               \r
+                               Expression ml = MemberLookup (\r
+                                       ec, ec.ContainerType, ei.Name,\r
+                                       MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);\r
+\r
+                               if (ml == null) {\r
+                                       //\r
+                                       // If this is the case, then the Event does not belong \r
+                                       // to this Type and so, according to the spec\r
+                                       // cannot be accessed directly\r
+                                       //\r
+                                       // Note that target will not appear as an EventExpr\r
+                                       // in the case it is being referenced within the same type container;\r
+                                       // it will appear as a FieldExpr in that case.\r
+                                       //\r
+                                       \r
+                                       Assign.error70 (ei, loc);\r
+                                       return null;\r
+                               }\r
+                       }\r
+                       \r
+                       \r
+                       Type del_type = InstanceExpr.Type;\r
+                       if (del_type == null)\r
+                               return null;\r
+                       \r
+                       if (Arguments != null){\r
+                               foreach (Argument a in Arguments){\r
+                                       if (!a.Resolve (ec, loc))\r
+                                               return null;\r
+                               }\r
+                       }\r
+                       \r
+                       if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))\r
+                               return null;\r
+\r
+                       Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);\r
+                       if (!(lookup is MethodGroupExpr)) {\r
+                               Report.Error (-100, loc, "Internal error: could not find Invoke method!");\r
+                               return null;\r
+                       }\r
+                       \r
+                       method = ((MethodGroupExpr) lookup).Methods [0];\r
+                       type = ((MethodInfo) method).ReturnType;\r
+                       eclass = ExprClass.Value;\r
+                       \r
+                       return this;\r
+               }\r
+\r
+               public override void Emit (EmitContext ec)\r
+               {\r
+                       Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);\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
-       \r
 }\r