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