2 // delegate.cs: Delegate Handler
5 // Ravi Pratap (ravi@ximian.com)
6 // Miguel de Icaza (miguel@ximian.com)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
20 namespace Mono.CSharp {
25 public class Delegate : DeclSpace {
26 public Expression ReturnType;
27 public Parameters Parameters;
29 public ConstructorBuilder ConstructorBuilder;
30 public MethodBuilder InvokeBuilder;
31 public MethodBuilder BeginInvokeBuilder;
32 public MethodBuilder EndInvokeBuilder;
36 static string[] attribute_targets = new string [] { "type", "return" };
38 Expression instance_expr;
39 MethodBase delegate_method;
40 ReturnParameter return_attributes;
42 const int AllowedModifiers =
50 public Delegate (NamespaceEntry ns, TypeContainer parent, Expression type,
51 int mod_flags, MemberName name, Parameters param_list,
53 : base (ns, parent, name, attrs)
56 this.ReturnType = type;
57 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
58 IsTopLevel ? Modifiers.INTERNAL :
59 Modifiers.PRIVATE, name.Location);
60 Parameters = param_list;
63 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
65 if (a.Target == AttributeTargets.ReturnValue) {
66 if (return_attributes == null)
67 return_attributes = new ReturnParameter (InvokeBuilder, Location);
69 return_attributes.ApplyAttributeBuilder (a, cb);
73 base.ApplyAttributeBuilder (a, cb);
76 public override TypeBuilder DefineType ()
78 if (TypeBuilder != null)
81 if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
82 Namespace system = RootNamespace.Global.GetNamespace ("System", true);
83 TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
84 TypeManager.multicast_delegate_type = expr.Type;
87 if (TypeManager.multicast_delegate_type == null)
88 throw new InternalErrorException ("System.MulticastDelegate unresolved");
91 if (TypeManager.NamespaceClash (Name, Location))
94 ModuleBuilder builder = CodeGen.Module.Builder;
96 TypeBuilder = builder.DefineType (
97 Name, TypeAttr, TypeManager.multicast_delegate_type);
99 TypeBuilder builder = Parent.TypeBuilder;
101 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
102 TypeBuilder = builder.DefineNestedType (
103 name, TypeAttr, TypeManager.multicast_delegate_type);
106 TypeManager.AddUserType (this);
111 public override bool Define ()
113 // FIXME: POSSIBLY make this static, as it is always constant
115 Type [] const_arg_types = new Type [2];
116 const_arg_types [0] = TypeManager.object_type;
117 const_arg_types [1] = TypeManager.intptr_type;
119 const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
120 MethodAttributes.HideBySig | MethodAttributes.Public;
122 ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
123 CallingConventions.Standard,
126 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
127 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
129 // HACK because System.Reflection.Emit is lame
131 Parameter [] fixed_pars = new Parameter [2];
132 fixed_pars [0] = new Parameter (TypeManager.object_type, "object",
133 Parameter.Modifier.NONE, null, Location);
134 fixed_pars [1] = new Parameter (TypeManager.intptr_type, "method",
135 Parameter.Modifier.NONE, null, Location);
136 Parameters const_parameters = new Parameters (fixed_pars);
137 const_parameters.Resolve (null);
139 TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
142 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
145 // Here the various methods like Invoke, BeginInvoke etc are defined
147 // First, call the `out of band' special method for
148 // defining recursively any types we need:
150 if (!Parameters.Resolve (this))
157 // Check accessibility
158 foreach (Type partype in Parameters.Types){
159 if (!Parent.AsAccessible (partype, ModFlags)) {
160 Report.Error (59, Location,
161 "Inconsistent accessibility: parameter type `" +
162 TypeManager.CSharpName (partype) + "' is less " +
163 "accessible than delegate `" + Name + "'");
168 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
169 if (ReturnType == null)
172 ret_type = ReturnType.Type;
174 if (!Parent.AsAccessible (ret_type, ModFlags)) {
175 Report.Error (58, Location,
176 "Inconsistent accessibility: return type `" +
177 TypeManager.CSharpName (ret_type) + "' is less " +
178 "accessible than delegate `" + Name + "'");
182 if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
183 Method.Error1599 (Location, ret_type);
188 // We don't have to check any others because they are all
189 // guaranteed to be accessible - they are standard types.
192 CallingConventions cc = Parameters.CallingConvention;
194 const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
196 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
202 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
204 TypeManager.RegisterMethod (InvokeBuilder, Parameters);
210 Parameters async_parameters = Parameters.MergeGenerated (Parameters,
211 new Parameter (TypeManager.asynccallback_type, "callback", Parameter.Modifier.NONE, null, Location),
212 new Parameter (TypeManager.object_type, "object", Parameter.Modifier.NONE, null, Location));
214 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
215 mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
217 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
218 async_parameters.ApplyAttributes (BeginInvokeBuilder);
219 TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
222 // EndInvoke is a bit more interesting, all the parameters labeled as
223 // out or ref have to be duplicated here.
227 // Define parameters, and count out/ref parameters
229 Parameters end_parameters;
232 foreach (Parameter p in Parameters.FixedParameters) {
233 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
237 if (out_params > 0) {
238 Type [] end_param_types = new Type [out_params];
239 Parameter [] end_params = new Parameter [out_params ];
242 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
243 Parameter p = Parameters.FixedParameters [i];
244 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
247 end_param_types [param] = p.ExternalType();
248 end_params [param] = p;
251 end_parameters = new Parameters (end_params, end_param_types);
254 end_parameters = Parameters.EmptyReadOnlyParameters;
257 end_parameters = Parameters.MergeGenerated (end_parameters,
258 new Parameter (TypeManager.iasyncresult_type, "result", Parameter.Modifier.NONE, null, Location));
261 // Create method, define parameters, register parameters with type system
263 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.Types);
264 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
266 end_parameters.ApplyAttributes (EndInvokeBuilder);
267 TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
272 public override void Emit ()
274 Parameters.ApplyAttributes (InvokeBuilder);
276 if (OptAttributes != null) {
277 OptAttributes.Emit ();
283 protected override TypeAttributes TypeAttr {
285 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
286 TypeAttributes.Class | TypeAttributes.Sealed |
291 public override string[] ValidAttributeTargets {
293 return attribute_targets;
298 protected override bool VerifyClsCompliance ()
300 if (!base.VerifyClsCompliance ()) {
304 Parameters.VerifyClsCompliance ();
306 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
307 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant", GetSignatureForError ());
313 // Returns the MethodBase for "Invoke" from a delegate type, this is used
314 // to extract the signature of a delegate.
316 public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type, Location loc)
318 Expression ml = Expression.MemberLookup (container_type, delegate_type,
321 if (!(ml is MethodGroupExpr)) {
322 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
326 return (MethodInfo) (((MethodGroupExpr) ml).Methods [0]);
330 /// Verifies whether the method in question is compatible with the delegate
331 /// Returns the method itself if okay and null if not.
333 public static MethodBase VerifyMethod (Type container_type, Type delegate_type, MethodBase mb,
336 ParameterData pd = TypeManager.GetParameterData (mb);
338 int pd_count = pd.Count;
340 MethodBase invoke_mb = GetInvokeMethod (container_type, delegate_type, loc);
341 if (invoke_mb == null)
344 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
346 if (invoke_pd.Count != pd_count)
349 for (int i = pd_count; i > 0; ) {
352 Type invoke_pd_type = invoke_pd.ParameterType (i);
353 Type pd_type = pd.ParameterType (i);
354 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
355 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
357 if (invoke_pd_type == pd_type &&
358 invoke_pd_type_mod == pd_type_mod)
361 if (invoke_pd_type.IsSubclassOf (pd_type) &&
362 invoke_pd_type_mod == pd_type_mod)
363 if (RootContext.Version == LanguageVersion.ISO_1) {
364 Report.FeatureIsNotStandardized (loc, "contravariance");
372 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
373 Type mb_retval = ((MethodInfo) mb).ReturnType;
374 if (invoke_mb_retval == mb_retval)
377 if (mb_retval.IsSubclassOf (invoke_mb_retval))
378 if (RootContext.Version == LanguageVersion.ISO_1) {
379 Report.FeatureIsNotStandardized (loc, "covariance");
389 // Verifies whether the invocation arguments are compatible with the
390 // delegate's target method
392 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
393 ArrayList args, Location loc)
400 arg_count = args.Count;
402 Expression ml = Expression.MemberLookup (
403 ec.ContainerType, delegate_type, "Invoke", loc);
405 MethodGroupExpr me = ml as MethodGroupExpr;
407 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
411 MethodBase mb = me.Methods [0];
412 ParameterData pd = TypeManager.GetParameterData (mb);
414 int pd_count = pd.Count;
416 bool params_method = pd.HasParams;
417 bool is_params_applicable = false;
418 bool is_applicable = Invocation.IsApplicable (ec, args, arg_count, mb);
420 if (!is_applicable && params_method &&
421 Invocation.IsParamsMethodApplicable (ec, args, arg_count, mb))
422 is_applicable = is_params_applicable = true;
424 if (!is_applicable && !params_method && arg_count != pd_count) {
425 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
426 TypeManager.CSharpName (delegate_type), arg_count.ToString ());
430 return Invocation.VerifyArgumentsCompat (
431 ec, args, arg_count, mb,
432 is_params_applicable || (!is_applicable && params_method),
433 delegate_type, false, loc);
437 /// Verifies whether the delegate in question is compatible with this one in
438 /// order to determine if instantiation from the same is possible.
440 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
442 Expression ml = Expression.MemberLookup (
443 ec.ContainerType, delegate_type, "Invoke", loc);
445 if (!(ml is MethodGroupExpr)) {
446 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
450 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
451 ParameterData pd = TypeManager.GetParameterData (mb);
453 Expression probe_ml = Expression.MemberLookup (
454 ec.ContainerType, delegate_type, "Invoke", loc);
456 if (!(probe_ml is MethodGroupExpr)) {
457 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
461 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
462 ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
464 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
467 if (pd.Count != probe_pd.Count)
470 for (int i = pd.Count; i > 0; ) {
473 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
474 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
481 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
483 StringBuilder sb = new StringBuilder ();
484 sb.Append (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
486 sb.Append (TypeManager.CSharpName (del_type));
487 sb.Append (pd.GetSignatureForError ());
488 return sb.ToString ();
491 // Hack around System.Reflection as found everywhere else
492 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
493 MemberFilter filter, object criteria)
495 ArrayList members = new ArrayList ();
497 if ((mt & MemberTypes.Method) != 0) {
498 if (ConstructorBuilder != null)
499 if (filter (ConstructorBuilder, criteria))
500 members.Add (ConstructorBuilder);
502 if (InvokeBuilder != null)
503 if (filter (InvokeBuilder, criteria))
504 members.Add (InvokeBuilder);
506 if (BeginInvokeBuilder != null)
507 if (filter (BeginInvokeBuilder, criteria))
508 members.Add (BeginInvokeBuilder);
510 if (EndInvokeBuilder != null)
511 if (filter (EndInvokeBuilder, criteria))
512 members.Add (EndInvokeBuilder);
515 return new MemberList (members);
518 public override MemberCache MemberCache {
524 public Expression InstanceExpression {
526 return instance_expr;
529 instance_expr = value;
533 public MethodBase TargetMethod {
535 return delegate_method;
538 delegate_method = value;
542 public Type TargetReturnType {
548 public override AttributeTargets AttributeTargets {
550 return AttributeTargets.Delegate;
555 // Represents header string for documentation comment.
557 public override string DocCommentHeader {
564 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
566 public abstract class DelegateCreation : Expression {
567 protected MethodBase constructor_method;
568 protected MethodBase delegate_method;
569 protected MethodGroupExpr method_group;
570 protected Expression delegate_instance_expression;
572 protected DelegateCreation () {}
574 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
577 MethodInfo found_method = (MethodInfo)mg.Methods [0];
579 if (mg.Methods.Length > 1)
580 method_desc = found_method.Name;
582 method_desc = Invocation.FullMethodDesc (found_method);
584 Expression invoke_method = Expression.MemberLookup (
585 ec.ContainerType, type, "Invoke", MemberTypes.Method,
586 Expression.AllBindingFlags, loc);
587 MethodInfo method = ((MethodGroupExpr) invoke_method).Methods [0] as MethodInfo;
589 ParameterData param = TypeManager.GetParameterData (method);
590 string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
592 if (method.ReturnType != found_method.ReturnType) {
593 Report.Error (407, loc, "`{0}' has the wrong return type to match the delegate `{1}'", method_desc, delegate_desc);
595 Report.Error (123, loc, "Method `{0}' does not match delegate `{1}'", method_desc, delegate_desc);
599 public override void Emit (EmitContext ec)
601 if (delegate_instance_expression == null || delegate_method.IsStatic)
602 ec.ig.Emit (OpCodes.Ldnull);
604 delegate_instance_expression.Emit (ec);
606 if (delegate_method.IsVirtual && !method_group.IsBase) {
607 ec.ig.Emit (OpCodes.Dup);
608 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
610 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
611 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
614 protected bool ResolveConstructorMethod (EmitContext ec)
616 Expression ml = Expression.MemberLookup (
617 ec.ContainerType, type, ".ctor", loc);
619 if (!(ml is MethodGroupExpr)) {
620 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
624 constructor_method = ((MethodGroupExpr) ml).Methods [0];
628 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type targetType)
630 foreach (MethodInfo mi in mg.Methods){
631 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, targetType, mi, Location.Null);
638 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
640 delegate_method = ImplicitStandardConversionExists (mg, type);
642 if (delegate_method == null) {
643 Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
648 // Check safe/unsafe of the delegate
651 ParameterData param = TypeManager.GetParameterData (delegate_method);
652 int count = param.Count;
654 for (int i = 0; i < count; i++){
655 if (param.ParameterType (i).IsPointer){
656 Expression.UnsafeError (loc);
662 //TODO: implement caching when performance will be low
663 IMethodData md = TypeManager.GetMethod (delegate_method);
665 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
666 Report.SymbolRelatedToPreviousError (delegate_method);
667 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
671 md.SetMemberIsUsed ();
672 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type) != null) {
673 Report.SymbolRelatedToPreviousError (delegate_method);
674 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
679 if (mg.InstanceExpression != null)
680 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
681 else if (ec.IsStatic) {
682 if (!delegate_method.IsStatic) {
683 Report.Error (120, loc, "`{0}': An object reference is required for the nonstatic field, method or property",
684 TypeManager.CSharpSignature (delegate_method));
687 delegate_instance_expression = null;
689 delegate_instance_expression = ec.GetThis (loc);
691 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
692 delegate_instance_expression = new BoxedCast (
693 delegate_instance_expression, TypeManager.object_type);
696 eclass = ExprClass.Value;
702 // Created from the conversion code
704 public class ImplicitDelegateCreation : DelegateCreation {
706 ImplicitDelegateCreation (Type t, Location l)
712 public override Expression DoResolve (EmitContext ec)
717 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
718 Type target_type, Location loc)
720 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
721 if (!d.ResolveConstructorMethod (ec))
724 return d.ResolveMethodGroupExpr (ec, mge);
729 // A delegate-creation-expression, invoked from the `New' class
731 public class NewDelegate : DelegateCreation {
732 public ArrayList Arguments;
735 // This constructor is invoked from the `New' expression
737 public NewDelegate (Type type, ArrayList Arguments, Location loc)
740 this.Arguments = Arguments;
744 public override Expression DoResolve (EmitContext ec)
746 if (Arguments == null || Arguments.Count != 1) {
747 Report.Error (149, loc,
748 "Method name expected");
752 if (!ResolveConstructorMethod (ec))
755 Argument a = (Argument) Arguments [0];
757 if (!a.ResolveMethodGroup (ec, loc))
760 Expression e = a.Expr;
762 if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
763 return ((AnonymousMethod) e).Compatible (ec, type, false);
765 MethodGroupExpr mg = e as MethodGroupExpr;
767 return ResolveMethodGroupExpr (ec, mg);
769 Type e_type = e.Type;
771 if (!TypeManager.IsDelegateType (e_type)) {
772 Report.Error (149, loc, "Method name expected");
776 method_group = Expression.MemberLookup (
777 ec.ContainerType, type, "Invoke", MemberTypes.Method,
778 Expression.AllBindingFlags, loc) as MethodGroupExpr;
780 if (method_group == null) {
781 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
785 // This is what MS' compiler reports. We could always choose
786 // to be more verbose and actually give delegate-level specifics
787 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
788 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
789 "to type '" + type + "'");
793 delegate_instance_expression = e;
794 delegate_method = method_group.Methods [0];
796 eclass = ExprClass.Value;
801 public class DelegateInvocation : ExpressionStatement {
803 public Expression InstanceExpr;
804 public ArrayList Arguments;
808 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
810 this.InstanceExpr = instance_expr;
811 this.Arguments = args;
815 public override Expression DoResolve (EmitContext ec)
817 if (InstanceExpr is EventExpr) {
819 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
821 Expression ml = MemberLookup (
822 ec.ContainerType, ec.ContainerType, ei.Name,
823 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
827 // If this is the case, then the Event does not belong
828 // to this Type and so, according to the spec
829 // cannot be accessed directly
831 // Note that target will not appear as an EventExpr
832 // in the case it is being referenced within the same type container;
833 // it will appear as a FieldExpr in that case.
836 Assign.error70 (ei, loc);
842 Type del_type = InstanceExpr.Type;
843 if (del_type == null)
846 if (Arguments != null){
847 foreach (Argument a in Arguments){
848 if (!a.Resolve (ec, loc))
853 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
856 Expression lookup = Expression.MemberLookup (ec.ContainerType, del_type, "Invoke", loc);
857 if (!(lookup is MethodGroupExpr)) {
858 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
862 method = ((MethodGroupExpr) lookup).Methods [0];
863 type = ((MethodInfo) method).ReturnType;
864 eclass = ExprClass.Value;
869 public override void Emit (EmitContext ec)
872 // Invocation on delegates call the virtual Invoke member
873 // so we are always `instance' calls
875 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
878 public override void EmitStatement (EmitContext ec)
882 // Pop the return value if there is one
884 if (method is MethodInfo){
885 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
886 ec.ig.Emit (OpCodes.Pop);