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
48 public Delegate (string type, int mod_flags, string name, Parameters param_list,
\r
49 Attributes attrs, Location l)
\r
52 this.ReturnType = type;
\r
53 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC, l);
\r
54 Parameters = param_list;
\r
55 OptAttributes = attrs;
\r
58 public void DefineDelegate (object parent_builder)
\r
60 TypeAttributes attr;
\r
62 if (TypeBuilder != null)
\r
65 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
\r
67 if (parent_builder is ModuleBuilder) {
\r
68 ModuleBuilder builder = (ModuleBuilder) parent_builder;
\r
69 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
\r
71 TypeBuilder = builder.DefineType (
\r
72 name, attr, TypeManager.multicast_delegate_type);
\r
74 // FIXME: We could just use TypeBuilder here.
\r
75 TypeBuilder builder = (System.Reflection.Emit.TypeBuilder) parent_builder;
\r
76 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
\r
77 TypeAttributes.Sealed;
\r
79 TypeBuilder = builder.DefineNestedType (
\r
80 name, attr, TypeManager.multicast_delegate_type);
\r
83 TypeManager.AddDelegateType (Name, TypeBuilder, this);
\r
86 public override bool Define (TypeContainer parent)
\r
88 MethodAttributes mattr;
\r
91 // FIXME: POSSIBLY make this static, as it is always constant
\r
93 Type [] const_arg_types = new Type [2];
\r
94 const_arg_types [0] = TypeManager.object_type;
\r
95 const_arg_types [1] = TypeManager.intptr_type;
\r
97 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
\r
98 MethodAttributes.HideBySig | MethodAttributes.Public;
\r
100 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
\r
101 CallingConventions.Standard,
\r
104 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
\r
105 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
\r
107 // HACK because System.Reflection.Emit is lame
\r
110 // FIXME: POSSIBLY make these static, as they are always the same
\r
111 Parameter [] fixed_pars = new Parameter [2];
\r
112 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
113 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
114 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
\r
116 TypeManager.RegisterMethod (
\r
117 ConstructorBuilder,
\r
118 new InternalParameters (const_arg_types, const_parameters),
\r
122 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
124 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
129 param_types = Parameters.GetParameterInfo (parent);
\r
130 if (param_types == null)
\r
133 // Check accessibility
\r
134 foreach (Type partype in param_types)
\r
135 if (!TypeContainer.AsAccessible (partype, ModFlags))
\r
138 ret_type = RootContext.LookupType (parent, ReturnType, false, Location);
\r
139 if (ret_type == null)
\r
142 if (!TypeContainer.AsAccessible (ret_type, ModFlags))
\r
146 // We don't have to check any others because they are all
\r
147 // guaranteed to be accessible - they are standard types.
\r
150 CallingConventions cc = Parameters.GetCallingConvention ();
\r
152 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
154 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
160 for (i = 0 ; i < param_types.Length; i++) {
\r
161 Parameter p = Parameters.FixedParameters [i];
\r
162 string name = p.Name;
\r
163 ParameterBuilder pb = InvokeBuilder.DefineParameter (i+1, p.Attributes, name);
\r
166 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
168 TypeManager.RegisterMethod (InvokeBuilder,
\r
169 new InternalParameters (parent, Parameters),
\r
175 int params_num = param_types.Length;
\r
176 Type [] async_param_types = new Type [params_num + 2];
\r
178 param_types.CopyTo (async_param_types, 0);
\r
180 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
181 async_param_types [params_num + 1] = TypeManager.object_type;
\r
183 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |
\r
184 MethodAttributes.NewSlot;
\r
186 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
189 TypeManager.iasyncresult_type,
\r
190 async_param_types);
\r
192 for (i = 0 ; i < param_types.Length; i++) {
\r
193 Parameter p = Parameters.FixedParameters [i];
\r
194 string name = p.Name;
\r
195 BeginInvokeBuilder.DefineParameter (i + 1, p.Attributes, name);
\r
198 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
199 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
201 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
203 Parameter [] async_params = new Parameter [params_num + 2];
\r
204 if (params_num > 0)
\r
205 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
207 async_params [params_num] = new Parameter ("System.AsyncCallback", "callback",
\r
208 Parameter.Modifier.NONE, null);
\r
209 async_params [params_num + 1] = new Parameter ("System.IAsyncResult", "object",
\r
210 Parameter.Modifier.NONE, null);
\r
212 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
213 new InternalParameters (
\r
215 new Parameters (async_params, null, Location)),
\r
216 async_param_types);
\r
221 Type [] end_param_types = new Type [1];
\r
222 end_param_types [0] = TypeManager.iasyncresult_type;
\r
224 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
229 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
231 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
233 Parameter [] end_params = new Parameter [1];
\r
234 end_params [0] = new Parameter ("System.IAsyncResult", "result",
\r
235 Parameter.Modifier.NONE, null);
\r
237 TypeManager.RegisterMethod (EndInvokeBuilder,
\r
238 new InternalParameters (
\r
240 new Parameters (end_params, null, Location)),
\r
247 /// Verifies whether the method in question is compatible with the delegate
\r
248 /// Returns the method itself if okay and null if not.
\r
250 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
\r
253 ParameterData pd = Invocation.GetParameterData (mb);
\r
255 Expression ml = Expression.MemberLookup (
\r
256 ec, delegate_type, "Invoke", loc);
\r
258 if (!(ml is MethodGroupExpr)) {
\r
259 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
263 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
265 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
267 bool mismatch = false;
\r
268 for (int i = pd.Count; i > 0; ) {
\r
271 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
281 123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
282 "' does not match delegate '" +
\r
283 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
287 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
293 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
294 "' does not match delegate '" +
\r
295 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
303 // Verifies whether the invocation arguments are compatible with the
\r
304 // delegate's target method
\r
306 public static bool VerifyApplicability (EmitContext ec, Type delegate_type, ArrayList args,
\r
314 arg_count = args.Count;
\r
316 Expression ml = Expression.MemberLookup (
\r
317 ec, delegate_type, "Invoke", loc);
\r
319 if (!(ml is MethodGroupExpr)) {
\r
320 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
324 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
326 ParameterData pd = Invocation.GetParameterData (mb);
\r
328 if (pd.Count != arg_count) {
\r
329 Report.Error (1593, loc,
\r
330 "Delegate '" + delegate_type.ToString ()
\r
331 + "' does not take '" + arg_count + "' arguments");
\r
335 for (int i = arg_count; i > 0;) {
\r
338 Argument a = (Argument) args [i];
\r
339 Expression a_expr = a.Expr;
\r
341 if (pd.ParameterType (i) != a_expr.Type) {
\r
343 conv = Expression.ConvertImplicitStandard (ec, a_expr, pd.ParameterType (i), loc);
\r
345 if (conv == null) {
\r
346 Report.Error (1594, loc,
\r
347 "Delegate '" + delegate_type.ToString () +
\r
348 "' has some invalid arguments.");
\r
350 Report.Error (1503, loc,
\r
351 "Argument " + (i+1) +
\r
352 ": Cannot convert from '" +
\r
353 TypeManager.CSharpName (a_expr.Type)
\r
354 + "' to '" + TypeManager.CSharpName (pd.ParameterType (i)) + "'");
\r
358 if (a_expr != conv)
\r
367 /// Verifies whether the delegate in question is compatible with this one in
\r
368 /// order to determine if instantiation from the same is possible.
\r
370 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
372 Expression ml = Expression.MemberLookup (
\r
373 ec, delegate_type, "Invoke", loc);
\r
375 if (!(ml is MethodGroupExpr)) {
\r
376 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
380 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
381 ParameterData pd = Invocation.GetParameterData (mb);
\r
383 Expression probe_ml = Expression.MemberLookup (
\r
384 ec, delegate_type, "Invoke", loc);
\r
386 if (!(probe_ml is MethodGroupExpr)) {
\r
387 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
391 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
392 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
394 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
397 if (pd.Count != probe_pd.Count)
\r
400 for (int i = pd.Count; i > 0; ) {
\r
403 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
404 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
411 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
413 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
415 sb.Append (" " + del_type.ToString ());
\r
418 int length = pd.Count;
\r
420 for (int i = length; i > 0; ) {
\r
423 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
429 return sb.ToString ();
\r
433 // Hack around System.Reflection as found everywhere else
\r
434 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
436 ArrayList members = new ArrayList ();
\r
438 if ((mt & MemberTypes.Method) != 0) {
\r
439 if (filter (ConstructorBuilder, criteria))
\r
440 members.Add (ConstructorBuilder);
\r
442 if (filter (InvokeBuilder, criteria))
\r
443 members.Add (InvokeBuilder);
\r
445 if (filter (BeginInvokeBuilder, criteria))
\r
446 members.Add (BeginInvokeBuilder);
\r
448 if (filter (EndInvokeBuilder, criteria))
\r
449 members.Add (EndInvokeBuilder);
\r
452 int count = members.Count;
\r
455 MemberInfo [] mi = new MemberInfo [count];
\r
456 members.CopyTo (mi, 0);
\r
463 public void CloseDelegate ()
\r
465 TypeBuilder.CreateType ();
\r
468 public Expression InstanceExpression {
\r
470 return instance_expr;
\r
473 instance_expr = value;
\r
477 public MethodBase TargetMethod {
\r
479 return delegate_method;
\r
482 delegate_method = value;
\r
486 public Type TargetReturnType {
\r
492 public Type [] ParameterTypes {
\r
494 return param_types;
\r
500 public class NewDelegate : Expression {
\r
502 public ArrayList Arguments;
\r
504 MethodBase constructor_method;
\r
505 MethodBase delegate_method;
\r
506 Expression delegate_instance_expr;
\r
510 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
513 this.Arguments = Arguments;
\r
514 this.Location = loc;
\r
517 public override Expression DoResolve (EmitContext ec)
\r
519 if (Arguments == null) {
\r
520 Report.Error (-11, Location,
\r
521 "Delegate creation expression takes only one argument");
\r
525 if (Arguments.Count != 1) {
\r
526 Report.Error (-11, Location,
\r
527 "Delegate creation expression takes only one argument");
\r
531 Expression ml = Expression.MemberLookup (
\r
532 ec, type, ".ctor", Location);
\r
534 if (!(ml is MethodGroupExpr)) {
\r
535 Report.Error (-100, Location, "Internal error : Could not find delegate constructor!");
\r
539 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
541 Argument a = (Argument) Arguments [0];
\r
543 if (!a.Resolve (ec, Location))
\r
546 Expression e = a.Expr;
\r
548 if (e is MethodGroupExpr) {
\r
549 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
551 if (mg.Methods.Length > 1) {
\r
552 Report.Error (-14, Location, "Ambiguous method reference in delegate creation");
\r
556 delegate_method = Delegate.VerifyMethod (ec, type, mg.Methods [0], Location);
\r
558 if (delegate_method == null)
\r
561 if (mg.InstanceExpression != null)
\r
562 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
565 delegate_instance_expr = ec.This;
\r
567 delegate_instance_expr = null;
\r
570 if (delegate_instance_expr != null)
\r
571 if (delegate_instance_expr.Type.IsValueType)
\r
572 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
574 eclass = ExprClass.Value;
\r
578 Type e_type = e.Type;
\r
580 if (!TypeManager.IsDelegateType (e_type)) {
\r
581 Report.Error (-12, Location, "Cannot create a delegate from something " +
\r
582 "not a delegate or a method.");
\r
586 // This is what MS' compiler reports. We could always choose
\r
587 // to be more verbose and actually give delegate-level specifics
\r
589 if (!Delegate.VerifyDelegate (ec, type, e_type, Location)) {
\r
590 Report.Error (29, Location, "Cannot implicitly convert type '" + e_type + "' " +
\r
591 "to type '" + type + "'");
\r
595 Expression invoke_method = Expression.MemberLookup (
\r
596 ec, e_type, "Invoke", MemberTypes.Method,
\r
597 Expression.AllBindingFlags, Location);
\r
599 if (invoke_method == null) {
\r
600 Report.Error (-200, Location, "Internal error ! COuld not find Invoke method!");
\r
604 delegate_instance_expr = e;
\r
605 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
607 eclass = ExprClass.Value;
\r
611 public override void Emit (EmitContext ec)
\r
613 if (delegate_instance_expr == null)
\r
614 ec.ig.Emit (OpCodes.Ldnull);
\r
616 delegate_instance_expr.Emit (ec);
\r
618 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
619 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
623 public class DelegateInvocation : ExpressionStatement {
\r
625 public Expression InstanceExpr;
\r
626 public ArrayList Arguments;
\r
627 public Location Location;
\r
631 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
633 this.InstanceExpr = instance_expr;
\r
634 this.Arguments = args;
\r
635 this.Location = loc;
\r
638 public override Expression DoResolve (EmitContext ec)
\r
640 Type del_type = InstanceExpr.Type;
\r
642 if (del_type == null)
\r
645 if (Arguments != null){
\r
646 for (int i = Arguments.Count; i > 0;){
\r
648 Argument a = (Argument) Arguments [i];
\r
650 if (!a.Resolve (ec, Location))
\r
655 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, Location))
\r
658 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", Location);
\r
660 if (!(ml is MethodGroupExpr)) {
\r
661 Report.Error (-100, Location, "Internal error : could not find Invoke method!");
\r
665 method = ((MethodGroupExpr) ml).Methods [0];
\r
667 type = ((MethodInfo) method).ReturnType;
\r
669 eclass = ExprClass.Value;
\r
674 public override void Emit (EmitContext ec)
\r
676 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
679 // Invocation on delegates call the virtual Invoke member
\r
680 // so we are always `instance' calls
\r
682 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments);
\r
685 public override void EmitStatement (EmitContext ec)
\r
689 // Pop the return value if there is one
\r
691 if (method is MethodInfo){
\r
692 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
693 ec.ig.Emit (OpCodes.Pop);
\r