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 (ec, delegate_type, "Invoke", false, loc);
\r
252 if (!(ml is MethodGroupExpr)) {
\r
253 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
257 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
259 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
261 bool mismatch = false;
\r
262 for (int i = pd.Count; i > 0; ) {
\r
265 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
275 123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
276 "' does not match delegate '" +
\r
277 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
281 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
287 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
288 "' does not match delegate '" +
\r
289 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
297 // Verifies whether the invocation arguments are compatible with the
\r
298 // delegate's target method
\r
300 public static bool VerifyApplicability (EmitContext ec, Type delegate_type, ArrayList args,
\r
308 arg_count = args.Count;
\r
310 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
312 if (!(ml is MethodGroupExpr)) {
\r
313 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
317 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
319 ParameterData pd = Invocation.GetParameterData (mb);
\r
321 if (pd.Count != arg_count) {
\r
322 Report.Error (1593, loc,
\r
323 "Delegate '" + delegate_type.ToString ()
\r
324 + "' does not take '" + arg_count + "' arguments");
\r
328 for (int i = arg_count; i > 0;) {
\r
331 Argument a = (Argument) args [i];
\r
332 Expression a_expr = a.Expr;
\r
334 if (pd.ParameterType (i) != a_expr.Type) {
\r
336 conv = Expression.ConvertImplicitStandard (ec, a_expr, pd.ParameterType (i), loc);
\r
338 if (conv == null) {
\r
339 Report.Error (1594, loc,
\r
340 "Delegate '" + delegate_type.ToString () +
\r
341 "' has some invalid arguments.");
\r
343 Report.Error (1503, loc,
\r
344 "Argument " + (i+1) +
\r
345 ": Cannot convert from '" +
\r
346 TypeManager.CSharpName (a_expr.Type)
\r
347 + "' to '" + TypeManager.CSharpName (pd.ParameterType (i)) + "'");
\r
351 if (a_expr != conv)
\r
360 /// Verifies whether the delegate in question is compatible with this one in
\r
361 /// order to determine if instantiation from the same is possible.
\r
363 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
365 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
367 if (!(ml is MethodGroupExpr)) {
\r
368 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
372 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
373 ParameterData pd = Invocation.GetParameterData (mb);
\r
375 Expression probe_ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
377 if (!(probe_ml is MethodGroupExpr)) {
\r
378 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
382 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
383 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
385 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
388 if (pd.Count != probe_pd.Count)
\r
391 for (int i = pd.Count; i > 0; ) {
\r
394 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
395 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
402 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
404 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
406 sb.Append (" " + del_type.ToString ());
\r
409 int length = pd.Count;
\r
411 for (int i = length; i > 0; ) {
\r
414 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
420 return sb.ToString ();
\r
424 // Hack around System.Reflection as found everywhere else
\r
425 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
427 ArrayList members = new ArrayList ();
\r
429 if ((mt & MemberTypes.Method) != 0) {
\r
430 if (filter (ConstructorBuilder, criteria))
\r
431 members.Add (ConstructorBuilder);
\r
433 if (filter (InvokeBuilder, criteria))
\r
434 members.Add (InvokeBuilder);
\r
436 if (filter (BeginInvokeBuilder, criteria))
\r
437 members.Add (BeginInvokeBuilder);
\r
439 if (filter (EndInvokeBuilder, criteria))
\r
440 members.Add (EndInvokeBuilder);
\r
443 int count = members.Count;
\r
446 MemberInfo [] mi = new MemberInfo [count];
\r
447 members.CopyTo (mi, 0);
\r
454 public void CloseDelegate ()
\r
456 TypeBuilder.CreateType ();
\r
459 public Expression InstanceExpression {
\r
461 return instance_expr;
\r
464 instance_expr = value;
\r
468 public MethodBase TargetMethod {
\r
470 return delegate_method;
\r
473 delegate_method = value;
\r
477 public Type TargetReturnType {
\r
483 public Type [] ParameterTypes {
\r
485 return param_types;
\r
491 public class NewDelegate : Expression {
\r
493 public ArrayList Arguments;
\r
495 MethodBase constructor_method;
\r
496 MethodBase delegate_method;
\r
497 Expression delegate_instance_expr;
\r
501 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
504 this.Arguments = Arguments;
\r
505 this.Location = loc;
\r
508 public override Expression DoResolve (EmitContext ec)
\r
510 if (Arguments == null) {
\r
511 Report.Error (-11, Location,
\r
512 "Delegate creation expression takes only one argument");
\r
516 if (Arguments.Count != 1) {
\r
517 Report.Error (-11, Location,
\r
518 "Delegate creation expression takes only one argument");
\r
522 Expression ml = Expression.MemberLookup (ec, type, ".ctor", false, Location);
\r
524 if (!(ml is MethodGroupExpr)) {
\r
525 Report.Error (-100, Location, "Internal error : Could not find delegate constructor!");
\r
529 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
531 Argument a = (Argument) Arguments [0];
\r
533 if (!a.Resolve (ec, Location))
\r
536 Expression e = a.Expr;
\r
538 if (e is MethodGroupExpr) {
\r
539 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
541 if (mg.Methods.Length > 1) {
\r
542 Report.Error (-14, Location, "Ambiguous method reference in delegate creation");
\r
546 delegate_method = Delegate.VerifyMethod (ec, type, mg.Methods [0], Location);
\r
548 if (delegate_method == null)
\r
551 if (mg.InstanceExpression != null)
\r
552 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
555 delegate_instance_expr = ec.This;
\r
557 delegate_instance_expr = null;
\r
560 if (delegate_instance_expr != null)
\r
561 if (delegate_instance_expr.Type.IsValueType)
\r
562 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
564 eclass = ExprClass.Value;
\r
568 Type e_type = e.Type;
\r
570 if (!TypeManager.IsDelegateType (e_type)) {
\r
571 Report.Error (-12, Location, "Cannot create a delegate from something " +
\r
572 "not a delegate or a method.");
\r
576 // This is what MS' compiler reports. We could always choose
\r
577 // to be more verbose and actually give delegate-level specifics
\r
579 if (!Delegate.VerifyDelegate (ec, type, e_type, Location)) {
\r
580 Report.Error (29, Location, "Cannot implicitly convert type '" + e_type + "' " +
\r
581 "to type '" + type + "'");
\r
585 Expression invoke_method = Expression.MemberLookup (ec, e_type, "Invoke", false,
\r
586 MemberTypes.Method,
\r
587 Expression.AllBindingFlags,
\r
590 if (invoke_method == null) {
\r
591 Report.Error (-200, Location, "Internal error ! COuld not find Invoke method!");
\r
595 delegate_instance_expr = e;
\r
596 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
598 eclass = ExprClass.Value;
\r
602 public override void Emit (EmitContext ec)
\r
604 if (delegate_instance_expr == null)
\r
605 ec.ig.Emit (OpCodes.Ldnull);
\r
607 delegate_instance_expr.Emit (ec);
\r
609 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
610 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
614 public class DelegateInvocation : ExpressionStatement {
\r
616 public Expression InstanceExpr;
\r
617 public ArrayList Arguments;
\r
618 public Location Location;
\r
622 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
624 this.InstanceExpr = instance_expr;
\r
625 this.Arguments = args;
\r
626 this.Location = loc;
\r
629 public override Expression DoResolve (EmitContext ec)
\r
631 Type del_type = InstanceExpr.Type;
\r
633 if (del_type == null)
\r
636 if (Arguments != null){
\r
637 for (int i = Arguments.Count; i > 0;){
\r
639 Argument a = (Argument) Arguments [i];
\r
641 if (!a.Resolve (ec, Location))
\r
646 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, Location))
\r
649 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", false, Location);
\r
651 if (!(ml is MethodGroupExpr)) {
\r
652 Report.Error (-100, Location, "Internal error : could not find Invoke method!");
\r
656 method = ((MethodGroupExpr) ml).Methods [0];
\r
658 type = ((MethodInfo) method).ReturnType;
\r
660 eclass = ExprClass.Value;
\r
665 public override void Emit (EmitContext ec)
\r
667 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
670 // Invocation on delegates call the virtual Invoke member
\r
671 // so we are always `instance' calls
\r
673 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments);
\r
676 public override void EmitStatement (EmitContext ec)
\r
680 // Pop the return value if there is one
\r
682 if (method is MethodInfo){
\r
683 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
684 ec.ig.Emit (OpCodes.Pop);
\r