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 Expression 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, Expression 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,
\r
54 IsTopLevel ? Modifiers.INTERNAL :
\r
55 Modifiers.PRIVATE, l);
\r
56 Parameters = param_list;
\r
57 OptAttributes = attrs;
\r
60 public override TypeBuilder DefineType ()
\r
62 TypeAttributes attr;
\r
64 if (TypeBuilder != null)
\r
68 ModuleBuilder builder = CodeGen.ModuleBuilder;
\r
69 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
\r
71 TypeBuilder = builder.DefineType (
\r
72 Name, attr, TypeManager.multicast_delegate_type);
\r
74 TypeBuilder builder = Parent.TypeBuilder;
\r
75 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
\r
76 TypeAttributes.Sealed;
\r
78 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
\r
79 TypeBuilder = builder.DefineNestedType (
\r
80 name, attr, TypeManager.multicast_delegate_type);
\r
83 TypeManager.AddDelegateType (Name, TypeBuilder, this);
\r
88 public override bool DefineMembers (TypeContainer container)
\r
93 public override bool Define (TypeContainer container)
\r
95 MethodAttributes mattr;
\r
98 // FIXME: POSSIBLY make this static, as it is always constant
\r
100 Type [] const_arg_types = new Type [2];
\r
101 const_arg_types [0] = TypeManager.object_type;
\r
102 const_arg_types [1] = TypeManager.intptr_type;
\r
104 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
\r
105 MethodAttributes.HideBySig | MethodAttributes.Public;
\r
107 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
\r
108 CallingConventions.Standard,
\r
111 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
\r
112 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
\r
114 // HACK because System.Reflection.Emit is lame
\r
117 // FIXME: POSSIBLY make these static, as they are always the same
\r
118 Parameter [] fixed_pars = new Parameter [2];
\r
119 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
120 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
121 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
\r
123 TypeManager.RegisterMethod (
\r
124 ConstructorBuilder,
\r
125 new InternalParameters (const_arg_types, const_parameters),
\r
129 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
132 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
134 // First, call the `out of band' special method for
\r
135 // defining recursively any types we need:
\r
137 if (!Parameters.ComputeAndDefineParameterTypes (this))
\r
140 param_types = Parameters.GetParameterInfo (this);
\r
141 if (param_types == null)
\r
148 // Check accessibility
\r
149 foreach (Type partype in param_types)
\r
150 if (!container.AsAccessible (partype, ModFlags)) {
\r
151 Report.Error (59, Location,
\r
152 "Inconsistent accessibility: parameter type `" +
\r
153 TypeManager.CSharpName (partype) + "` is less " +
\r
154 "accessible than delegate `" + Name + "'");
\r
158 ReturnType = ResolveTypeExpr (ReturnType, false, Location);
\r
159 ret_type = ReturnType.Type;
\r
160 if (ret_type == null)
\r
163 if (!container.AsAccessible (ret_type, ModFlags)) {
\r
164 Report.Error (58, Location,
\r
165 "Inconsistent accessibility: return type `" +
\r
166 TypeManager.CSharpName (ret_type) + "` is less " +
\r
167 "accessible than delegate `" + Name + "'");
\r
172 // We don't have to check any others because they are all
\r
173 // guaranteed to be accessible - they are standard types.
\r
176 CallingConventions cc = Parameters.GetCallingConvention ();
\r
178 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
180 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
187 if (Parameters.FixedParameters != null){
\r
188 int top = Parameters.FixedParameters.Length;
\r
191 for (; i < top; i++) {
\r
192 p = Parameters.FixedParameters [i];
\r
194 InvokeBuilder.DefineParameter (
\r
195 i+1, p.Attributes, p.Name);
\r
198 if (Parameters.ArrayParameter != null){
\r
199 Parameter p = Parameters.ArrayParameter;
\r
201 InvokeBuilder.DefineParameter (
\r
202 i+1, p.Attributes, p.Name);
\r
205 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
207 TypeManager.RegisterMethod (InvokeBuilder,
\r
208 new InternalParameters (container, Parameters),
\r
214 int params_num = param_types.Length;
\r
215 Type [] async_param_types = new Type [params_num + 2];
\r
217 param_types.CopyTo (async_param_types, 0);
\r
219 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
220 async_param_types [params_num + 1] = TypeManager.object_type;
\r
222 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
\r
223 MethodAttributes.Virtual | MethodAttributes.NewSlot;
\r
225 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
228 TypeManager.iasyncresult_type,
\r
229 async_param_types);
\r
232 if (Parameters.FixedParameters != null){
\r
233 int top = Parameters.FixedParameters.Length;
\r
236 for (i = 0 ; i < top; i++) {
\r
237 p = Parameters.FixedParameters [i];
\r
239 BeginInvokeBuilder.DefineParameter (
\r
240 i+1, p.Attributes, p.Name);
\r
243 if (Parameters.ArrayParameter != null){
\r
244 Parameter p = Parameters.ArrayParameter;
\r
246 BeginInvokeBuilder.DefineParameter (
\r
247 i+1, p.Attributes, p.Name);
\r
251 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
252 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
254 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
256 Parameter [] async_params = new Parameter [params_num + 2];
\r
258 if (Parameters.FixedParameters != null){
\r
259 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
260 n = Parameters.FixedParameters.Length;
\r
262 if (Parameters.ArrayParameter != null)
\r
263 async_params [n] = Parameters.ArrayParameter;
\r
265 async_params [params_num] = new Parameter (
\r
266 TypeManager.system_asynccallback_expr, "callback",
\r
267 Parameter.Modifier.NONE, null);
\r
268 async_params [params_num + 1] = new Parameter (
\r
269 TypeManager.system_object_expr, "object",
\r
270 Parameter.Modifier.NONE, null);
\r
272 Parameters async_parameters = new Parameters (async_params, null, Location);
\r
274 async_parameters.ComputeAndDefineParameterTypes (this);
\r
275 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
276 new InternalParameters (container, async_parameters),
\r
277 async_param_types);
\r
282 Type [] end_param_types = new Type [1];
\r
283 end_param_types [0] = TypeManager.iasyncresult_type;
\r
285 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
290 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
292 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
294 Parameter [] end_params = new Parameter [1];
\r
295 end_params [0] = new Parameter (
\r
296 TypeManager.system_iasyncresult_expr, "result",
\r
297 Parameter.Modifier.NONE, null);
\r
299 TypeManager.RegisterMethod (
\r
300 EndInvokeBuilder, new InternalParameters (
\r
303 end_params, null, Location)),
\r
310 /// Verifies whether the method in question is compatible with the delegate
\r
311 /// Returns the method itself if okay and null if not.
\r
313 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
\r
316 ParameterData pd = Invocation.GetParameterData (mb);
\r
318 int pd_count = pd.Count;
\r
320 Expression ml = Expression.MemberLookup (
\r
321 ec, delegate_type, "Invoke", loc);
\r
323 if (!(ml is MethodGroupExpr)) {
\r
324 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
328 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
330 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
332 if (invoke_pd.Count != pd_count)
\r
335 for (int i = pd_count; i > 0; ) {
\r
338 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
344 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
351 // Verifies whether the invocation arguments are compatible with the
\r
352 // delegate's target method
\r
354 public static bool VerifyApplicability (EmitContext ec,
\r
355 Type delegate_type,
\r
364 arg_count = args.Count;
\r
366 Expression ml = Expression.MemberLookup (
\r
367 ec, delegate_type, "Invoke", loc);
\r
369 if (!(ml is MethodGroupExpr)) {
\r
370 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
\r
374 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
375 ParameterData pd = Invocation.GetParameterData (mb);
\r
377 int pd_count = pd.Count;
\r
379 bool not_params_method = (pd_count == 0) ||
\r
380 (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
\r
382 if (not_params_method && pd_count != arg_count) {
\r
383 Report.Error (1593, loc,
\r
384 "Delegate '" + delegate_type.ToString ()
\r
385 + "' does not take '" + arg_count + "' arguments");
\r
389 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
\r
390 delegate_type, loc);
\r
394 /// Verifies whether the delegate in question is compatible with this one in
\r
395 /// order to determine if instantiation from the same is possible.
\r
397 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
399 Expression ml = Expression.MemberLookup (
\r
400 ec, delegate_type, "Invoke", loc);
\r
402 if (!(ml is MethodGroupExpr)) {
\r
403 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
407 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
408 ParameterData pd = Invocation.GetParameterData (mb);
\r
410 Expression probe_ml = Expression.MemberLookup (
\r
411 ec, delegate_type, "Invoke", loc);
\r
413 if (!(probe_ml is MethodGroupExpr)) {
\r
414 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
418 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
419 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
421 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
424 if (pd.Count != probe_pd.Count)
\r
427 for (int i = pd.Count; i > 0; ) {
\r
430 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
431 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
438 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
440 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
442 sb.Append (" " + del_type.ToString ());
\r
445 int length = pd.Count;
\r
447 for (int i = length; i > 0; ) {
\r
450 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
456 return sb.ToString ();
\r
460 // Hack around System.Reflection as found everywhere else
\r
461 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
\r
462 MemberFilter filter, object criteria)
\r
464 ArrayList members = new ArrayList ();
\r
466 if ((mt & MemberTypes.Method) != 0) {
\r
467 if (ConstructorBuilder != null)
\r
468 if (filter (ConstructorBuilder, criteria))
\r
469 members.Add (ConstructorBuilder);
\r
471 if (InvokeBuilder != null)
\r
472 if (filter (InvokeBuilder, criteria))
\r
473 members.Add (InvokeBuilder);
\r
475 if (BeginInvokeBuilder != null)
\r
476 if (filter (BeginInvokeBuilder, criteria))
\r
477 members.Add (BeginInvokeBuilder);
\r
479 if (EndInvokeBuilder != null)
\r
480 if (filter (EndInvokeBuilder, criteria))
\r
481 members.Add (EndInvokeBuilder);
\r
484 return new MemberList (members);
\r
487 public override MemberCache MemberCache {
\r
493 public Expression InstanceExpression {
\r
495 return instance_expr;
\r
498 instance_expr = value;
\r
502 public MethodBase TargetMethod {
\r
504 return delegate_method;
\r
507 delegate_method = value;
\r
511 public Type TargetReturnType {
\r
517 public Type [] ParameterTypes {
\r
519 return param_types;
\r
525 public class NewDelegate : Expression {
\r
527 public ArrayList Arguments;
\r
529 MethodBase constructor_method;
\r
530 MethodBase delegate_method;
\r
531 Expression delegate_instance_expr;
\r
533 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
536 this.Arguments = Arguments;
\r
540 public override Expression DoResolve (EmitContext ec)
\r
542 if (Arguments == null) {
\r
543 Report.Error (-11, loc,
\r
544 "Delegate creation expression takes only one argument");
\r
548 if (Arguments.Count != 1) {
\r
549 Report.Error (-11, loc,
\r
550 "Delegate creation expression takes only one argument");
\r
554 Expression ml = Expression.MemberLookup (
\r
555 ec, type, ".ctor", loc);
\r
557 if (!(ml is MethodGroupExpr)) {
\r
558 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
\r
562 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
563 Argument a = (Argument) Arguments [0];
\r
565 if (!a.ResolveMethodGroup (ec, Location))
\r
568 Expression e = a.Expr;
\r
570 Expression invoke_method = Expression.MemberLookup (
\r
571 ec, type, "Invoke", MemberTypes.Method,
\r
572 Expression.AllBindingFlags, loc);
\r
574 if (invoke_method == null) {
\r
575 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
\r
579 if (e is MethodGroupExpr) {
\r
580 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
582 foreach (MethodInfo mi in mg.Methods){
\r
583 delegate_method = Delegate.VerifyMethod (ec, type, mi, loc);
\r
585 if (delegate_method != null)
\r
589 if (delegate_method == null) {
\r
590 string method_desc;
\r
591 if (mg.Methods.Length > 1)
\r
592 method_desc = mg.Methods [0].Name;
\r
594 method_desc = Invocation.FullMethodDesc (mg.Methods [0]);
\r
596 MethodBase dm = ((MethodGroupExpr) invoke_method).Methods [0];
\r
597 ParameterData param = Invocation.GetParameterData (dm);
\r
598 string delegate_desc = Delegate.FullDelegateDesc (type, dm, param);
\r
600 Report.Error (123, loc, "Method '" + method_desc + "' does not " +
\r
601 "match delegate '" + delegate_desc + "'");
\r
607 // Check safe/unsafe of the delegate
\r
610 ParameterData param = Invocation.GetParameterData (delegate_method);
\r
611 int count = param.Count;
\r
613 for (int i = 0; i < count; i++){
\r
614 if (param.ParameterType (i).IsPointer){
\r
615 Expression.UnsafeError (loc);
\r
621 if (mg.InstanceExpression != null)
\r
622 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
625 delegate_instance_expr = ec.This;
\r
627 delegate_instance_expr = null;
\r
630 if (delegate_instance_expr != null)
\r
631 if (delegate_instance_expr.Type.IsValueType)
\r
632 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
634 eclass = ExprClass.Value;
\r
638 Type e_type = e.Type;
\r
640 if (!TypeManager.IsDelegateType (e_type)) {
\r
641 Report.Error (-12, loc, "Cannot create a delegate from something " +
\r
642 "not a delegate or a method.");
\r
646 // This is what MS' compiler reports. We could always choose
\r
647 // to be more verbose and actually give delegate-level specifics
\r
649 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
\r
650 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
\r
651 "to type '" + type + "'");
\r
655 delegate_instance_expr = e;
\r
656 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
658 eclass = ExprClass.Value;
\r
662 public override void Emit (EmitContext ec)
\r
664 if (delegate_instance_expr == null ||
\r
665 delegate_method.IsStatic)
\r
666 ec.ig.Emit (OpCodes.Ldnull);
\r
668 delegate_instance_expr.Emit (ec);
\r
670 if (delegate_method.IsVirtual) {
\r
671 ec.ig.Emit (OpCodes.Dup);
\r
672 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
\r
674 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
675 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
679 public class DelegateInvocation : ExpressionStatement {
\r
681 public Expression InstanceExpr;
\r
682 public ArrayList Arguments;
\r
686 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
688 this.InstanceExpr = instance_expr;
\r
689 this.Arguments = args;
\r
693 public override Expression DoResolve (EmitContext ec)
\r
695 if (InstanceExpr is EventExpr) {
\r
697 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
\r
699 Expression ml = MemberLookup (
\r
700 ec, ec.ContainerType, ei.Name,
\r
701 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
\r
705 // If this is the case, then the Event does not belong
\r
706 // to this Type and so, according to the spec
\r
707 // cannot be accessed directly
\r
709 // Note that target will not appear as an EventExpr
\r
710 // in the case it is being referenced within the same type container;
\r
711 // it will appear as a FieldExpr in that case.
\r
714 Assign.error70 (ei, loc);
\r
720 Type del_type = InstanceExpr.Type;
\r
721 if (del_type == null)
\r
724 if (Arguments != null){
\r
725 foreach (Argument a in Arguments){
\r
726 if (!a.Resolve (ec, loc))
\r
731 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
\r
734 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
\r
735 if (!(lookup is MethodGroupExpr)) {
\r
736 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
740 method = ((MethodGroupExpr) lookup).Methods [0];
\r
741 type = ((MethodInfo) method).ReturnType;
\r
742 eclass = ExprClass.Value;
\r
747 public override void Emit (EmitContext ec)
\r
749 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
752 // Invocation on delegates call the virtual Invoke member
\r
753 // so we are always `instance' calls
\r
755 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
\r
758 public override void EmitStatement (EmitContext ec)
\r
762 // Pop the return value if there is one
\r
764 if (method is MethodInfo){
\r
765 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
766 ec.ig.Emit (OpCodes.Pop);
\r