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, IMemberFinder {
\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 Define (TypeContainer container)
\r
90 MethodAttributes mattr;
\r
93 // FIXME: POSSIBLY make this static, as it is always constant
\r
95 Type [] const_arg_types = new Type [2];
\r
96 const_arg_types [0] = TypeManager.object_type;
\r
97 const_arg_types [1] = TypeManager.intptr_type;
\r
99 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
\r
100 MethodAttributes.HideBySig | MethodAttributes.Public;
\r
102 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
\r
103 CallingConventions.Standard,
\r
106 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
\r
107 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
\r
109 // HACK because System.Reflection.Emit is lame
\r
112 // FIXME: POSSIBLY make these static, as they are always the same
\r
113 Parameter [] fixed_pars = new Parameter [2];
\r
114 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
115 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
116 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
\r
118 TypeManager.RegisterMethod (
\r
119 ConstructorBuilder,
\r
120 new InternalParameters (const_arg_types, const_parameters),
\r
124 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
127 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
129 // First, call the `out of band' special method for
\r
130 // defining recursively any types we need:
\r
132 if (!Parameters.ComputeAndDefineParameterTypes (this))
\r
135 param_types = Parameters.GetParameterInfo (this);
\r
136 if (param_types == null)
\r
143 // Check accessibility
\r
144 foreach (Type partype in param_types)
\r
145 if (!container.AsAccessible (partype, ModFlags)) {
\r
146 Report.Error (59, Location,
\r
147 "Inconsistent accessibility: parameter type `" +
\r
148 TypeManager.CSharpName (partype) + "` is less " +
\r
149 "accessible than delegate `" + Name + "'");
\r
153 ReturnType = ResolveTypeExpr (ReturnType, false, Location);
\r
154 ret_type = ReturnType.Type;
\r
155 if (ret_type == null)
\r
158 if (!container.AsAccessible (ret_type, ModFlags)) {
\r
159 Report.Error (58, Location,
\r
160 "Inconsistent accessibility: return type `" +
\r
161 TypeManager.CSharpName (ret_type) + "` is less " +
\r
162 "accessible than delegate `" + Name + "'");
\r
167 // We don't have to check any others because they are all
\r
168 // guaranteed to be accessible - they are standard types.
\r
171 CallingConventions cc = Parameters.GetCallingConvention ();
\r
173 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
175 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
182 if (Parameters.FixedParameters != null){
\r
183 int top = Parameters.FixedParameters.Length;
\r
186 for (; i < top; i++) {
\r
187 p = Parameters.FixedParameters [i];
\r
189 InvokeBuilder.DefineParameter (
\r
190 i+1, p.Attributes, p.Name);
\r
193 if (Parameters.ArrayParameter != null){
\r
194 Parameter p = Parameters.ArrayParameter;
\r
196 InvokeBuilder.DefineParameter (
\r
197 i+1, p.Attributes, p.Name);
\r
200 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
202 TypeManager.RegisterMethod (InvokeBuilder,
\r
203 new InternalParameters (container, Parameters),
\r
209 int params_num = param_types.Length;
\r
210 Type [] async_param_types = new Type [params_num + 2];
\r
212 param_types.CopyTo (async_param_types, 0);
\r
214 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
215 async_param_types [params_num + 1] = TypeManager.object_type;
\r
217 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
\r
218 MethodAttributes.Virtual | MethodAttributes.NewSlot;
\r
220 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
223 TypeManager.iasyncresult_type,
\r
224 async_param_types);
\r
227 if (Parameters.FixedParameters != null){
\r
228 int top = Parameters.FixedParameters.Length;
\r
231 for (i = 0 ; i < top; i++) {
\r
232 p = Parameters.FixedParameters [i];
\r
234 BeginInvokeBuilder.DefineParameter (
\r
235 i+1, p.Attributes, p.Name);
\r
238 if (Parameters.ArrayParameter != null){
\r
239 Parameter p = Parameters.ArrayParameter;
\r
241 BeginInvokeBuilder.DefineParameter (
\r
242 i+1, p.Attributes, p.Name);
\r
246 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
247 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
249 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
251 Parameter [] async_params = new Parameter [params_num + 2];
\r
253 if (Parameters.FixedParameters != null){
\r
254 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
255 n = Parameters.FixedParameters.Length;
\r
257 if (Parameters.ArrayParameter != null)
\r
258 async_params [n] = Parameters.ArrayParameter;
\r
260 async_params [params_num] = new Parameter (
\r
261 TypeManager.system_asynccallback_expr, "callback",
\r
262 Parameter.Modifier.NONE, null);
\r
263 async_params [params_num + 1] = new Parameter (
\r
264 TypeManager.system_object_expr, "object",
\r
265 Parameter.Modifier.NONE, null);
\r
267 Parameters async_parameters = new Parameters (async_params, null, Location);
\r
269 async_parameters.ComputeAndDefineParameterTypes (this);
\r
270 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
271 new InternalParameters (container, async_parameters),
\r
272 async_param_types);
\r
277 Type [] end_param_types = new Type [1];
\r
278 end_param_types [0] = TypeManager.iasyncresult_type;
\r
280 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
285 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
287 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
289 Parameter [] end_params = new Parameter [1];
\r
290 end_params [0] = new Parameter (
\r
291 TypeManager.system_iasyncresult_expr, "result",
\r
292 Parameter.Modifier.NONE, null);
\r
294 TypeManager.RegisterMethod (
\r
295 EndInvokeBuilder, new InternalParameters (
\r
298 end_params, null, Location)),
\r
305 /// Verifies whether the method in question is compatible with the delegate
\r
306 /// Returns the method itself if okay and null if not.
\r
308 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
\r
311 ParameterData pd = Invocation.GetParameterData (mb);
\r
313 int pd_count = pd.Count;
\r
315 Expression ml = Expression.MemberLookup (
\r
316 ec, delegate_type, "Invoke", loc);
\r
318 if (!(ml is MethodGroupExpr)) {
\r
319 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
323 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
325 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
327 if (invoke_pd.Count != pd_count)
\r
330 for (int i = pd_count; i > 0; ) {
\r
333 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
339 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
346 // Verifies whether the invocation arguments are compatible with the
\r
347 // delegate's target method
\r
349 public static bool VerifyApplicability (EmitContext ec,
\r
350 Type delegate_type,
\r
359 arg_count = args.Count;
\r
361 Expression ml = Expression.MemberLookup (
\r
362 ec, delegate_type, "Invoke", loc);
\r
364 if (!(ml is MethodGroupExpr)) {
\r
365 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
369 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
370 ParameterData pd = Invocation.GetParameterData (mb);
\r
372 int pd_count = pd.Count;
\r
374 bool not_params_method = (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
\r
376 if (not_params_method && pd_count != arg_count) {
\r
377 Report.Error (1593, loc,
\r
378 "Delegate '" + delegate_type.ToString ()
\r
379 + "' does not take '" + arg_count + "' arguments");
\r
383 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
\r
384 delegate_type, loc);
\r
388 /// Verifies whether the delegate in question is compatible with this one in
\r
389 /// order to determine if instantiation from the same is possible.
\r
391 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
393 Expression ml = Expression.MemberLookup (
\r
394 ec, delegate_type, "Invoke", loc);
\r
396 if (!(ml is MethodGroupExpr)) {
\r
397 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
401 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
402 ParameterData pd = Invocation.GetParameterData (mb);
\r
404 Expression probe_ml = Expression.MemberLookup (
\r
405 ec, delegate_type, "Invoke", loc);
\r
407 if (!(probe_ml is MethodGroupExpr)) {
\r
408 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
412 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
413 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
415 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
418 if (pd.Count != probe_pd.Count)
\r
421 for (int i = pd.Count; i > 0; ) {
\r
424 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
425 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
432 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
434 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
436 sb.Append (" " + del_type.ToString ());
\r
439 int length = pd.Count;
\r
441 for (int i = length; i > 0; ) {
\r
444 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
450 return sb.ToString ();
\r
454 // Hack around System.Reflection as found everywhere else
\r
455 public MemberList FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
457 ArrayList members = new ArrayList ();
\r
459 if ((mt & MemberTypes.Method) != 0) {
\r
460 if (ConstructorBuilder != null)
\r
461 if (filter (ConstructorBuilder, criteria))
\r
462 members.Add (ConstructorBuilder);
\r
464 if (InvokeBuilder != null)
\r
465 if (filter (InvokeBuilder, criteria))
\r
466 members.Add (InvokeBuilder);
\r
468 if (BeginInvokeBuilder != null)
\r
469 if (filter (BeginInvokeBuilder, criteria))
\r
470 members.Add (BeginInvokeBuilder);
\r
472 if (EndInvokeBuilder != null)
\r
473 if (filter (EndInvokeBuilder, criteria))
\r
474 members.Add (EndInvokeBuilder);
\r
477 return new MemberList (members);
\r
480 public void CloseDelegate ()
\r
482 TypeBuilder.CreateType ();
\r
485 public Expression InstanceExpression {
\r
487 return instance_expr;
\r
490 instance_expr = value;
\r
494 public MethodBase TargetMethod {
\r
496 return delegate_method;
\r
499 delegate_method = value;
\r
503 public Type TargetReturnType {
\r
509 public Type [] ParameterTypes {
\r
511 return param_types;
\r
517 public class NewDelegate : Expression {
\r
519 public ArrayList Arguments;
\r
521 MethodBase constructor_method;
\r
522 MethodBase delegate_method;
\r
523 Expression delegate_instance_expr;
\r
525 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
528 this.Arguments = Arguments;
\r
532 public override Expression DoResolve (EmitContext ec)
\r
534 if (Arguments == null) {
\r
535 Report.Error (-11, loc,
\r
536 "Delegate creation expression takes only one argument");
\r
540 if (Arguments.Count != 1) {
\r
541 Report.Error (-11, loc,
\r
542 "Delegate creation expression takes only one argument");
\r
546 Expression ml = Expression.MemberLookup (
\r
547 ec, type, ".ctor", loc);
\r
549 if (!(ml is MethodGroupExpr)) {
\r
550 Report.Error (-100, loc, "Internal error : Could not find delegate constructor!");
\r
554 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
555 Argument a = (Argument) Arguments [0];
\r
557 if (!a.ResolveMethodGroup (ec, Location))
\r
560 Expression e = a.Expr;
\r
562 Expression invoke_method = Expression.MemberLookup (
\r
563 ec, type, "Invoke", MemberTypes.Method,
\r
564 Expression.AllBindingFlags, loc);
\r
566 if (invoke_method == null) {
\r
567 Report.Error (-200, loc, "Internal error ! COuld not find Invoke method!");
\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, loc);
\r
577 if (delegate_method != null)
\r
581 if (delegate_method == null) {
\r
582 string method_desc;
\r
583 if (mg.Methods.Length > 1)
\r
584 method_desc = mg.Methods [0].Name;
\r
586 method_desc = Invocation.FullMethodDesc (mg.Methods [0]);
\r
588 MethodBase dm = ((MethodGroupExpr) invoke_method).Methods [0];
\r
589 ParameterData param = Invocation.GetParameterData (dm);
\r
590 string delegate_desc = Delegate.FullDelegateDesc (type, dm, param);
\r
592 Report.Error (123, loc, "Method '" + method_desc + "' does not " +
\r
593 "match delegate '" + delegate_desc + "'");
\r
598 if (mg.InstanceExpression != null)
\r
599 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
602 delegate_instance_expr = ec.This;
\r
604 delegate_instance_expr = null;
\r
607 if (delegate_instance_expr != null)
\r
608 if (delegate_instance_expr.Type.IsValueType)
\r
609 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
611 eclass = ExprClass.Value;
\r
615 Type e_type = e.Type;
\r
617 if (!TypeManager.IsDelegateType (e_type)) {
\r
618 Report.Error (-12, loc, "Cannot create a delegate from something " +
\r
619 "not a delegate or a method.");
\r
623 // This is what MS' compiler reports. We could always choose
\r
624 // to be more verbose and actually give delegate-level specifics
\r
626 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
\r
627 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
\r
628 "to type '" + type + "'");
\r
632 delegate_instance_expr = e;
\r
633 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
\r
635 eclass = ExprClass.Value;
\r
639 public override void Emit (EmitContext ec)
\r
641 if (delegate_instance_expr == null ||
\r
642 delegate_method.IsStatic)
\r
643 ec.ig.Emit (OpCodes.Ldnull);
\r
645 delegate_instance_expr.Emit (ec);
\r
647 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
648 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
652 public class DelegateInvocation : ExpressionStatement {
\r
654 public Expression InstanceExpr;
\r
655 public ArrayList Arguments;
\r
659 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
661 this.InstanceExpr = instance_expr;
\r
662 this.Arguments = args;
\r
666 public override Expression DoResolve (EmitContext ec)
\r
668 Type del_type = InstanceExpr.Type;
\r
669 if (del_type == null)
\r
672 if (Arguments != null){
\r
673 foreach (Argument a in Arguments){
\r
674 if (!a.Resolve (ec, loc))
\r
679 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
\r
682 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", loc);
\r
683 if (!(ml is MethodGroupExpr)) {
\r
684 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
688 method = ((MethodGroupExpr) ml).Methods [0];
\r
689 type = ((MethodInfo) method).ReturnType;
\r
690 eclass = ExprClass.Value;
\r
695 public override void Emit (EmitContext ec)
\r
697 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
700 // Invocation on delegates call the virtual Invoke member
\r
701 // so we are always `instance' calls
\r
703 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
\r
706 public override void EmitStatement (EmitContext ec)
\r
710 // Pop the return value if there is one
\r
712 if (method is MethodInfo){
\r
713 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
714 ec.ig.Emit (OpCodes.Pop);
\r