2 // delegate.cs: Delegate Handler
\r
4 // Author: Ravi Pratap (ravi@ximian.com)
\r
6 // Licensed under the terms of the GNU GPL
\r
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
\r
13 using System.Collections;
\r
14 using System.Reflection;
\r
15 using System.Reflection.Emit;
\r
18 namespace Mono.CSharp {
\r
23 public class Delegate : MemberCore {
\r
24 public readonly string ReturnType;
\r
25 public Parameters Parameters;
\r
26 public Attributes OptAttributes;
\r
27 public TypeBuilder TypeBuilder;
\r
29 public ConstructorBuilder ConstructorBuilder;
\r
30 public MethodBuilder InvokeBuilder;
\r
31 public MethodBuilder BeginInvokeBuilder;
\r
32 public MethodBuilder EndInvokeBuilder;
\r
34 Type [] param_types;
\r
37 Expression instance_expr;
\r
38 MethodBase delegate_method;
\r
40 const int AllowedModifiers =
\r
43 Modifiers.PROTECTED |
\r
44 Modifiers.INTERNAL |
\r
47 public Delegate (string type, int mod_flags, string name, Parameters param_list,
\r
48 Attributes attrs, Location l)
\r
51 this.ReturnType = type;
\r
52 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);
\r
53 Parameters = param_list;
\r
54 OptAttributes = attrs;
\r
57 public void DefineDelegate (object parent_builder)
\r
59 TypeAttributes attr;
\r
60 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
\r
62 if (parent_builder is ModuleBuilder) {
\r
63 ModuleBuilder builder = (ModuleBuilder) parent_builder;
\r
64 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
\r
66 TypeBuilder = builder.DefineType (
\r
67 name, attr, TypeManager.multicast_delegate_type);
\r
69 // FIXME: We could just use TypeBuilder here.
\r
70 TypeBuilder builder = (System.Reflection.Emit.TypeBuilder) parent_builder;
\r
71 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
\r
72 TypeAttributes.Sealed;
\r
74 TypeBuilder = builder.DefineNestedType (
\r
75 name, attr, TypeManager.multicast_delegate_type);
\r
78 RootContext.TypeManager.AddDelegateType (Name, TypeBuilder, this);
\r
81 public override bool Define (TypeContainer parent)
\r
83 MethodAttributes mattr;
\r
86 // FIXME: POSSIBLY make this static, as it is always constant
\r
88 Type [] const_arg_types = new Type [2];
\r
89 const_arg_types [0] = TypeManager.object_type;
\r
90 const_arg_types [1] = TypeManager.intptr_type;
\r
92 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
\r
93 MethodAttributes.HideBySig | MethodAttributes.Public;
\r
95 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
\r
96 CallingConventions.Standard,
\r
99 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
\r
100 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
\r
102 // HACK because System.Reflection.Emit is lame
\r
105 // FIXME: POSSIBLY make these static, as they are always the same
\r
106 Parameter [] fixed_pars = new Parameter [2];
\r
107 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
108 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
109 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
\r
111 TypeManager.RegisterMethod (
\r
112 ConstructorBuilder,
\r
113 new InternalParameters (const_arg_types, const_parameters),
\r
117 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
119 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
124 param_types = Parameters.GetParameterInfo (parent);
\r
125 if (param_types == null)
\r
128 // Check accessibility
\r
129 foreach (Type partype in param_types)
\r
130 if (!TypeContainer.AsAccessible (partype, ModFlags))
\r
133 ret_type = RootContext.LookupType (parent, ReturnType, false, Location);
\r
134 if (ret_type == null)
\r
137 if (!TypeContainer.AsAccessible (ret_type, ModFlags))
\r
141 // We don't have to check any others because they are all
\r
142 // guaranteed to be accessible - they are standard types.
\r
145 CallingConventions cc = Parameters.GetCallingConvention ();
\r
147 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
149 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
155 for (i = 0 ; i < param_types.Length; i++) {
\r
156 Parameter p = Parameters.FixedParameters [i];
\r
157 string name = p.Name;
\r
158 ParameterBuilder pb = InvokeBuilder.DefineParameter (i+1, p.Attributes, name);
\r
161 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
163 TypeManager.RegisterMethod (InvokeBuilder,
\r
164 new InternalParameters (parent, Parameters),
\r
170 int params_num = param_types.Length;
\r
171 Type [] async_param_types = new Type [params_num + 2];
\r
173 param_types.CopyTo (async_param_types, 0);
\r
175 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
176 async_param_types [params_num + 1] = TypeManager.object_type;
\r
178 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |
\r
179 MethodAttributes.NewSlot;
\r
181 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
184 TypeManager.iasyncresult_type,
\r
185 async_param_types);
\r
187 for (i = 0 ; i < param_types.Length; i++) {
\r
188 Parameter p = Parameters.FixedParameters [i];
\r
189 string name = p.Name;
\r
190 BeginInvokeBuilder.DefineParameter (i + 1, p.Attributes, name);
\r
193 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
194 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
196 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
198 Parameter [] async_params = new Parameter [params_num + 2];
\r
199 if (params_num > 0)
\r
200 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
202 async_params [params_num] = new Parameter ("System.AsyncCallback", "callback",
\r
203 Parameter.Modifier.NONE, null);
\r
204 async_params [params_num + 1] = new Parameter ("System.IAsyncResult", "object",
\r
205 Parameter.Modifier.NONE, null);
\r
207 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
208 new InternalParameters (
\r
210 new Parameters (async_params, null, Location)),
\r
211 async_param_types);
\r
216 Type [] end_param_types = new Type [1];
\r
217 end_param_types [0] = TypeManager.iasyncresult_type;
\r
219 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
224 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
226 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
228 Parameter [] end_params = new Parameter [1];
\r
229 end_params [0] = new Parameter ("System.IAsyncResult", "result",
\r
230 Parameter.Modifier.NONE, null);
\r
232 TypeManager.RegisterMethod (EndInvokeBuilder,
\r
233 new InternalParameters (
\r
235 new Parameters (end_params, null, Location)),
\r
242 /// Verifies whether the method in question is compatible with the delegate
\r
243 /// Returns the method itself if okay and null if not.
\r
245 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
\r
248 ParameterData pd = Invocation.GetParameterData (mb);
\r
250 Expression ml = Expression.MemberLookup (
\r
251 ec, delegate_type, "Invoke", loc);
\r
253 if (!(ml is MethodGroupExpr)) {
\r
254 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
258 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
260 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
262 bool mismatch = false;
\r
263 for (int i = pd.Count; i > 0; ) {
\r
266 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
276 123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
277 "' does not match delegate '" +
\r
278 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
282 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
288 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
289 "' does not match delegate '" +
\r
290 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
298 // Verifies whether the invocation arguments are compatible with the
\r
299 // delegate's target method
\r
301 public static bool VerifyApplicability (EmitContext ec, Type delegate_type, ArrayList args,
\r
309 arg_count = args.Count;
\r
311 Expression ml = Expression.MemberLookup (
\r
312 ec, delegate_type, "Invoke", loc);
\r
314 if (!(ml is MethodGroupExpr)) {
\r
315 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
319 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
321 ParameterData pd = Invocation.GetParameterData (mb);
\r
323 if (pd.Count != arg_count) {
\r
324 Report.Error (1593, loc,
\r
325 "Delegate '" + delegate_type.ToString ()
\r
326 + "' does not take '" + arg_count + "' arguments");
\r
330 for (int i = arg_count; i > 0;) {
\r
333 Argument a = (Argument) args [i];
\r
334 Expression a_expr = a.Expr;
\r
336 if (pd.ParameterType (i) != a_expr.Type) {
\r
338 conv = Expression.ConvertImplicitStandard (ec, a_expr, pd.ParameterType (i), loc);
\r
340 if (conv == null) {
\r
341 Report.Error (1594, loc,
\r
342 "Delegate '" + delegate_type.ToString () +
\r
343 "' has some invalid arguments.");
\r
345 Report.Error (1503, loc,
\r
346 "Argument " + (i+1) +
\r
347 ": Cannot convert from '" +
\r
348 TypeManager.CSharpName (a_expr.Type)
\r
349 + "' to '" + TypeManager.CSharpName (pd.ParameterType (i)) + "'");
\r
353 if (a_expr != conv)
\r
362 /// Verifies whether the delegate in question is compatible with this one in
\r
363 /// order to determine if instantiation from the same is possible.
\r
365 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
367 Expression ml = Expression.MemberLookup (
\r
368 ec, delegate_type, "Invoke", loc);
\r
370 if (!(ml is MethodGroupExpr)) {
\r
371 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
375 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
376 ParameterData pd = Invocation.GetParameterData (mb);
\r
378 Expression probe_ml = Expression.MemberLookup (
\r
379 ec, delegate_type, "Invoke", loc);
\r
381 if (!(probe_ml is MethodGroupExpr)) {
\r
382 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
386 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
387 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
389 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
392 if (pd.Count != probe_pd.Count)
\r
395 for (int i = pd.Count; i > 0; ) {
\r
398 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
399 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
406 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
408 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
410 sb.Append (" " + del_type.ToString ());
\r
413 int length = pd.Count;
\r
415 for (int i = length; i > 0; ) {
\r
418 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
424 return sb.ToString ();
\r
428 // Hack around System.Reflection as found everywhere else
\r
429 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
431 ArrayList members = new ArrayList ();
\r
433 if ((mt & MemberTypes.Method) != 0) {
\r
434 if (filter (ConstructorBuilder, criteria))
\r
435 members.Add (ConstructorBuilder);
\r
437 if (filter (InvokeBuilder, criteria))
\r
438 members.Add (InvokeBuilder);
\r
440 if (filter (BeginInvokeBuilder, criteria))
\r
441 members.Add (BeginInvokeBuilder);
\r
443 if (filter (EndInvokeBuilder, criteria))
\r
444 members.Add (EndInvokeBuilder);
\r
447 int count = members.Count;
\r
450 MemberInfo [] mi = new MemberInfo [count];
\r
451 members.CopyTo (mi, 0);
\r
458 public void CloseDelegate ()
\r
460 TypeBuilder.CreateType ();
\r
463 public Expression InstanceExpression {
\r
465 return instance_expr;
\r
468 instance_expr = value;
\r
472 public MethodBase TargetMethod {
\r
474 return delegate_method;
\r
477 delegate_method = value;
\r
481 public Type TargetReturnType {
\r
487 public Type [] ParameterTypes {
\r
489 return param_types;
\r
495 public class NewDelegate : Expression {
\r
497 public ArrayList Arguments;
\r
499 MethodBase constructor_method;
\r
500 MethodBase delegate_method;
\r
501 Expression delegate_instance_expr;
\r
505 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
508 this.Arguments = Arguments;
\r
509 this.Location = loc;
\r
512 public override Expression DoResolve (EmitContext ec)
\r
514 if (Arguments == null) {
\r
515 Report.Error (-11, Location,
\r
516 "Delegate creation expression takes only one argument");
\r
520 if (Arguments.Count != 1) {
\r
521 Report.Error (-11, Location,
\r
522 "Delegate creation expression takes only one argument");
\r
526 Expression ml = Expression.MemberLookup (
\r
527 ec, type, ".ctor", Location);
\r
529 if (!(ml is MethodGroupExpr)) {
\r
530 Report.Error (-100, Location, "Internal error : Could not find delegate constructor!");
\r
534 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
536 Argument a = (Argument) Arguments [0];
\r
538 if (!a.Resolve (ec, Location))
\r
541 Expression e = a.Expr;
\r
543 if (e is MethodGroupExpr) {
\r
544 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
546 if (mg.Methods.Length > 1) {
\r
547 Report.Error (-14, Location, "Ambiguous method reference in delegate creation");
\r
551 delegate_method = Delegate.VerifyMethod (ec, type, mg.Methods [0], Location);
\r
553 if (delegate_method == null)
\r
556 if (mg.InstanceExpression != null)
\r
557 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
560 delegate_instance_expr = ec.This;
\r
562 delegate_instance_expr = null;
\r
565 if (delegate_instance_expr != null)
\r
566 if (delegate_instance_expr.Type.IsValueType)
\r
567 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
569 eclass = ExprClass.Value;
\r
573 Type e_type = e.Type;
\r
575 if (!TypeManager.IsDelegateType (e_type)) {
\r
576 Report.Error (-12, Location, "Cannot create a delegate from something " +
\r
577 "not a delegate or a method.");
\r
581 // This is what MS' compiler reports. We could always choose
\r
582 // to be more verbose and actually give delegate-level specifics
\r
584 if (!Delegate.VerifyDelegate (ec, type, e_type, Location)) {
\r
585 Report.Error (29, Location, "Cannot implicitly convert type '" + e_type + "' " +
\r
586 "to type '" + type + "'");
\r
590 Expression invoke_method = Expression.MemberLookup (
\r
591 ec, e_type, "Invoke", MemberTypes.Method,
\r
592 Expression.AllBindingFlags, Location);
\r
594 if (invoke_method == null) {
\r
595 Report.Error (-200, Location, "Internal error ! COuld not find Invoke method!");
\r
599 delegate_instance_expr = e;
\r
600 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
602 eclass = ExprClass.Value;
\r
606 public override void Emit (EmitContext ec)
\r
608 if (delegate_instance_expr == null)
\r
609 ec.ig.Emit (OpCodes.Ldnull);
\r
611 delegate_instance_expr.Emit (ec);
\r
613 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
614 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
618 public class DelegateInvocation : ExpressionStatement {
\r
620 public Expression InstanceExpr;
\r
621 public ArrayList Arguments;
\r
622 public Location Location;
\r
626 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
628 this.InstanceExpr = instance_expr;
\r
629 this.Arguments = args;
\r
630 this.Location = loc;
\r
633 public override Expression DoResolve (EmitContext ec)
\r
635 Type del_type = InstanceExpr.Type;
\r
637 if (del_type == null)
\r
640 if (Arguments != null){
\r
641 for (int i = Arguments.Count; i > 0;){
\r
643 Argument a = (Argument) Arguments [i];
\r
645 if (!a.Resolve (ec, Location))
\r
650 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, Location))
\r
653 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", Location);
\r
655 if (!(ml is MethodGroupExpr)) {
\r
656 Report.Error (-100, Location, "Internal error : could not find Invoke method!");
\r
660 method = ((MethodGroupExpr) ml).Methods [0];
\r
662 type = ((MethodInfo) method).ReturnType;
\r
664 eclass = ExprClass.Value;
\r
669 public override void Emit (EmitContext ec)
\r
671 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
674 // Invocation on delegates call the virtual Invoke member
\r
675 // so we are always `instance' calls
\r
677 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments);
\r
680 public override void EmitStatement (EmitContext ec)
\r
684 // Pop the return value if there is one
\r
686 if (method is MethodInfo){
\r
687 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
688 ec.ig.Emit (OpCodes.Pop);
\r