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 Define (TypeContainer container)
90 MethodAttributes mattr;
93 // FIXME: POSSIBLY make this static, as it is always constant
95 Type [] const_arg_types = new Type [2];
96 const_arg_types [0] = TypeManager.object_type;
97 const_arg_types [1] = TypeManager.intptr_type;
99 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
100 MethodAttributes.HideBySig | MethodAttributes.Public;
102 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
103 CallingConventions.Standard,
106 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
107 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
109 // HACK because System.Reflection.Emit is lame
112 // FIXME: POSSIBLY make these static, as they are always the same
113 Parameter [] fixed_pars = new Parameter [2];
114 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
115 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
116 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
118 TypeManager.RegisterMethod (
120 new InternalParameters (const_arg_types, const_parameters),
124 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
127 // Here the various methods like Invoke, BeginInvoke etc are defined
129 // First, call the `out of band' special method for
130 // defining recursively any types we need:
132 if (!Parameters.ComputeAndDefineParameterTypes (this))
135 param_types = Parameters.GetParameterInfo (this);
136 if (param_types == null)
143 // Check accessibility
144 foreach (Type partype in param_types)
145 if (!container.AsAccessible (partype, ModFlags)) {
146 Report.Error (59, Location,
147 "Inconsistent accessibility: parameter type `" +
148 TypeManager.CSharpName (partype) + "` is less " +
149 "accessible than delegate `" + Name + "'");
153 ReturnType = ResolveTypeExpr (ReturnType, false, Location);
154 ret_type = ReturnType.Type;
155 if (ret_type == null)
158 if (!container.AsAccessible (ret_type, ModFlags)) {
159 Report.Error (58, Location,
160 "Inconsistent accessibility: return type `" +
161 TypeManager.CSharpName (ret_type) + "` is less " +
162 "accessible than delegate `" + Name + "'");
167 // We don't have to check any others because they are all
168 // guaranteed to be accessible - they are standard types.
171 CallingConventions cc = Parameters.GetCallingConvention ();
173 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
175 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
182 if (Parameters.FixedParameters != null){
183 int top = Parameters.FixedParameters.Length;
186 for (; i < top; i++) {
187 p = Parameters.FixedParameters [i];
189 InvokeBuilder.DefineParameter (
190 i+1, p.Attributes, p.Name);
193 if (Parameters.ArrayParameter != null){
194 Parameter p = Parameters.ArrayParameter;
196 InvokeBuilder.DefineParameter (
197 i+1, p.Attributes, p.Name);
200 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
202 TypeManager.RegisterMethod (InvokeBuilder,
203 new InternalParameters (container, Parameters),
209 int params_num = param_types.Length;
210 Type [] async_param_types = new Type [params_num + 2];
212 param_types.CopyTo (async_param_types, 0);
214 async_param_types [params_num] = TypeManager.asynccallback_type;
215 async_param_types [params_num + 1] = TypeManager.object_type;
217 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
218 MethodAttributes.Virtual | MethodAttributes.NewSlot;
220 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
223 TypeManager.iasyncresult_type,
227 if (Parameters.FixedParameters != null){
228 int top = Parameters.FixedParameters.Length;
231 for (i = 0 ; i < top; i++) {
232 p = Parameters.FixedParameters [i];
234 BeginInvokeBuilder.DefineParameter (
235 i+1, p.Attributes, p.Name);
238 if (Parameters.ArrayParameter != null){
239 Parameter p = Parameters.ArrayParameter;
241 BeginInvokeBuilder.DefineParameter (
242 i+1, p.Attributes, p.Name);
246 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
247 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
249 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
251 Parameter [] async_params = new Parameter [params_num + 2];
253 if (Parameters.FixedParameters != null){
254 Parameters.FixedParameters.CopyTo (async_params, 0);
255 n = Parameters.FixedParameters.Length;
257 if (Parameters.ArrayParameter != null)
258 async_params [n] = Parameters.ArrayParameter;
260 async_params [params_num] = new Parameter (
261 TypeManager.system_asynccallback_expr, "callback",
262 Parameter.Modifier.NONE, null);
263 async_params [params_num + 1] = new Parameter (
264 TypeManager.system_object_expr, "object",
265 Parameter.Modifier.NONE, null);
267 Parameters async_parameters = new Parameters (async_params, null, Location);
269 async_parameters.ComputeAndDefineParameterTypes (this);
270 TypeManager.RegisterMethod (BeginInvokeBuilder,
271 new InternalParameters (container, async_parameters),
277 Type [] end_param_types = new Type [1];
278 end_param_types [0] = TypeManager.iasyncresult_type;
280 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
285 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
287 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
289 Parameter [] end_params = new Parameter [1];
290 end_params [0] = new Parameter (
291 TypeManager.system_iasyncresult_expr, "result",
292 Parameter.Modifier.NONE, null);
294 TypeManager.RegisterMethod (
295 EndInvokeBuilder, new InternalParameters (
298 end_params, null, Location)),
305 /// Verifies whether the method in question is compatible with the delegate
306 /// Returns the method itself if okay and null if not.
308 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
311 ParameterData pd = Invocation.GetParameterData (mb);
313 int pd_count = pd.Count;
315 Expression ml = Expression.MemberLookup (
316 ec, delegate_type, "Invoke", loc);
318 if (!(ml is MethodGroupExpr)) {
319 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
323 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
325 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
327 if (invoke_pd.Count != pd_count)
330 for (int i = pd_count; i > 0; ) {
333 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
339 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
346 // Verifies whether the invocation arguments are compatible with the
347 // delegate's target method
349 public static bool VerifyApplicability (EmitContext ec,
359 arg_count = args.Count;
361 Expression ml = Expression.MemberLookup (
362 ec, delegate_type, "Invoke", loc);
364 if (!(ml is MethodGroupExpr)) {
365 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
369 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
370 ParameterData pd = Invocation.GetParameterData (mb);
372 int pd_count = pd.Count;
374 bool not_params_method = (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
376 if (not_params_method && pd_count != arg_count) {
377 Report.Error (1593, loc,
378 "Delegate '" + delegate_type.ToString ()
379 + "' does not take '" + arg_count + "' arguments");
383 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
388 /// Verifies whether the delegate in question is compatible with this one in
389 /// order to determine if instantiation from the same is possible.
391 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
393 Expression ml = Expression.MemberLookup (
394 ec, delegate_type, "Invoke", loc);
396 if (!(ml is MethodGroupExpr)) {
397 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
401 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
402 ParameterData pd = Invocation.GetParameterData (mb);
404 Expression probe_ml = Expression.MemberLookup (
405 ec, delegate_type, "Invoke", loc);
407 if (!(probe_ml is MethodGroupExpr)) {
408 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
412 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
413 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
415 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
418 if (pd.Count != probe_pd.Count)
421 for (int i = pd.Count; i > 0; ) {
424 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
425 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
432 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
434 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
436 sb.Append (" " + del_type.ToString ());
439 int length = pd.Count;
441 for (int i = length; i > 0; ) {
444 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
450 return sb.ToString ();
454 // Hack around System.Reflection as found everywhere else
455 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
457 ArrayList members = new ArrayList ();
459 if ((mt & MemberTypes.Method) != 0) {
460 if (ConstructorBuilder != null)
461 if (filter (ConstructorBuilder, criteria))
462 members.Add (ConstructorBuilder);
464 if (InvokeBuilder != null)
465 if (filter (InvokeBuilder, criteria))
466 members.Add (InvokeBuilder);
468 if (BeginInvokeBuilder != null)
469 if (filter (BeginInvokeBuilder, criteria))
470 members.Add (BeginInvokeBuilder);
472 if (EndInvokeBuilder != null)
473 if (filter (EndInvokeBuilder, criteria))
474 members.Add (EndInvokeBuilder);
477 int count = members.Count;
480 MemberInfo [] mi = new MemberInfo [count];
481 members.CopyTo (mi, 0);
488 public void CloseDelegate ()
490 TypeBuilder.CreateType ();
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.Resolve (ec, loc))
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 + "'");
606 if (mg.InstanceExpression != null)
607 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
610 delegate_instance_expr = ec.This;
612 delegate_instance_expr = null;
615 if (delegate_instance_expr != null)
616 if (delegate_instance_expr.Type.IsValueType)
617 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
619 eclass = ExprClass.Value;
623 Type e_type = e.Type;
625 if (!TypeManager.IsDelegateType (e_type)) {
626 Report.Error (-12, loc, "Cannot create a delegate from something " +
627 "not a delegate or a method.");
631 // This is what MS' compiler reports. We could always choose
632 // to be more verbose and actually give delegate-level specifics
634 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
635 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
636 "to type '" + type + "'");
640 delegate_instance_expr = e;
641 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
643 eclass = ExprClass.Value;
647 public override void Emit (EmitContext ec)
649 if (delegate_instance_expr == null ||
650 delegate_method.IsStatic)
651 ec.ig.Emit (OpCodes.Ldnull);
653 delegate_instance_expr.Emit (ec);
655 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
656 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
660 public class DelegateInvocation : ExpressionStatement {
662 public Expression InstanceExpr;
663 public ArrayList Arguments;
667 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
669 this.InstanceExpr = instance_expr;
670 this.Arguments = args;
674 public override Expression DoResolve (EmitContext ec)
676 Type del_type = InstanceExpr.Type;
677 if (del_type == null)
680 if (Arguments != null){
681 foreach (Argument a in Arguments){
682 if (!a.Resolve (ec, loc))
687 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
690 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", loc);
691 if (!(ml is MethodGroupExpr)) {
692 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
696 method = ((MethodGroupExpr) ml).Methods [0];
697 type = ((MethodInfo) method).ReturnType;
698 eclass = ExprClass.Value;
703 public override void Emit (EmitContext ec)
705 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
708 // Invocation on delegates call the virtual Invoke member
709 // so we are always `instance' calls
711 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
714 public override void EmitStatement (EmitContext ec)
718 // Pop the return value if there is one
720 if (method is MethodInfo){
721 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
722 ec.ig.Emit (OpCodes.Pop);