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!");
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.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
381 if (not_params_method && pd_count != arg_count) {
382 Report.Error (1593, loc,
383 "Delegate '" + delegate_type.ToString ()
384 + "' does not take '" + arg_count + "' arguments");
388 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
393 /// Verifies whether the delegate in question is compatible with this one in
394 /// order to determine if instantiation from the same is possible.
396 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
398 Expression ml = Expression.MemberLookup (
399 ec, delegate_type, "Invoke", loc);
401 if (!(ml is MethodGroupExpr)) {
402 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
406 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
407 ParameterData pd = Invocation.GetParameterData (mb);
409 Expression probe_ml = Expression.MemberLookup (
410 ec, delegate_type, "Invoke", loc);
412 if (!(probe_ml is MethodGroupExpr)) {
413 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
417 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
418 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
420 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
423 if (pd.Count != probe_pd.Count)
426 for (int i = pd.Count; i > 0; ) {
429 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
430 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
437 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
439 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
441 sb.Append (" " + del_type.ToString ());
444 int length = pd.Count;
446 for (int i = length; i > 0; ) {
449 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
455 return sb.ToString ();
459 // Hack around System.Reflection as found everywhere else
460 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
461 MemberFilter filter, object criteria)
463 ArrayList members = new ArrayList ();
465 if ((mt & MemberTypes.Method) != 0) {
466 if (ConstructorBuilder != null)
467 if (filter (ConstructorBuilder, criteria))
468 members.Add (ConstructorBuilder);
470 if (InvokeBuilder != null)
471 if (filter (InvokeBuilder, criteria))
472 members.Add (InvokeBuilder);
474 if (BeginInvokeBuilder != null)
475 if (filter (BeginInvokeBuilder, criteria))
476 members.Add (BeginInvokeBuilder);
478 if (EndInvokeBuilder != null)
479 if (filter (EndInvokeBuilder, criteria))
480 members.Add (EndInvokeBuilder);
483 return new MemberList (members);
486 public override MemberCache MemberCache {
492 public void CloseDelegate ()
494 TypeBuilder.CreateType ();
497 public Expression InstanceExpression {
499 return instance_expr;
502 instance_expr = value;
506 public MethodBase TargetMethod {
508 return delegate_method;
511 delegate_method = value;
515 public Type TargetReturnType {
521 public Type [] ParameterTypes {
529 public class NewDelegate : Expression {
531 public ArrayList Arguments;
533 MethodBase constructor_method;
534 MethodBase delegate_method;
535 Expression delegate_instance_expr;
537 public NewDelegate (Type type, ArrayList Arguments, Location loc)
540 this.Arguments = Arguments;
544 public override Expression DoResolve (EmitContext ec)
546 if (Arguments == null) {
547 Report.Error (-11, loc,
548 "Delegate creation expression takes only one argument");
552 if (Arguments.Count != 1) {
553 Report.Error (-11, loc,
554 "Delegate creation expression takes only one argument");
558 Expression ml = Expression.MemberLookup (
559 ec, type, ".ctor", loc);
561 if (!(ml is MethodGroupExpr)) {
562 Report.Error (-100, loc, "Internal error : Could not find delegate constructor!");
566 constructor_method = ((MethodGroupExpr) ml).Methods [0];
567 Argument a = (Argument) Arguments [0];
569 if (!a.ResolveMethodGroup (ec, Location))
572 Expression e = a.Expr;
574 Expression invoke_method = Expression.MemberLookup (
575 ec, type, "Invoke", MemberTypes.Method,
576 Expression.AllBindingFlags, loc);
578 if (invoke_method == null) {
579 Report.Error (-200, loc, "Internal error ! COuld not find Invoke method!");
583 if (e is MethodGroupExpr) {
584 MethodGroupExpr mg = (MethodGroupExpr) e;
586 foreach (MethodInfo mi in mg.Methods){
587 delegate_method = Delegate.VerifyMethod (ec, type, mi, loc);
589 if (delegate_method != null)
593 if (delegate_method == null) {
595 if (mg.Methods.Length > 1)
596 method_desc = mg.Methods [0].Name;
598 method_desc = Invocation.FullMethodDesc (mg.Methods [0]);
600 MethodBase dm = ((MethodGroupExpr) invoke_method).Methods [0];
601 ParameterData param = Invocation.GetParameterData (dm);
602 string delegate_desc = Delegate.FullDelegateDesc (type, dm, param);
604 Report.Error (123, loc, "Method '" + method_desc + "' does not " +
605 "match delegate '" + delegate_desc + "'");
610 if (mg.InstanceExpression != null)
611 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
614 delegate_instance_expr = ec.This;
616 delegate_instance_expr = null;
619 if (delegate_instance_expr != null)
620 if (delegate_instance_expr.Type.IsValueType)
621 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
623 eclass = ExprClass.Value;
627 Type e_type = e.Type;
629 if (!TypeManager.IsDelegateType (e_type)) {
630 Report.Error (-12, loc, "Cannot create a delegate from something " +
631 "not a delegate or a method.");
635 // This is what MS' compiler reports. We could always choose
636 // to be more verbose and actually give delegate-level specifics
638 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
639 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
640 "to type '" + type + "'");
644 delegate_instance_expr = e;
645 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
647 eclass = ExprClass.Value;
651 public override void Emit (EmitContext ec)
653 if (delegate_instance_expr == null ||
654 delegate_method.IsStatic)
655 ec.ig.Emit (OpCodes.Ldnull);
657 delegate_instance_expr.Emit (ec);
659 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
660 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
664 public class DelegateInvocation : ExpressionStatement {
666 public Expression InstanceExpr;
667 public ArrayList Arguments;
671 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
673 this.InstanceExpr = instance_expr;
674 this.Arguments = args;
678 public override Expression DoResolve (EmitContext ec)
680 if (InstanceExpr is EventExpr) {
682 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
684 Expression ml = MemberLookup (
685 ec, ec.ContainerType, ei.Name,
686 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
690 // If this is the case, then the Event does not belong
691 // to this Type and so, according to the spec
692 // cannot be accessed directly
694 // Note that target will not appear as an EventExpr
695 // in the case it is being referenced within the same type container;
696 // it will appear as a FieldExpr in that case.
699 Assign.error70 (ei, loc);
705 Type del_type = InstanceExpr.Type;
706 if (del_type == null)
709 if (Arguments != null){
710 foreach (Argument a in Arguments){
711 if (!a.Resolve (ec, loc))
716 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
719 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
720 if (!(lookup is MethodGroupExpr)) {
721 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
725 method = ((MethodGroupExpr) lookup).Methods [0];
726 type = ((MethodInfo) method).ReturnType;
727 eclass = ExprClass.Value;
732 public override void Emit (EmitContext ec)
734 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
737 // Invocation on delegates call the virtual Invoke member
738 // so we are always `instance' calls
740 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
743 public override void EmitStatement (EmitContext ec)
747 // Pop the return value if there is one
749 if (method is MethodInfo){
750 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
751 ec.ig.Emit (OpCodes.Pop);