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 {
\r
25 public readonly string Name;
\r
26 public readonly string ReturnType;
\r
27 public int mod_flags;
\r
28 public Parameters Parameters;
\r
29 public Attributes OptAttributes;
\r
30 public TypeBuilder TypeBuilder;
\r
32 public ConstructorBuilder ConstructorBuilder;
\r
33 public MethodBuilder InvokeBuilder;
\r
34 public MethodBuilder BeginInvokeBuilder;
\r
35 public MethodBuilder EndInvokeBuilder;
\r
37 Type [] param_types;
\r
40 Expression instance_expr;
\r
41 MethodBase delegate_method;
\r
45 const int AllowedModifiers =
\r
48 Modifiers.PROTECTED |
\r
49 Modifiers.INTERNAL |
\r
52 public Delegate (string type, int mod_flags, string name, Parameters param_list,
\r
53 Attributes attrs, Location loc)
\r
56 this.ReturnType = type;
\r
57 this.mod_flags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);
\r
58 Parameters = param_list;
\r
59 OptAttributes = attrs;
\r
63 public void DefineDelegate (object parent_builder)
\r
65 TypeAttributes attr;
\r
67 if (parent_builder is ModuleBuilder) {
\r
68 ModuleBuilder builder = (ModuleBuilder) parent_builder;
\r
69 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
\r
71 TypeBuilder = builder.DefineType (Name, attr, TypeManager.delegate_type);
\r
73 TypeBuilder builder = (TypeBuilder) parent_builder;
\r
74 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
\r
75 TypeAttributes.Sealed;
\r
77 TypeBuilder = builder.DefineNestedType (
\r
78 Name, attr, TypeManager.delegate_type);
\r
81 RootContext.TypeManager.AddDelegateType (Name, TypeBuilder, this);
\r
84 public bool Populate (TypeContainer parent)
\r
87 MethodAttributes mattr;
\r
90 // FIXME: POSSIBLY make this static, as it is always constant
\r
92 Type [] const_arg_types = new Type [2];
\r
93 const_arg_types [0] = TypeManager.object_type;
\r
94 const_arg_types [1] = TypeManager.intptr_type;
\r
96 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
\r
97 MethodAttributes.HideBySig | MethodAttributes.Public;
\r
99 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
\r
100 CallingConventions.Standard,
\r
104 // HACK because System.Reflection.Emit is lame
\r
107 // FIXME: POSSIBLY make these static, as they are always the same
\r
108 Parameter [] fixed_pars = new Parameter [2];
\r
109 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
110 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
111 Parameters const_parameters = new Parameters (fixed_pars, null);
\r
113 TypeManager.RegisterMethod (
\r
114 ConstructorBuilder,
\r
115 new InternalParameters (const_arg_types, const_parameters),
\r
119 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
121 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
124 // TODO: Call AsAccessible for each type
\r
130 param_types = Parameters.GetParameterInfo (parent);
\r
131 if (param_types == null)
\r
134 ret_type = parent.LookupType (ReturnType, false);
\r
135 if (ret_type == null)
\r
138 CallingConventions cc = Parameters.GetCallingConvention ();
\r
140 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
142 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
148 for (i = 0 ; i < param_types.Length; i++) {
\r
149 Parameter p = Parameters.FixedParameters [i];
\r
150 string name = p.Name;
\r
151 ParameterBuilder pb = InvokeBuilder.DefineParameter (i+1, p.Attributes, name);
\r
154 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
156 TypeManager.RegisterMethod (InvokeBuilder,
\r
157 new InternalParameters (parent, Parameters),
\r
163 int params_num = param_types.Length;
\r
164 Type [] async_param_types = new Type [params_num + 2];
\r
166 param_types.CopyTo (async_param_types, 0);
\r
168 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
169 async_param_types [params_num + 1] = TypeManager.object_type;
\r
171 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |
\r
172 MethodAttributes.NewSlot;
\r
174 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
177 TypeManager.iasyncresult_type,
\r
178 async_param_types);
\r
180 for (i = 0 ; i < param_types.Length; i++) {
\r
181 Parameter p = Parameters.FixedParameters [i];
\r
182 string name = p.Name;
\r
183 BeginInvokeBuilder.DefineParameter (i + 1, p.Attributes, name);
\r
186 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
187 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
189 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
191 Parameter [] async_params = new Parameter [params_num + 2];
\r
192 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
194 async_params [params_num] = new Parameter ("System.AsyncCallback", "callback",
\r
195 Parameter.Modifier.NONE, null);
\r
196 async_params [params_num + 1] = new Parameter ("System.IAsyncResult", "object",
\r
197 Parameter.Modifier.NONE, null);
\r
199 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
200 new InternalParameters (
\r
202 new Parameters (async_params, null)),
\r
203 async_param_types);
\r
208 Type [] end_param_types = new Type [1];
\r
209 end_param_types [0] = TypeManager.iasyncresult_type;
\r
211 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
216 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
218 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
220 Parameter [] end_params = new Parameter [1];
\r
221 end_params [0] = new Parameter ("System.IAsyncResult", "result",
\r
222 Parameter.Modifier.NONE, null);
\r
224 TypeManager.RegisterMethod (EndInvokeBuilder,
\r
225 new InternalParameters (
\r
226 parent, new Parameters (end_params, null)),
\r
233 /// Verifies whether the method in question is compatible with the delegate
\r
234 /// Returns the method itself if okay and null if not.
\r
236 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb, Location loc)
\r
238 ParameterData pd = Invocation.GetParameterData (mb);
\r
240 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
242 if (!(ml is MethodGroupExpr)) {
\r
243 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
247 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
249 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
251 bool mismatch = false;
\r
252 for (int i = pd.Count; i > 0; ) {
\r
255 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
264 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +
\r
265 "delegate '" + FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
269 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
275 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) + "' does not match " +
\r
276 "delegate '" + FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
284 // Verifies whether the invocation arguments are compatible with the
\r
285 // delegate's target method
\r
287 public static bool VerifyApplicability (EmitContext ec, Type delegate_type, ArrayList args, Location loc)
\r
294 arg_count = args.Count;
\r
296 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
298 if (!(ml is MethodGroupExpr)) {
\r
299 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
303 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
305 ParameterData pd = Invocation.GetParameterData (mb);
\r
307 if (pd.Count != arg_count) {
\r
308 Report.Error (1593, loc,
\r
309 "Delegate '" + delegate_type.ToString ()
\r
310 + "' does not take '" + arg_count + "' arguments");
\r
314 for (int i = arg_count; i > 0;) {
\r
317 Argument a = (Argument) args [i];
\r
318 Expression a_expr = a.Expr;
\r
320 if (pd.ParameterType (i) != a_expr.Type) {
\r
322 conv = Expression.ConvertImplicitStandard (ec, a_expr, pd.ParameterType (i), loc);
\r
324 if (conv == null) {
\r
325 Report.Error (1594, loc,
\r
326 "Delegate '" + delegate_type.ToString () +
\r
327 "' has some invalid arguments.");
\r
329 Report.Error (1503, loc,
\r
330 "Argument " + (i+1) +
\r
331 ": Cannot convert from '" +
\r
332 TypeManager.CSharpName (a_expr.Type)
\r
333 + "' to '" + TypeManager.CSharpName (pd.ParameterType (i)) + "'");
\r
337 if (a_expr != conv)
\r
346 /// Verifies whether the delegate in question is compatible with this one in
\r
347 /// order to determine if instantiation from the same is possible.
\r
349 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
351 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
353 if (!(ml is MethodGroupExpr)) {
\r
354 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
358 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
359 ParameterData pd = Invocation.GetParameterData (mb);
\r
361 Expression probe_ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
363 if (!(probe_ml is MethodGroupExpr)) {
\r
364 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
368 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
369 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
371 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
374 if (pd.Count != probe_pd.Count)
\r
377 for (int i = pd.Count; i > 0; ) {
\r
380 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
381 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
388 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
390 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
392 sb.Append (" " + del_type.ToString ());
\r
395 int length = pd.Count;
\r
397 for (int i = length; i > 0; ) {
\r
400 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
406 return sb.ToString ();
\r
410 // Hack around System.Reflection as found everywhere else
\r
411 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
413 ArrayList members = new ArrayList ();
\r
415 if ((mt & MemberTypes.Method) != 0) {
\r
416 if (filter (ConstructorBuilder, criteria))
\r
417 members.Add (ConstructorBuilder);
\r
419 if (filter (InvokeBuilder, criteria))
\r
420 members.Add (InvokeBuilder);
\r
422 if (filter (BeginInvokeBuilder, criteria))
\r
423 members.Add (BeginInvokeBuilder);
\r
425 if (filter (EndInvokeBuilder, criteria))
\r
426 members.Add (EndInvokeBuilder);
\r
429 int count = members.Count;
\r
432 MemberInfo [] mi = new MemberInfo [count];
\r
433 members.CopyTo (mi, 0);
\r
440 public void CloseDelegate ()
\r
442 TypeBuilder.CreateType ();
\r
445 public int ModFlags {
\r
451 public Expression InstanceExpression {
\r
453 return instance_expr;
\r
456 instance_expr = value;
\r
460 public MethodBase TargetMethod {
\r
462 return delegate_method;
\r
465 delegate_method = value;
\r
469 public Type TargetReturnType {
\r
475 public Type [] ParameterTypes {
\r
477 return param_types;
\r
483 public class NewDelegate : Expression {
\r
485 public ArrayList Arguments;
\r
487 MethodBase constructor_method;
\r
488 MethodBase delegate_method;
\r
489 Expression delegate_instance_expr;
\r
493 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
496 this.Arguments = Arguments;
\r
497 this.Location = loc;
\r
500 public override Expression DoResolve (EmitContext ec)
\r
502 if (Arguments == null) {
\r
503 Report.Error (-11, Location,
\r
504 "Delegate creation expression takes only one argument");
\r
508 if (Arguments.Count != 1) {
\r
509 Report.Error (-11, Location,
\r
510 "Delegate creation expression takes only one argument");
\r
514 Expression ml = Expression.MemberLookup (ec, type, ".ctor", false, Location);
\r
516 if (!(ml is MethodGroupExpr)) {
\r
517 Report.Error (-100, Location, "Internal error : Could not find delegate constructor!");
\r
521 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
523 Argument a = (Argument) Arguments [0];
\r
525 if (!a.Resolve (ec, Location))
\r
528 Expression e = a.Expr;
\r
530 if (e is MethodGroupExpr) {
\r
531 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
533 delegate_method = Delegate.VerifyMethod (ec, type, mg.Methods [0], Location);
\r
535 if (delegate_method == null)
\r
538 if (mg.InstanceExpression != null)
\r
539 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
541 delegate_instance_expr = null;
\r
543 if (delegate_instance_expr != null)
\r
544 if (delegate_instance_expr.Type.IsValueType)
\r
545 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
547 DictionaryEntry de = new DictionaryEntry (delegate_method, delegate_instance_expr);
\r
548 TypeManager.RegisterDelegateData (type, de);
\r
550 eclass = ExprClass.Value;
\r
554 Type e_type = e.Type;
\r
556 if (!TypeManager.IsDelegateType (e_type)) {
\r
557 Report.Error (-12, Location, "Cannot create a delegate from something " +
\r
558 "not a delegate or a method.");
\r
562 // This is what MS' compiler reports. We could always choose
\r
563 // to be more verbose and actually give delegate-level specifics
\r
565 if (!Delegate.VerifyDelegate (ec, type, e_type, Location)) {
\r
566 Report.Error (29, Location, "Cannot implicitly convert type '" + e_type + "' " +
\r
567 "to type '" + type + "'");
\r
571 DictionaryEntry d = TypeManager.GetDelegateData (e_type);
\r
573 delegate_instance_expr = (Expression) d.Value;
\r
574 delegate_method = (MethodBase) d.Key;
\r
576 eclass = ExprClass.Value;
\r
580 public override void Emit (EmitContext ec)
\r
582 if (delegate_instance_expr == null)
\r
583 ec.ig.Emit (OpCodes.Ldnull);
\r
585 delegate_instance_expr.Emit (ec);
\r
587 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
588 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
592 public class DelegateInvocation : ExpressionStatement {
\r
594 public Expression InstanceExpr;
\r
595 public ArrayList Arguments;
\r
596 public Location Location;
\r
600 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
602 this.InstanceExpr = instance_expr;
\r
603 this.Arguments = args;
\r
604 this.Location = loc;
\r
607 public override Expression DoResolve (EmitContext ec)
\r
609 Type del_type = InstanceExpr.Type;
\r
611 if (Arguments != null){
\r
612 for (int i = Arguments.Count; i > 0;){
\r
614 Argument a = (Argument) Arguments [i];
\r
616 if (!a.Resolve (ec, Location))
\r
621 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, Location))
\r
624 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", false, Location);
\r
626 if (!(ml is MethodGroupExpr)) {
\r
627 Report.Error (-100, Location, "Internal error : could not find Invoke method!");
\r
631 method = ((MethodGroupExpr) ml).Methods [0];
\r
633 type = ((MethodInfo) method).ReturnType;
\r
635 eclass = ExprClass.Value;
\r
640 public override void Emit (EmitContext ec)
\r
642 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
645 // Invocation on delegates call the virtual Invoke member
\r
646 // so we are always `instance' calls
\r
648 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments);
\r
651 public override void EmitStatement (EmitContext ec)
\r
655 // Pop the return value if there is one
\r
657 if (method is MethodInfo){
\r
658 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
659 ec.ig.Emit (OpCodes.Pop);
\r