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 : MemberCore {
\r
24 public readonly string ReturnType;
\r
25 public Parameters Parameters;
\r
26 public Attributes OptAttributes;
\r
27 public TypeBuilder TypeBuilder;
\r
29 public ConstructorBuilder ConstructorBuilder;
\r
30 public MethodBuilder InvokeBuilder;
\r
31 public MethodBuilder BeginInvokeBuilder;
\r
32 public MethodBuilder EndInvokeBuilder;
\r
34 Type [] param_types;
\r
37 Expression instance_expr;
\r
38 MethodBase delegate_method;
\r
40 const int AllowedModifiers =
\r
43 Modifiers.PROTECTED |
\r
44 Modifiers.INTERNAL |
\r
47 public Delegate (string type, int mod_flags, string name, Parameters param_list,
\r
48 Attributes attrs, Location l)
\r
51 this.ReturnType = type;
\r
52 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags, Modifiers.PUBLIC);
\r
53 Parameters = param_list;
\r
54 OptAttributes = attrs;
\r
57 public void DefineDelegate (object parent_builder)
\r
59 TypeAttributes attr;
\r
60 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
\r
62 if (parent_builder is ModuleBuilder) {
\r
63 ModuleBuilder builder = (ModuleBuilder) parent_builder;
\r
64 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
\r
66 TypeBuilder = builder.DefineType (
\r
67 name, attr, TypeManager.multicast_delegate_type);
\r
69 // FIXME: We could just use TypeBuilder here.
\r
70 TypeBuilder builder = (System.Reflection.Emit.TypeBuilder) parent_builder;
\r
71 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
\r
72 TypeAttributes.Sealed;
\r
74 TypeBuilder = builder.DefineNestedType (
\r
75 name, attr, TypeManager.multicast_delegate_type);
\r
78 RootContext.TypeManager.AddDelegateType (Name, TypeBuilder, this);
\r
81 public override bool Define (TypeContainer parent)
\r
83 MethodAttributes mattr;
\r
86 // FIXME: POSSIBLY make this static, as it is always constant
\r
88 Type [] const_arg_types = new Type [2];
\r
89 const_arg_types [0] = TypeManager.object_type;
\r
90 const_arg_types [1] = TypeManager.intptr_type;
\r
92 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
\r
93 MethodAttributes.HideBySig | MethodAttributes.Public;
\r
95 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
\r
96 CallingConventions.Standard,
\r
100 // HACK because System.Reflection.Emit is lame
\r
103 // FIXME: POSSIBLY make these static, as they are always the same
\r
104 Parameter [] fixed_pars = new Parameter [2];
\r
105 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
106 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
\r
107 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
\r
109 TypeManager.RegisterMethod (
\r
110 ConstructorBuilder,
\r
111 new InternalParameters (const_arg_types, const_parameters),
\r
115 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
117 // Here the various methods like Invoke, BeginInvoke etc are defined
\r
122 param_types = Parameters.GetParameterInfo (parent);
\r
123 if (param_types == null)
\r
126 // Check accessibility
\r
127 foreach (Type partype in param_types)
\r
128 if (!TypeContainer.AsAccessible (partype, ModFlags))
\r
131 ret_type = RootContext.LookupType (parent, ReturnType, false, Location);
\r
132 if (ret_type == null)
\r
135 if (!TypeContainer.AsAccessible (ret_type, ModFlags))
\r
139 // We don't have to check any others because they are all
\r
140 // guaranteed to be accessible - they are standard types.
\r
143 CallingConventions cc = Parameters.GetCallingConvention ();
\r
145 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
\r
147 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
\r
153 for (i = 0 ; i < param_types.Length; i++) {
\r
154 Parameter p = Parameters.FixedParameters [i];
\r
155 string name = p.Name;
\r
156 ParameterBuilder pb = InvokeBuilder.DefineParameter (i+1, p.Attributes, name);
\r
159 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
161 TypeManager.RegisterMethod (InvokeBuilder,
\r
162 new InternalParameters (parent, Parameters),
\r
168 int params_num = param_types.Length;
\r
169 Type [] async_param_types = new Type [params_num + 2];
\r
171 param_types.CopyTo (async_param_types, 0);
\r
173 async_param_types [params_num] = TypeManager.asynccallback_type;
\r
174 async_param_types [params_num + 1] = TypeManager.object_type;
\r
176 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual |
\r
177 MethodAttributes.NewSlot;
\r
179 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
\r
182 TypeManager.iasyncresult_type,
\r
183 async_param_types);
\r
185 for (i = 0 ; i < param_types.Length; i++) {
\r
186 Parameter p = Parameters.FixedParameters [i];
\r
187 string name = p.Name;
\r
188 BeginInvokeBuilder.DefineParameter (i + 1, p.Attributes, name);
\r
191 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
\r
192 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
\r
194 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
196 Parameter [] async_params = new Parameter [params_num + 2];
\r
197 if (params_num > 0)
\r
198 Parameters.FixedParameters.CopyTo (async_params, 0);
\r
200 async_params [params_num] = new Parameter ("System.AsyncCallback", "callback",
\r
201 Parameter.Modifier.NONE, null);
\r
202 async_params [params_num + 1] = new Parameter ("System.IAsyncResult", "object",
\r
203 Parameter.Modifier.NONE, null);
\r
205 TypeManager.RegisterMethod (BeginInvokeBuilder,
\r
206 new InternalParameters (
\r
208 new Parameters (async_params, null, Location)),
\r
209 async_param_types);
\r
214 Type [] end_param_types = new Type [1];
\r
215 end_param_types [0] = TypeManager.iasyncresult_type;
\r
217 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
\r
222 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
\r
224 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
\r
226 Parameter [] end_params = new Parameter [1];
\r
227 end_params [0] = new Parameter ("System.IAsyncResult", "result",
\r
228 Parameter.Modifier.NONE, null);
\r
230 TypeManager.RegisterMethod (EndInvokeBuilder,
\r
231 new InternalParameters (
\r
233 new Parameters (end_params, null, Location)),
\r
240 /// Verifies whether the method in question is compatible with the delegate
\r
241 /// Returns the method itself if okay and null if not.
\r
243 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
\r
246 ParameterData pd = Invocation.GetParameterData (mb);
\r
248 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
250 if (!(ml is MethodGroupExpr)) {
\r
251 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
255 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
\r
257 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
\r
259 bool mismatch = false;
\r
260 for (int i = pd.Count; i > 0; ) {
\r
263 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
\r
273 123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
274 "' does not match delegate '" +
\r
275 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
279 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
\r
285 Report.Error (123, loc, "Method '" + Invocation.FullMethodDesc (mb) +
\r
286 "' does not match delegate '" +
\r
287 FullDelegateDesc (delegate_type, invoke_mb, invoke_pd) + "'");
\r
295 // Verifies whether the invocation arguments are compatible with the
\r
296 // delegate's target method
\r
298 public static bool VerifyApplicability (EmitContext ec, Type delegate_type, ArrayList args,
\r
306 arg_count = args.Count;
\r
308 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
310 if (!(ml is MethodGroupExpr)) {
\r
311 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
315 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
317 ParameterData pd = Invocation.GetParameterData (mb);
\r
319 if (pd.Count != arg_count) {
\r
320 Report.Error (1593, loc,
\r
321 "Delegate '" + delegate_type.ToString ()
\r
322 + "' does not take '" + arg_count + "' arguments");
\r
326 for (int i = arg_count; i > 0;) {
\r
329 Argument a = (Argument) args [i];
\r
330 Expression a_expr = a.Expr;
\r
332 if (pd.ParameterType (i) != a_expr.Type) {
\r
334 conv = Expression.ConvertImplicitStandard (ec, a_expr, pd.ParameterType (i), loc);
\r
336 if (conv == null) {
\r
337 Report.Error (1594, loc,
\r
338 "Delegate '" + delegate_type.ToString () +
\r
339 "' has some invalid arguments.");
\r
341 Report.Error (1503, loc,
\r
342 "Argument " + (i+1) +
\r
343 ": Cannot convert from '" +
\r
344 TypeManager.CSharpName (a_expr.Type)
\r
345 + "' to '" + TypeManager.CSharpName (pd.ParameterType (i)) + "'");
\r
349 if (a_expr != conv)
\r
358 /// Verifies whether the delegate in question is compatible with this one in
\r
359 /// order to determine if instantiation from the same is possible.
\r
361 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
\r
363 Expression ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
365 if (!(ml is MethodGroupExpr)) {
\r
366 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
370 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
\r
371 ParameterData pd = Invocation.GetParameterData (mb);
\r
373 Expression probe_ml = Expression.MemberLookup (ec, delegate_type, "Invoke", false, loc);
\r
375 if (!(probe_ml is MethodGroupExpr)) {
\r
376 Report.Error (-100, loc, "Internal error : could not find Invoke method!");
\r
380 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
\r
381 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
\r
383 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
\r
386 if (pd.Count != probe_pd.Count)
\r
389 for (int i = pd.Count; i > 0; ) {
\r
392 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
\r
393 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
\r
400 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
\r
402 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
\r
404 sb.Append (" " + del_type.ToString ());
\r
407 int length = pd.Count;
\r
409 for (int i = length; i > 0; ) {
\r
412 sb.Append (TypeManager.CSharpName (pd.ParameterType (length - i - 1)));
\r
418 return sb.ToString ();
\r
422 // Hack around System.Reflection as found everywhere else
\r
423 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, MemberFilter filter, object criteria)
\r
425 ArrayList members = new ArrayList ();
\r
427 if ((mt & MemberTypes.Method) != 0) {
\r
428 if (filter (ConstructorBuilder, criteria))
\r
429 members.Add (ConstructorBuilder);
\r
431 if (filter (InvokeBuilder, criteria))
\r
432 members.Add (InvokeBuilder);
\r
434 if (filter (BeginInvokeBuilder, criteria))
\r
435 members.Add (BeginInvokeBuilder);
\r
437 if (filter (EndInvokeBuilder, criteria))
\r
438 members.Add (EndInvokeBuilder);
\r
441 int count = members.Count;
\r
444 MemberInfo [] mi = new MemberInfo [count];
\r
445 members.CopyTo (mi, 0);
\r
452 public void CloseDelegate ()
\r
454 TypeBuilder.CreateType ();
\r
457 public Expression InstanceExpression {
\r
459 return instance_expr;
\r
462 instance_expr = value;
\r
466 public MethodBase TargetMethod {
\r
468 return delegate_method;
\r
471 delegate_method = value;
\r
475 public Type TargetReturnType {
\r
481 public Type [] ParameterTypes {
\r
483 return param_types;
\r
489 public class NewDelegate : Expression {
\r
491 public ArrayList Arguments;
\r
493 MethodBase constructor_method;
\r
494 MethodBase delegate_method;
\r
495 Expression delegate_instance_expr;
\r
499 public NewDelegate (Type type, ArrayList Arguments, Location loc)
\r
502 this.Arguments = Arguments;
\r
503 this.Location = loc;
\r
506 public override Expression DoResolve (EmitContext ec)
\r
508 if (Arguments == null) {
\r
509 Report.Error (-11, Location,
\r
510 "Delegate creation expression takes only one argument");
\r
514 if (Arguments.Count != 1) {
\r
515 Report.Error (-11, Location,
\r
516 "Delegate creation expression takes only one argument");
\r
520 Expression ml = Expression.MemberLookup (ec, type, ".ctor", false, Location);
\r
522 if (!(ml is MethodGroupExpr)) {
\r
523 Report.Error (-100, Location, "Internal error : Could not find delegate constructor!");
\r
527 constructor_method = ((MethodGroupExpr) ml).Methods [0];
\r
529 Argument a = (Argument) Arguments [0];
\r
531 if (!a.Resolve (ec, Location))
\r
534 Expression e = a.Expr;
\r
536 if (e is MethodGroupExpr) {
\r
537 MethodGroupExpr mg = (MethodGroupExpr) e;
\r
539 if (mg.Methods.Length > 1) {
\r
540 Report.Error (-14, Location, "Ambiguous method reference in delegate creation");
\r
544 delegate_method = Delegate.VerifyMethod (ec, type, mg.Methods [0], Location);
\r
546 if (delegate_method == null)
\r
549 if (mg.InstanceExpression != null)
\r
550 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
\r
553 delegate_instance_expr = (
\r
554 new This (Mono.CSharp.Location.Null)).Resolve (ec);
\r
556 delegate_instance_expr = null;
\r
559 if (delegate_instance_expr != null)
\r
560 if (delegate_instance_expr.Type.IsValueType)
\r
561 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
\r
563 DictionaryEntry de = new DictionaryEntry (delegate_method, delegate_instance_expr);
\r
564 TypeManager.RegisterDelegateData (type, de);
\r
566 eclass = ExprClass.Value;
\r
570 Type e_type = e.Type;
\r
572 if (!TypeManager.IsDelegateType (e_type)) {
\r
573 Report.Error (-12, Location, "Cannot create a delegate from something " +
\r
574 "not a delegate or a method.");
\r
578 // This is what MS' compiler reports. We could always choose
\r
579 // to be more verbose and actually give delegate-level specifics
\r
581 if (!Delegate.VerifyDelegate (ec, type, e_type, Location)) {
\r
582 Report.Error (29, Location, "Cannot implicitly convert type '" + e_type + "' " +
\r
583 "to type '" + type + "'");
\r
587 DictionaryEntry d = TypeManager.GetDelegateData (e_type);
\r
589 delegate_instance_expr = (Expression) d.Value;
\r
590 delegate_method = (MethodBase) d.Key;
\r
592 eclass = ExprClass.Value;
\r
596 public override void Emit (EmitContext ec)
\r
598 if (delegate_instance_expr == null)
\r
599 ec.ig.Emit (OpCodes.Ldnull);
\r
601 delegate_instance_expr.Emit (ec);
\r
603 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
\r
604 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
\r
608 public class DelegateInvocation : ExpressionStatement {
\r
610 public Expression InstanceExpr;
\r
611 public ArrayList Arguments;
\r
612 public Location Location;
\r
616 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
\r
618 this.InstanceExpr = instance_expr;
\r
619 this.Arguments = args;
\r
620 this.Location = loc;
\r
623 public override Expression DoResolve (EmitContext ec)
\r
625 Type del_type = InstanceExpr.Type;
\r
627 if (del_type == null)
\r
630 if (Arguments != null){
\r
631 for (int i = Arguments.Count; i > 0;){
\r
633 Argument a = (Argument) Arguments [i];
\r
635 if (!a.Resolve (ec, Location))
\r
640 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, Location))
\r
643 Expression ml = Expression.MemberLookup (ec, del_type, "Invoke", false, Location);
\r
645 if (!(ml is MethodGroupExpr)) {
\r
646 Report.Error (-100, Location, "Internal error : could not find Invoke method!");
\r
650 method = ((MethodGroupExpr) ml).Methods [0];
\r
652 type = ((MethodInfo) method).ReturnType;
\r
654 eclass = ExprClass.Value;
\r
659 public override void Emit (EmitContext ec)
\r
661 Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
\r
664 // Invocation on delegates call the virtual Invoke member
\r
665 // so we are always `instance' calls
\r
667 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments);
\r
670 public override void EmitStatement (EmitContext ec)
\r
674 // Pop the return value if there is one
\r
676 if (method is MethodInfo){
\r
677 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
\r
678 ec.ig.Emit (OpCodes.Pop);
\r