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 : DeclSpace {
\r
24 public readonly string ReturnType;
\r
25 public Parameters Parameters;
\r
26 public Attributes OptAttributes;
\r
28 public ConstructorBuilder ConstructorBuilder;
\r
29 public MethodBuilder InvokeBuilder;
\r
30 public MethodBuilder BeginInvokeBuilder;
\r
31 public MethodBuilder EndInvokeBuilder;
\r
33 Type [] param_types;
\r
36 Expression instance_expr;
\r
37 MethodBase delegate_method;
\r
39 const int AllowedModifiers =
\r
42 Modifiers.PROTECTED |
\r
43 Modifiers.INTERNAL |
\r
47 public Delegate (TypeContainer parent, string type, int mod_flags,
\r
48 string name, Parameters param_list,
\r
49 Attributes attrs, Location l)
\r
50 : base (parent, name, 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 override TypeBuilder DefineType ()
\r
60 TypeAttributes attr;
\r
62 if (TypeBuilder != null)
\r
66 ModuleBuilder builder = CodeGen.ModuleBuilder;
\r
67 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
\r
69 TypeBuilder = builder.DefineType (
\r
70 Name, attr, TypeManager.multicast_delegate_type);
\r
72 TypeBuilder builder = Parent.TypeBuilder;
\r
73 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
\r
74 TypeAttributes.Sealed;
\r
76 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
\r
77 TypeBuilder = builder.DefineNestedType (
\r
78 name, attr, TypeManager.multicast_delegate_type);
\r
81 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
125 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
127 // First, call the `out of band' special method for
\r
128 // defining recursively any types we need:
\r
130 if (!Parameters.ComputeAndDefineParameterTypes (this))
\r
133 param_types = Parameters.GetParameterInfo (this);
\r
134 if (param_types == null)
\r
141 // Check accessibility
\r
142 foreach (Type partype in param_types)
\r
143 if (!TypeContainer.AsAccessible (partype, ModFlags))
\r
146 ret_type = FindType (ReturnType);
\r
147 if (ret_type == null)
\r
150 if (!TypeContainer.AsAccessible (ret_type, ModFlags))
\r
154 // We don't have to check any others because they are all
\r
155 // guaranteed to be accessible - they are standard types.
\r
158 CallingConventions cc = Parameters.GetCallingConvention ();
\r
160 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
162 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
169 if (Parameters.FixedParameters != null){
\r
170 int top = Parameters.FixedParameters.Length;
\r
173 for (; i < top; i++) {
\r
174 p = Parameters.FixedParameters [i];
\r
176 InvokeBuilder.DefineParameter (
\r
177 i+1, p.Attributes, p.Name);
\r
180 if (Parameters.ArrayParameter != null){
\r
181 Parameter p = Parameters.ArrayParameter;
\r
183 InvokeBuilder.DefineParameter (
\r
184 i+1, p.Attributes, p.Name);
\r
187 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
189 TypeManager.RegisterMethod (InvokeBuilder,
\r
190 new InternalParameters (parent, Parameters),
\r
196 int params_num = param_types.Length;
\r
197 Type [] async_param_types = new Type [params_num + 2];
\r
199 param_types.CopyTo (async_param_types, 0);
\r
201 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
202 async_param_types [params_num + 1] = TypeManager.object_type;
\r
204 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
\r
205 MethodAttributes.Virtual | MethodAttributes.NewSlot;
\r
207 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
210 TypeManager.iasyncresult_type,
\r
211 async_param_types);
\r
214 if (Parameters.FixedParameters != null){
\r
215 int top = Parameters.FixedParameters.Length;
\r
218 for (i = 0 ; i < top; i++) {
\r
219 p = Parameters.FixedParameters [i];
\r
221 BeginInvokeBuilder.DefineParameter (
\r
222 i+1, p.Attributes, p.Name);
\r
225 if (Parameters.ArrayParameter != null){
\r
226 Parameter p = Parameters.ArrayParameter;
\r
228 BeginInvokeBuilder.DefineParameter (
\r
229 i+1, p.Attributes, p.Name);
\r
233 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
234 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
236 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
238 Parameter [] async_params = new Parameter [params_num + 2];
\r
240 if (Parameters.FixedParameters != null){
\r
241 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
242 n = Parameters.FixedParameters.Length;
\r
244 if (Parameters.ArrayParameter != null)
\r
245 async_params [n] = Parameters.ArrayParameter;
\r
247 async_params [params_num] = new Parameter ("System.AsyncCallback", "callback",
\r
248 Parameter.Modifier.NONE, null);
\r
249 async_params [params_num + 1] = new Parameter ("System.Object", "object",
\r
250 Parameter.Modifier.NONE, null);
\r
252 Parameters async_parameters = new Parameters (async_params, null, Location);
\r
254 async_parameters.ComputeAndDefineParameterTypes (this);
\r
255 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
256 new InternalParameters (parent, async_parameters),
\r
257 async_param_types);
\r
262 Type [] end_param_types = new Type [1];
\r
263 end_param_types [0] = TypeManager.iasyncresult_type;
\r
265 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
270 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
272 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
274 Parameter [] end_params = new Parameter [1];
\r
275 end_params [0] = new Parameter ("System.IAsyncResult", "result",
\r
276 Parameter.Modifier.NONE, null);
\r
278 TypeManager.RegisterMethod (EndInvokeBuilder,
\r
279 new InternalParameters (
\r
281 new Parameters (end_params, null, Location)),
\r
288 /// Verifies whether the method in question is compatible with the delegate
\r
289 /// Returns the method itself if okay and null if not.
\r
291 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
\r
294 ParameterData pd = Invocation.GetParameterData (mb);
\r
296 int pd_count = pd.Count;
\r
298 Expression ml = Expression.MemberLookup (
\r
299 ec, delegate_type, "Invoke", loc);
\r
301 if (!(ml is MethodGroupExpr)) {
\r
302 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
306 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
308 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
310 if (invoke_pd.Count != pd_count)
\r
313 bool mismatch = false;
\r
314 for (int i = pd_count; i > 0; ) {
\r
317 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
327 123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
328 "' does not match delegate '" +
\r
329 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
333 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
339 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
340 "' does not match delegate '" +
\r
341 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
349 // Verifies whether the invocation arguments are compatible with the
\r
350 // delegate's target method
\r
352 public static bool VerifyApplicability (EmitContext ec,
\r
353 Type delegate_type,
\r
362 arg_count = args.Count;
\r
364 Expression ml = Expression.MemberLookup (
\r
365 ec, delegate_type, "Invoke", 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 int pd_count = pd.Count;
\r
377 bool not_params_method = (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
\r
379 if (not_params_method && pd_count != arg_count) {
\r
380 Report.Error (1593, loc,
\r
381 "Delegate '" + delegate_type.ToString ()
\r
382 + "' does not take '" + arg_count + "' arguments");
\r
386 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
\r
387 delegate_type, loc);
\r
391 /// Verifies whether the delegate in question is compatible with this one in
\r
392 /// order to determine if instantiation from the same is possible.
\r
394 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
396 Expression ml = Expression.MemberLookup (
\r
397 ec, delegate_type, "Invoke", loc);
\r
399 if (!(ml is MethodGroupExpr)) {
\r
400 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
404 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
405 ParameterData pd = Invocation.GetParameterData (mb);
\r
407 Expression probe_ml = Expression.MemberLookup (
\r
408 ec, delegate_type, "Invoke", loc);
\r
410 if (!(probe_ml is MethodGroupExpr)) {
\r
411 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
415 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
416 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
418 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
421 if (pd.Count != probe_pd.Count)
\r
424 for (int i = pd.Count; i > 0; ) {
\r
427 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
428 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
435 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
437 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
439 sb.Append (" " + del_type.ToString ());
\r
442 int length = pd.Count;
\r
444 for (int i = length; i > 0; ) {
\r
447 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
453 return sb.ToString ();
\r
457 // Hack around System.Reflection as found everywhere else
\r
458 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
460 ArrayList members = new ArrayList ();
\r
462 if ((mt & MemberTypes.Method) != 0) {
\r
463 if (filter (ConstructorBuilder, criteria))
\r
464 members.Add (ConstructorBuilder);
\r
466 if (filter (InvokeBuilder, criteria))
\r
467 members.Add (InvokeBuilder);
\r
469 if (filter (BeginInvokeBuilder, criteria))
\r
470 members.Add (BeginInvokeBuilder);
\r
472 if (filter (EndInvokeBuilder, criteria))
\r
473 members.Add (EndInvokeBuilder);
\r
476 int count = members.Count;
\r
479 MemberInfo [] mi = new MemberInfo [count];
\r
480 members.CopyTo (mi, 0);
\r
487 public void CloseDelegate ()
\r
489 TypeBuilder.CreateType ();
\r
492 public Expression InstanceExpression {
\r
494 return instance_expr;
\r
497 instance_expr = value;
\r
501 public MethodBase TargetMethod {
\r
503 return delegate_method;
\r
506 delegate_method = value;
\r
510 public Type TargetReturnType {
\r
516 public Type [] ParameterTypes {
\r
518 return param_types;
\r
524 public class NewDelegate : Expression {
\r
526 public ArrayList Arguments;
\r
528 MethodBase constructor_method;
\r
529 MethodBase delegate_method;
\r
530 Expression delegate_instance_expr;
\r
534 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
537 this.Arguments = Arguments;
\r
538 this.Location = loc;
\r
541 public override Expression DoResolve (EmitContext ec)
\r
543 if (Arguments == null) {
\r
544 Report.Error (-11, Location,
\r
545 "Delegate creation expression takes only one argument");
\r
549 if (Arguments.Count != 1) {
\r
550 Report.Error (-11, Location,
\r
551 "Delegate creation expression takes only one argument");
\r
555 Expression ml = Expression.MemberLookup (
\r
556 ec, type, ".ctor", Location);
\r
558 if (!(ml is MethodGroupExpr)) {
\r
559 Report.Error (-100, Location, "Internal error : Could not find delegate constructor!");
\r
563 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
564 Argument a = (Argument) Arguments [0];
\r
566 if (!a.Resolve (ec, Location))
\r
569 Expression e = a.Expr;
\r
571 if (e is MethodGroupExpr) {
\r
572 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
574 foreach (MethodInfo mi in mg.Methods){
\r
575 delegate_method = Delegate.VerifyMethod (ec, type, mi, Location);
\r
577 if (delegate_method != null)
\r
581 if (delegate_method == null) {
\r
582 Report.Error (-14, Location, "Ambiguous method reference in delegate creation");
\r
586 if (mg.InstanceExpression != null)
\r
587 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
590 delegate_instance_expr = ec.This;
\r
592 delegate_instance_expr = null;
\r
595 if (delegate_instance_expr != null)
\r
596 if (delegate_instance_expr.Type.IsValueType)
\r
597 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
599 eclass = ExprClass.Value;
\r
603 Type e_type = e.Type;
\r
605 if (!TypeManager.IsDelegateType (e_type)) {
\r
606 Report.Error (-12, Location, "Cannot create a delegate from something " +
\r
607 "not a delegate or a method.");
\r
611 // This is what MS' compiler reports. We could always choose
\r
612 // to be more verbose and actually give delegate-level specifics
\r
614 if (!Delegate.VerifyDelegate (ec, type, e_type, Location)) {
\r
615 Report.Error (29, Location, "Cannot implicitly convert type '" + e_type + "' " +
\r
616 "to type '" + type + "'");
\r
620 Expression invoke_method = Expression.MemberLookup (
\r
621 ec, e_type, "Invoke", MemberTypes.Method,
\r
622 Expression.AllBindingFlags, Location);
\r
624 if (invoke_method == null) {
\r
625 Report.Error (-200, Location, "Internal error ! COuld not find Invoke method!");
\r
629 delegate_instance_expr = e;
\r
630 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
632 eclass = ExprClass.Value;
\r
636 public override void Emit (EmitContext ec)
\r
638 if (delegate_instance_expr == null ||
\r
639 delegate_method.IsStatic)
\r
640 ec.ig.Emit (OpCodes.Ldnull);
\r
642 delegate_instance_expr.Emit (ec);
\r
644 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
645 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
649 public class DelegateInvocation : ExpressionStatement {
\r
651 public Expression InstanceExpr;
\r
652 public ArrayList Arguments;
\r
653 public Location Location;
\r
657 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
659 this.InstanceExpr = instance_expr;
\r
660 this.Arguments = args;
\r
661 this.Location = loc;
\r
664 public override Expression DoResolve (EmitContext ec)
\r
666 Type del_type = InstanceExpr.Type;
\r
667 if (del_type == null)
\r
670 if (Arguments != null){
\r
671 foreach (Argument a in Arguments){
\r
672 if (!a.Resolve (ec, Location))
\r
677 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, Location))
\r
680 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", Location);
\r
681 if (!(ml is MethodGroupExpr)) {
\r
682 Report.Error (-100, Location, "Internal error : could not find Invoke method!");
\r
686 method = ((MethodGroupExpr) ml).Methods [0];
\r
687 type = ((MethodInfo) method).ReturnType;
\r
688 eclass = ExprClass.Value;
\r
693 public override void Emit (EmitContext ec)
\r
695 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
698 // Invocation on delegates call the virtual Invoke member
\r
699 // so we are always `instance' calls
\r
701 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, Location);
\r
704 public override void EmitStatement (EmitContext ec)
\r
708 // Pop the return value if there is one
\r
710 if (method is MethodInfo){
\r
711 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
712 ec.ig.Emit (OpCodes.Pop);
\r