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
339 invoke_pd.ParameterModifier (i) == pd.ParameterModifier (i))
\r
345 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
352 // Verifies whether the invocation arguments are compatible with the
\r
353 // delegate's target method
\r
355 public static bool VerifyApplicability (EmitContext ec,
\r
356 Type delegate_type,
\r
365 arg_count = args.Count;
\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!" + delegate_type);
\r
375 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
376 ParameterData pd = Invocation.GetParameterData (mb);
\r
378 int pd_count = pd.Count;
\r
380 bool not_params_method = (pd_count == 0) ||
\r
381 (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
\r
383 if (not_params_method && pd_count != arg_count) {
\r
384 Report.Error (1593, loc,
\r
385 "Delegate '" + delegate_type.ToString ()
\r
386 + "' does not take '" + arg_count + "' arguments");
\r
390 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
\r
391 delegate_type, loc);
\r
395 /// Verifies whether the delegate in question is compatible with this one in
\r
396 /// order to determine if instantiation from the same is possible.
\r
398 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
400 Expression ml = Expression.MemberLookup (
\r
401 ec, delegate_type, "Invoke", loc);
\r
403 if (!(ml is MethodGroupExpr)) {
\r
404 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
408 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
409 ParameterData pd = Invocation.GetParameterData (mb);
\r
411 Expression probe_ml = Expression.MemberLookup (
\r
412 ec, delegate_type, "Invoke", loc);
\r
414 if (!(probe_ml is MethodGroupExpr)) {
\r
415 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
419 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
420 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
422 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
425 if (pd.Count != probe_pd.Count)
\r
428 for (int i = pd.Count; i > 0; ) {
\r
431 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
432 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
439 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
441 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
443 sb.Append (" " + del_type.ToString ());
\r
446 int length = pd.Count;
\r
448 for (int i = length; i > 0; ) {
\r
451 sb.Append (pd.ParameterDesc (length - i - 1));
\r
457 return sb.ToString ();
\r
461 // Hack around System.Reflection as found everywhere else
\r
462 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
\r
463 MemberFilter filter, object criteria)
\r
465 ArrayList members = new ArrayList ();
\r
467 if ((mt & MemberTypes.Method) != 0) {
\r
468 if (ConstructorBuilder != null)
\r
469 if (filter (ConstructorBuilder, criteria))
\r
470 members.Add (ConstructorBuilder);
\r
472 if (InvokeBuilder != null)
\r
473 if (filter (InvokeBuilder, criteria))
\r
474 members.Add (InvokeBuilder);
\r
476 if (BeginInvokeBuilder != null)
\r
477 if (filter (BeginInvokeBuilder, criteria))
\r
478 members.Add (BeginInvokeBuilder);
\r
480 if (EndInvokeBuilder != null)
\r
481 if (filter (EndInvokeBuilder, criteria))
\r
482 members.Add (EndInvokeBuilder);
\r
485 return new MemberList (members);
\r
488 public override MemberCache MemberCache {
\r
494 public Expression InstanceExpression {
\r
496 return instance_expr;
\r
499 instance_expr = value;
\r
503 public MethodBase TargetMethod {
\r
505 return delegate_method;
\r
508 delegate_method = value;
\r
512 public Type TargetReturnType {
\r
518 public Type [] ParameterTypes {
\r
520 return param_types;
\r
526 public class NewDelegate : Expression {
\r
528 public ArrayList Arguments;
\r
530 MethodBase constructor_method;
\r
531 MethodBase delegate_method;
\r
532 Expression delegate_instance_expr;
\r
534 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
537 this.Arguments = Arguments;
\r
541 public override Expression DoResolve (EmitContext ec)
\r
543 if (Arguments == null) {
\r
544 Report.Error (-11, loc,
\r
545 "Delegate creation expression takes only one argument");
\r
549 if (Arguments.Count != 1) {
\r
550 Report.Error (-11, loc,
\r
551 "Delegate creation expression takes only one argument");
\r
555 Expression ml = Expression.MemberLookup (
\r
556 ec, type, ".ctor", loc);
\r
558 if (!(ml is MethodGroupExpr)) {
\r
559 Report.Error (-100, loc, "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.ResolveMethodGroup (ec, Location))
\r
569 Expression e = a.Expr;
\r
571 Expression invoke_method = Expression.MemberLookup (
\r
572 ec, type, "Invoke", MemberTypes.Method,
\r
573 Expression.AllBindingFlags, loc);
\r
575 if (invoke_method == null) {
\r
576 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
\r
580 if (e is MethodGroupExpr) {
\r
581 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
583 foreach (MethodInfo mi in mg.Methods){
\r
584 delegate_method = Delegate.VerifyMethod (ec, type, mi, loc);
\r
586 if (delegate_method != null)
\r
590 if (delegate_method == null) {
\r
591 string method_desc;
\r
592 if (mg.Methods.Length > 1)
\r
593 method_desc = mg.Methods [0].Name;
\r
595 method_desc = Invocation.FullMethodDesc (mg.Methods [0]);
\r
597 MethodBase dm = ((MethodGroupExpr) invoke_method).Methods [0];
\r
598 ParameterData param = Invocation.GetParameterData (dm);
\r
599 string delegate_desc = Delegate.FullDelegateDesc (type, dm, param);
\r
601 Report.Error (123, loc, "Method '" + method_desc + "' does not " +
\r
602 "match delegate '" + delegate_desc + "'");
\r
608 // Check safe/unsafe of the delegate
\r
611 ParameterData param = Invocation.GetParameterData (delegate_method);
\r
612 int count = param.Count;
\r
614 for (int i = 0; i < count; i++){
\r
615 if (param.ParameterType (i).IsPointer){
\r
616 Expression.UnsafeError (loc);
\r
622 if (mg.InstanceExpression != null)
\r
623 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
626 delegate_instance_expr = ec.This;
\r
628 delegate_instance_expr = null;
\r
631 if (delegate_instance_expr != null)
\r
632 if (delegate_instance_expr.Type.IsValueType)
\r
633 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
635 eclass = ExprClass.Value;
\r
639 Type e_type = e.Type;
\r
641 if (!TypeManager.IsDelegateType (e_type)) {
\r
642 Report.Error (-12, loc, "Cannot create a delegate from something " +
\r
643 "not a delegate or a method.");
\r
647 // This is what MS' compiler reports. We could always choose
\r
648 // to be more verbose and actually give delegate-level specifics
\r
650 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
\r
651 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
\r
652 "to type '" + type + "'");
\r
656 delegate_instance_expr = e;
\r
657 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
659 eclass = ExprClass.Value;
\r
663 public override void Emit (EmitContext ec)
\r
665 if (delegate_instance_expr == null ||
\r
666 delegate_method.IsStatic)
\r
667 ec.ig.Emit (OpCodes.Ldnull);
\r
669 delegate_instance_expr.Emit (ec);
\r
671 if (delegate_method.IsVirtual) {
\r
672 ec.ig.Emit (OpCodes.Dup);
\r
673 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
\r
675 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
676 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
680 public class DelegateInvocation : ExpressionStatement {
\r
682 public Expression InstanceExpr;
\r
683 public ArrayList Arguments;
\r
687 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
689 this.InstanceExpr = instance_expr;
\r
690 this.Arguments = args;
\r
694 public override Expression DoResolve (EmitContext ec)
\r
696 if (InstanceExpr is EventExpr) {
\r
698 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
\r
700 Expression ml = MemberLookup (
\r
701 ec, ec.ContainerType, ei.Name,
\r
702 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
\r
706 // If this is the case, then the Event does not belong
\r
707 // to this Type and so, according to the spec
\r
708 // cannot be accessed directly
\r
710 // Note that target will not appear as an EventExpr
\r
711 // in the case it is being referenced within the same type container;
\r
712 // it will appear as a FieldExpr in that case.
\r
715 Assign.error70 (ei, loc);
\r
721 Type del_type = InstanceExpr.Type;
\r
722 if (del_type == null)
\r
725 if (Arguments != null){
\r
726 foreach (Argument a in Arguments){
\r
727 if (!a.Resolve (ec, loc))
\r
732 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
\r
735 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
\r
736 if (!(lookup is MethodGroupExpr)) {
\r
737 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
\r
741 method = ((MethodGroupExpr) lookup).Methods [0];
\r
742 type = ((MethodInfo) method).ReturnType;
\r
743 eclass = ExprClass.Value;
\r
748 public override void Emit (EmitContext ec)
\r
750 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
753 // Invocation on delegates call the virtual Invoke member
\r
754 // so we are always `instance' calls
\r
756 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
\r
759 public override void EmitStatement (EmitContext ec)
\r
763 // Pop the return value if there is one
\r
765 if (method is MethodInfo){
\r
766 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
767 ec.ig.Emit (OpCodes.Pop);
\r