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.MonoBASIC {
23 public class Delegate : DeclSpace {
24 public Expression ReturnType;
25 public Parameters Parameters;
27 public ConstructorBuilder ConstructorBuilder;
28 public MethodBuilder InvokeBuilder;
29 public MethodBuilder BeginInvokeBuilder;
30 public MethodBuilder EndInvokeBuilder;
35 Expression instance_expr;
36 MethodBase delegate_method;
38 const int AllowedModifiers =
46 public Delegate (TypeContainer parent, Expression type, int mod_flags,
47 string name, Parameters param_list,
48 Attributes attrs, Location l)
49 : base (parent, name, attrs, l)
51 this.ReturnType = type;
53 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
54 IsTopLevel ? Modifiers.INTERNAL :
56 Parameters = param_list;
59 public override AttributeTargets AttributeTargets {
61 return AttributeTargets.Delegate;
65 public override TypeBuilder DefineType ()
69 if (TypeBuilder != null)
73 ModuleBuilder builder = CodeGen.ModuleBuilder;
74 attr = TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed;
76 TypeBuilder = builder.DefineType (
77 Name, attr, TypeManager.multicast_delegate_type);
79 TypeBuilder builder = Parent.TypeBuilder;
80 attr = TypeAttributes.NestedPublic | TypeAttributes.Class |
81 TypeAttributes.Sealed;
83 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
84 TypeBuilder = builder.DefineNestedType (
85 name, attr, TypeManager.multicast_delegate_type);
88 TypeManager.AddDelegateType (Name, TypeBuilder, this);
93 public override bool DefineMembers (TypeContainer container)
98 public override bool Define (TypeContainer container)
100 MethodAttributes mattr;
103 // FIXME: POSSIBLY make this static, as it is always constant
105 Type [] const_arg_types = new Type [2];
106 const_arg_types [0] = TypeManager.object_type;
107 const_arg_types [1] = TypeManager.intptr_type;
109 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
110 MethodAttributes.HideBySig | MethodAttributes.Public;
112 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
113 CallingConventions.Standard,
116 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
117 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
119 // HACK because System.Reflection.Emit is lame
122 // FIXME: POSSIBLY make these static, as they are always the same
123 Parameter [] fixed_pars = new Parameter [2];
124 fixed_pars [0] = new Parameter (null, null, Parameter.Modifier.NONE, null);
125 fixed_pars [1] = new Parameter (null, null, Parameter.Modifier.NONE, null);
126 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
128 TypeManager.RegisterMethod (
130 new InternalParameters (const_arg_types, const_parameters),
134 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
137 // Here the various methods like Invoke, BeginInvoke etc are defined
139 // First, call the `out of band' special method for
140 // defining recursively any types we need:
142 if (!Parameters.ComputeAndDefineParameterTypes (this))
145 param_types = Parameters.GetParameterInfo (this);
146 if (param_types == null)
153 // Check accessibility
154 foreach (Type partype in param_types)
155 if (!container.AsAccessible (partype, ModFlags)) {
156 Report.Error (59, Location,
157 "Inconsistent accessibility: parameter type `" +
158 TypeManager.MonoBASIC_Name (partype) + "` is less " +
159 "accessible than delegate `" + Name + "'");
163 ReturnType = ResolveTypeExpr (ReturnType, false, Location);
164 ret_type = ReturnType.Type;
165 if (ret_type == null)
168 if (!container.AsAccessible (ret_type, ModFlags)) {
169 Report.Error (58, Location,
170 "Inconsistent accessibility: return type `" +
171 TypeManager.MonoBASIC_Name (ret_type) + "` is less " +
172 "accessible than delegate `" + Name + "'");
177 // We don't have to check any others because they are all
178 // guaranteed to be accessible - they are standard types.
181 CallingConventions cc = Parameters.GetCallingConvention ();
183 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
185 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
192 if (Parameters.FixedParameters != null){
193 int top = Parameters.FixedParameters.Length;
196 for (; i < top; i++) {
197 p = Parameters.FixedParameters [i];
199 InvokeBuilder.DefineParameter (
200 i+1, p.Attributes, p.Name);
203 if (Parameters.ArrayParameter != null){
204 Parameter p = Parameters.ArrayParameter;
206 InvokeBuilder.DefineParameter (
207 i+1, p.Attributes, p.Name);
210 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
212 TypeManager.RegisterMethod (InvokeBuilder,
213 new InternalParameters (container, Parameters),
219 int params_num = param_types.Length;
220 Type [] async_param_types = new Type [params_num + 2];
222 param_types.CopyTo (async_param_types, 0);
224 async_param_types [params_num] = TypeManager.asynccallback_type;
225 async_param_types [params_num + 1] = TypeManager.object_type;
227 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
228 MethodAttributes.Virtual | MethodAttributes.NewSlot;
230 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
233 TypeManager.iasyncresult_type,
237 if (Parameters.FixedParameters != null){
238 int top = Parameters.FixedParameters.Length;
241 for (i = 0 ; i < top; i++) {
242 p = Parameters.FixedParameters [i];
244 BeginInvokeBuilder.DefineParameter (
245 i+1, p.Attributes, p.Name);
248 if (Parameters.ArrayParameter != null){
249 Parameter p = Parameters.ArrayParameter;
251 BeginInvokeBuilder.DefineParameter (
252 i+1, p.Attributes, p.Name);
256 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
257 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
259 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
261 Parameter [] async_params = new Parameter [params_num + 2];
263 if (Parameters.FixedParameters != null){
264 Parameters.FixedParameters.CopyTo (async_params, 0);
265 n = Parameters.FixedParameters.Length;
267 if (Parameters.ArrayParameter != null)
268 async_params [n] = Parameters.ArrayParameter;
270 async_params [params_num] = new Parameter (
271 TypeManager.system_asynccallback_expr, "callback",
272 Parameter.Modifier.NONE, null);
273 async_params [params_num + 1] = new Parameter (
274 TypeManager.system_object_expr, "object",
275 Parameter.Modifier.NONE, null);
277 Parameters async_parameters = new Parameters (async_params, null, Location);
279 async_parameters.ComputeAndDefineParameterTypes (this);
280 TypeManager.RegisterMethod (BeginInvokeBuilder,
281 new InternalParameters (container, async_parameters),
287 Type [] end_param_types = new Type [1];
288 end_param_types [0] = TypeManager.iasyncresult_type;
290 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke",
295 EndInvokeBuilder.DefineParameter (1, ParameterAttributes.None, "result");
297 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
299 Parameter [] end_params = new Parameter [1];
300 end_params [0] = new Parameter (
301 TypeManager.system_iasyncresult_expr, "result",
302 Parameter.Modifier.NONE, null);
304 TypeManager.RegisterMethod (
305 EndInvokeBuilder, new InternalParameters (
308 end_params, null, Location)),
315 /// Verifies whether the method in question is compatible with the delegate
316 /// Returns the method itself if okay and null if not.
318 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
321 ParameterData pd = Invocation.GetParameterData (mb);
323 int pd_count = pd.Count;
325 Expression ml = Expression.MemberLookup (
326 ec, delegate_type, "Invoke", loc);
328 if (!(ml is MethodGroupExpr)) {
329 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
333 MethodBase invoke_mb = ((MethodGroupExpr) ml).Methods [0];
335 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
337 if (invoke_pd.Count != pd_count)
340 for (int i = pd_count; i > 0; ) {
343 if (invoke_pd.ParameterType (i) == pd.ParameterType (i))
349 if (((MethodInfo) invoke_mb).ReturnType == ((MethodInfo) mb).ReturnType)
356 // Verifies whether the invocation arguments are compatible with the
357 // delegate's target method
359 public static bool VerifyApplicability (EmitContext ec,
369 arg_count = args.Count;
371 Expression ml = Expression.MemberLookup (
372 ec, delegate_type, "Invoke", loc);
374 if (!(ml is MethodGroupExpr)) {
375 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
379 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
380 ParameterData pd = Invocation.GetParameterData (mb);
382 int pd_count = pd.Count;
384 bool not_params_method = (pd_count == 0) ||
385 (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS);
387 if (not_params_method && pd_count != arg_count) {
388 Report.Error (1593, loc,
389 "Delegate '" + delegate_type.ToString ()
390 + "' does not take '" + arg_count + "' arguments");
394 return Invocation.VerifyArgumentsCompat (ec, args, arg_count, mb, !not_params_method,
399 /// Verifies whether the delegate in question is compatible with this one in
400 /// order to determine if instantiation from the same is possible.
402 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
404 Expression ml = Expression.MemberLookup (
405 ec, delegate_type, "Invoke", loc);
407 if (!(ml is MethodGroupExpr)) {
408 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
412 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
413 ParameterData pd = Invocation.GetParameterData (mb);
415 Expression probe_ml = Expression.MemberLookup (
416 ec, delegate_type, "Invoke", loc);
418 if (!(probe_ml is MethodGroupExpr)) {
419 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
423 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
424 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
426 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
429 if (pd.Count != probe_pd.Count)
432 for (int i = pd.Count; i > 0; ) {
435 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
436 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
443 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
445 StringBuilder sb = new StringBuilder (TypeManager.MonoBASIC_Name (((MethodInfo) mb).ReturnType));
447 sb.Append (" " + del_type.ToString ());
450 int length = pd.Count;
452 for (int i = length; i > 0; ) {
455 sb.Append (TypeManager.MonoBASIC_Name (pd.ParameterType (length - i - 1)));
461 return sb.ToString ();
465 // Hack around System.Reflection as found everywhere else
466 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
467 MemberFilter filter, object criteria)
469 ArrayList members = new ArrayList ();
471 if ((mt & MemberTypes.Method) != 0) {
472 if (ConstructorBuilder != null)
473 if (filter (ConstructorBuilder, criteria))
474 members.Add (ConstructorBuilder);
476 if (InvokeBuilder != null)
477 if (filter (InvokeBuilder, criteria))
478 members.Add (InvokeBuilder);
480 if (BeginInvokeBuilder != null)
481 if (filter (BeginInvokeBuilder, criteria))
482 members.Add (BeginInvokeBuilder);
484 if (EndInvokeBuilder != null)
485 if (filter (EndInvokeBuilder, criteria))
486 members.Add (EndInvokeBuilder);
489 return new MemberList (members);
492 public override MemberCache MemberCache {
498 public Expression InstanceExpression {
500 return instance_expr;
503 instance_expr = value;
507 public MethodBase TargetMethod {
509 return delegate_method;
512 delegate_method = value;
516 public Type TargetReturnType {
522 public Type [] ParameterTypes {
530 public class NewDelegate : Expression {
532 public ArrayList Arguments;
534 MethodBase constructor_method;
535 MethodBase delegate_method;
536 Expression delegate_instance_expr;
538 public NewDelegate (Type type, ArrayList Arguments, Location loc)
541 this.Arguments = Arguments;
545 public override Expression DoResolve (EmitContext ec)
547 if (Arguments == null) {
548 Report.Error (-11, loc,
549 "Delegate creation expression takes only one argument");
553 if (Arguments.Count != 1) {
554 Report.Error (-11, loc,
555 "Delegate creation expression takes only one argument");
559 Expression ml = Expression.MemberLookup (
560 ec, type, ".ctor", loc);
562 if (!(ml is MethodGroupExpr)) {
563 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
567 constructor_method = ((MethodGroupExpr) ml).Methods [0];
568 Argument a = (Argument) Arguments [0];
570 if (!a.ResolveMethodGroup (ec, Location))
573 Expression e = a.Expr;
575 Expression invoke_method = Expression.MemberLookup (
576 ec, type, "Invoke", MemberTypes.Method,
577 Expression.AllBindingFlags, loc);
579 if (invoke_method == null) {
580 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
584 if (e is MethodGroupExpr) {
585 MethodGroupExpr mg = (MethodGroupExpr) e;
587 foreach (MethodInfo mi in mg.Methods){
588 delegate_method = Delegate.VerifyMethod (ec, type, mi, loc);
590 if (delegate_method != null)
594 if (delegate_method == null) {
596 if (mg.Methods.Length > 1)
597 method_desc = mg.Methods [0].Name;
599 method_desc = Invocation.FullMethodDesc (mg.Methods [0]);
601 MethodBase dm = ((MethodGroupExpr) invoke_method).Methods [0];
602 ParameterData param = Invocation.GetParameterData (dm);
603 string delegate_desc = Delegate.FullDelegateDesc (type, dm, param);
605 Report.Error (30408, loc, "Method '" + method_desc + "' does not " +
606 "match delegate '" + delegate_desc + "'");
612 // Check safe/unsafe of the delegate
615 ParameterData param = Invocation.GetParameterData (delegate_method);
616 int count = param.Count;
618 for (int i = 0; i < count; i++){
619 if (param.ParameterType (i).IsPointer){
620 Expression.UnsafeError (loc);
626 if (mg.InstanceExpression != null)
627 delegate_instance_expr = mg.InstanceExpression.Resolve (ec);
630 delegate_instance_expr = ec.This;
632 delegate_instance_expr = null;
635 if (delegate_instance_expr != null)
636 if (delegate_instance_expr.Type.IsValueType)
637 delegate_instance_expr = new BoxedCast (delegate_instance_expr);
639 eclass = ExprClass.Value;
643 Type e_type = e.Type;
645 if (!TypeManager.IsDelegateType (e_type)) {
646 Report.Error (-12, loc, "Cannot create a delegate from something " +
647 "not a delegate or a method.");
651 // This is what MS' compiler reports. We could always choose
652 // to be more verbose and actually give delegate-level specifics
654 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
655 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
656 "to type '" + type + "'");
660 delegate_instance_expr = e;
661 delegate_method = ((MethodGroupExpr) invoke_method).Methods [0];
663 eclass = ExprClass.Value;
667 public override void Emit (EmitContext ec)
669 if (delegate_instance_expr == null ||
670 delegate_method.IsStatic)
671 ec.ig.Emit (OpCodes.Ldnull);
673 delegate_instance_expr.Emit (ec);
675 if (delegate_method.IsVirtual) {
676 ec.ig.Emit (OpCodes.Dup);
677 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
679 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
680 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
684 public class DelegateInvocation : ExpressionStatement {
686 public Expression InstanceExpr;
687 public ArrayList Arguments;
691 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
693 this.InstanceExpr = instance_expr;
694 this.Arguments = args;
698 public override Expression DoResolve (EmitContext ec)
700 if (InstanceExpr is EventExpr) {
702 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
704 Expression ml = MemberLookup (
705 ec, ec.ContainerType, ei.Name,
706 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
710 // If this is the case, then the Event does not belong
711 // to this Type and so, according to the spec
712 // cannot be accessed directly
714 // Note that target will not appear as an EventExpr
715 // in the case it is being referenced within the same type container;
716 // it will appear as a FieldExpr in that case.
719 Assign.error70 (ei, loc);
725 Type del_type = InstanceExpr.Type;
726 if (del_type == null)
729 if (Arguments != null){
730 foreach (Argument a in Arguments){
731 if (!a.Resolve (ec, loc))
736 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
739 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
740 if (!(lookup is MethodGroupExpr)) {
741 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
745 method = ((MethodGroupExpr) lookup).Methods [0];
746 type = ((MethodInfo) method).ReturnType;
747 eclass = ExprClass.Value;
752 public override void Emit (EmitContext ec)
754 // Delegate del = TypeManager.LookupDelegate (InstanceExpr.Type);
757 // Invocation on delegates call the virtual Invoke member
758 // so we are always `instance' calls
760 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
763 public override void EmitStatement (EmitContext ec)
767 // Pop the return value if there is one
769 if (method is MethodInfo){
770 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
771 ec.ig.Emit (OpCodes.Pop);