2 // delegate.cs: Delegate Handler
5 // Ravi Pratap (ravi@ximian.com)
6 // Miguel de Icaza (miguel@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // Dual licensed under the terms of the MIT X11 or GNU GPL
11 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
12 // Copyright 2003-2008 Novell, Inc (http://www.ximian.com)
16 using System.Collections;
17 using System.Reflection;
18 using System.Reflection.Emit;
21 namespace Mono.CSharp {
26 public class Delegate : DeclSpace, IMemberContainer
28 FullNamedExpression ReturnType;
29 public Parameters Parameters;
31 public ConstructorBuilder ConstructorBuilder;
32 public MethodBuilder InvokeBuilder;
33 public MethodBuilder BeginInvokeBuilder;
34 public MethodBuilder EndInvokeBuilder;
38 static string[] attribute_targets = new string [] { "type", "return" };
40 Expression instance_expr;
41 MethodBase delegate_method;
42 ReturnParameter return_attributes;
44 MemberCache member_cache;
46 const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
47 MethodAttributes.Virtual | MethodAttributes.NewSlot;
49 const int AllowedModifiers =
57 public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
58 int mod_flags, MemberName name, Parameters param_list,
60 : base (ns, parent, name, attrs)
63 this.ReturnType = type;
64 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
65 IsTopLevel ? Modifiers.INTERNAL :
66 Modifiers.PRIVATE, name.Location);
67 Parameters = param_list;
70 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
72 if (a.Target == AttributeTargets.ReturnValue) {
73 if (return_attributes == null)
74 return_attributes = new ReturnParameter (InvokeBuilder, Location);
76 return_attributes.ApplyAttributeBuilder (a, cb);
80 base.ApplyAttributeBuilder (a, cb);
83 public override TypeBuilder DefineType ()
85 if (TypeBuilder != null)
89 if (TypeManager.NamespaceClash (Name, Location))
92 ModuleBuilder builder = CodeGen.Module.Builder;
94 TypeBuilder = builder.DefineType (
95 Name, TypeAttr, TypeManager.multicast_delegate_type);
97 TypeBuilder builder = Parent.TypeBuilder;
99 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
100 TypeBuilder = builder.DefineNestedType (
101 name, TypeAttr, TypeManager.multicast_delegate_type);
104 TypeManager.AddUserType (this);
108 string[] param_names = new string [TypeParameters.Length];
109 for (int i = 0; i < TypeParameters.Length; i++)
110 param_names [i] = TypeParameters [i].Name;
112 GenericTypeParameterBuilder[] gen_params;
113 gen_params = TypeBuilder.DefineGenericParameters (param_names);
115 int offset = CountTypeParameters - CurrentTypeParameters.Length;
116 for (int i = offset; i < gen_params.Length; i++)
117 CurrentTypeParameters [i - offset].Define (gen_params [i]);
119 foreach (TypeParameter type_param in CurrentTypeParameters) {
120 if (!type_param.Resolve (this))
124 Expression current = new SimpleName (
125 MemberName.Basename, TypeParameters, Location);
126 current = current.ResolveAsTypeTerminal (this, false);
130 CurrentType = current.Type;
137 public override bool Define ()
141 foreach (TypeParameter type_param in TypeParameters) {
142 if (!type_param.Resolve (this))
146 foreach (TypeParameter type_param in TypeParameters) {
147 if (!type_param.DefineType (this))
151 foreach (TypeParameter type_param in TypeParameters) {
152 if (!type_param.CheckDependencies ())
157 member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
159 // FIXME: POSSIBLY make this static, as it is always constant
161 Type [] const_arg_types = new Type [2];
162 const_arg_types [0] = TypeManager.object_type;
163 const_arg_types [1] = TypeManager.intptr_type;
165 const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
166 MethodAttributes.HideBySig | MethodAttributes.Public;
168 ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
169 CallingConventions.Standard,
172 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
173 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
175 // HACK because System.Reflection.Emit is lame
177 Parameter [] fixed_pars = new Parameter [2];
178 fixed_pars [0] = new Parameter (TypeManager.object_type, "object",
179 Parameter.Modifier.NONE, null, Location);
180 fixed_pars [1] = new Parameter (TypeManager.intptr_type, "method",
181 Parameter.Modifier.NONE, null, Location);
182 Parameters const_parameters = new Parameters (fixed_pars);
183 const_parameters.Resolve (null);
185 TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
186 member_cache.AddMember (ConstructorBuilder, this);
188 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
191 // Here the various methods like Invoke, BeginInvoke etc are defined
193 // First, call the `out of band' special method for
194 // defining recursively any types we need:
196 if (!Parameters.Resolve (this))
203 // Check accessibility
204 foreach (Type partype in Parameters.Types){
205 if (!IsAccessibleAs (partype)) {
206 Report.SymbolRelatedToPreviousError (partype);
207 Report.Error (59, Location,
208 "Inconsistent accessibility: parameter type `" +
209 TypeManager.CSharpName (partype) + "' is less " +
210 "accessible than delegate `" + GetSignatureForError () + "'");
215 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
216 if (ReturnType == null)
219 ret_type = ReturnType.Type;
221 if (!IsAccessibleAs (ret_type)) {
222 Report.SymbolRelatedToPreviousError (ret_type);
223 Report.Error (58, Location,
224 "Inconsistent accessibility: return type `" +
225 TypeManager.CSharpName (ret_type) + "' is less " +
226 "accessible than delegate `" + GetSignatureForError () + "'");
230 CheckProtectedModifier ();
232 if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
233 Method.Error1599 (Location, ret_type);
238 // We don't have to check any others because they are all
239 // guaranteed to be accessible - they are standard types.
242 CallingConventions cc = Parameters.CallingConvention;
244 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
250 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
252 TypeManager.RegisterMethod (InvokeBuilder, Parameters);
253 member_cache.AddMember (InvokeBuilder, this);
255 if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null) {
256 DefineAsyncMethods (cc);
262 void DefineAsyncMethods (CallingConventions cc)
267 Parameters async_parameters = Parameters.MergeGenerated (Parameters,
268 new Parameter (TypeManager.asynccallback_type, "callback", Parameter.Modifier.NONE, null, Location),
269 new Parameter (TypeManager.object_type, "object", Parameter.Modifier.NONE, null, Location));
271 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
272 mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
274 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
275 TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
276 member_cache.AddMember (BeginInvokeBuilder, this);
279 // EndInvoke is a bit more interesting, all the parameters labeled as
280 // out or ref have to be duplicated here.
284 // Define parameters, and count out/ref parameters
286 Parameters end_parameters;
289 foreach (Parameter p in Parameters.FixedParameters) {
290 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
294 if (out_params > 0) {
295 Type [] end_param_types = new Type [out_params];
296 Parameter [] end_params = new Parameter [out_params];
299 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
300 Parameter p = Parameters.FixedParameters [i];
301 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
304 end_param_types [param] = p.ExternalType ();
305 end_params [param] = p;
308 end_parameters = Parameters.CreateFullyResolved (end_params, end_param_types);
310 end_parameters = Parameters.EmptyReadOnlyParameters;
313 end_parameters = Parameters.MergeGenerated (end_parameters,
314 new Parameter (TypeManager.iasyncresult_type, "result", Parameter.Modifier.NONE, null, Location));
317 // Create method, define parameters, register parameters with type system
319 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.Types);
320 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
322 end_parameters.ApplyAttributes (EndInvokeBuilder);
323 TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
324 member_cache.AddMember (EndInvokeBuilder, this);
327 public override void Emit ()
329 Parameters.ApplyAttributes (InvokeBuilder);
331 if (BeginInvokeBuilder != null) {
332 Parameters p = (Parameters) TypeManager.GetParameterData (BeginInvokeBuilder);
333 p.ApplyAttributes (BeginInvokeBuilder);
336 if (OptAttributes != null) {
337 OptAttributes.Emit ();
343 protected override TypeAttributes TypeAttr {
345 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
346 TypeAttributes.Class | TypeAttributes.Sealed |
351 public override string[] ValidAttributeTargets {
353 return attribute_targets;
358 protected override bool VerifyClsCompliance ()
360 if (!base.VerifyClsCompliance ()) {
364 Parameters.VerifyClsCompliance ();
366 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
367 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant", GetSignatureForError ());
373 public static ConstructorInfo GetConstructor (Type container_type, Type delegate_type)
375 Type dt = delegate_type;
377 Type[] g_args = null;
378 if (delegate_type.IsGenericType) {
379 g_args = delegate_type.GetGenericArguments ();
380 delegate_type = delegate_type.GetGenericTypeDefinition ();
384 Delegate d = TypeManager.LookupDelegate (delegate_type);
388 return TypeBuilder.GetConstructor (dt, d.ConstructorBuilder);
390 return d.ConstructorBuilder;
393 Expression ml = Expression.MemberLookup (container_type,
394 null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
395 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
397 MethodGroupExpr mg = ml as MethodGroupExpr;
399 Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
400 // FIXME: null will cause a crash later
404 return (ConstructorInfo) mg.Methods[0];
408 // Returns the MethodBase for "Invoke" from a delegate type, this is used
409 // to extract the signature of a delegate.
411 public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
413 Type dt = delegate_type;
415 Type[] g_args = null;
416 if (delegate_type.IsGenericType) {
417 g_args = delegate_type.GetGenericArguments ();
418 delegate_type = delegate_type.GetGenericTypeDefinition ();
421 Delegate d = TypeManager.LookupDelegate (delegate_type);
424 if (g_args != null) {
425 MethodInfo invoke = TypeBuilder.GetMethod (dt, d.InvokeBuilder);
427 Parameters p = (Parameters) d.Parameters.InflateTypes (g_args, g_args);
428 TypeManager.RegisterMethod (invoke, p);
433 return d.InvokeBuilder;
436 Expression ml = Expression.MemberLookup (container_type, null, dt,
437 "Invoke", Location.Null);
439 MethodGroupExpr mg = ml as MethodGroupExpr;
441 Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
442 // FIXME: null will cause a crash later
446 return (MethodInfo) mg.Methods[0];
449 public static bool IsTypeCovariant (Expression a, Type b)
451 Type a_type = a.Type;
455 if (RootContext.Version == LanguageVersion.ISO_1)
458 if (!TypeManager.IsReferenceType (a_type))
461 return Convert.ImplicitReferenceConversionExists (a, b);
465 /// Verifies whether the method in question is compatible with the delegate
466 /// Returns the method itself if okay and null if not.
468 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
469 MethodGroupExpr old_mg, MethodBase mb,
472 MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
473 if (invoke_mb == null)
476 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
479 if (old_mg.type_arguments == null &&
480 !TypeManager.InferTypeArguments (invoke_pd, ref mb))
484 ParameterData pd = TypeManager.GetParameterData (mb);
486 if (invoke_pd.Count != pd.Count)
489 for (int i = pd.Count; i > 0; ) {
492 Type invoke_pd_type = invoke_pd.ParameterType (i);
493 Type pd_type = pd.ParameterType (i);
494 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
495 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
497 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
498 pd_type_mod &= ~Parameter.Modifier.PARAMS;
500 if (invoke_pd_type_mod != pd_type_mod)
503 if (invoke_pd_type == pd_type)
506 //if (!IsTypeCovariant (invoke_pd_type, pd_type))
509 if (RootContext.Version == LanguageVersion.ISO_1)
513 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
514 Type mb_retval = ((MethodInfo) mb).ReturnType;
515 if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
518 //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
521 if (RootContext.Version == LanguageVersion.ISO_1)
528 // Verifies whether the invocation arguments are compatible with the
529 // delegate's target method
531 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
532 ArrayList args, Location loc)
539 arg_count = args.Count;
541 Expression ml = Expression.MemberLookup (
542 ec.ContainerType, delegate_type, "Invoke", loc);
544 MethodGroupExpr me = ml as MethodGroupExpr;
546 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
550 MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
551 ParameterData pd = TypeManager.GetParameterData (mb);
553 int pd_count = pd.Count;
555 bool params_method = pd.HasParams;
556 bool is_params_applicable = false;
557 me.DelegateType = delegate_type;
558 bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
560 if (!is_applicable && !params_method && arg_count != pd_count) {
561 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
562 TypeManager.CSharpName (delegate_type), arg_count.ToString ());
566 return me.VerifyArgumentsCompat (
567 ec, ref args, arg_count, mb,
568 is_params_applicable || (!is_applicable && params_method),
572 public static string FullDelegateDesc (MethodBase invoke_method)
574 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
577 public override MemberCache MemberCache {
583 public Expression InstanceExpression {
585 return instance_expr;
588 instance_expr = value;
592 public MethodBase TargetMethod {
594 return delegate_method;
597 delegate_method = value;
601 public Type TargetReturnType {
607 public override AttributeTargets AttributeTargets {
609 return AttributeTargets.Delegate;
614 // Represents header string for documentation comment.
616 public override string DocCommentHeader {
620 #region IMemberContainer Members
622 string IMemberContainer.Name
624 get { throw new NotImplementedException (); }
627 Type IMemberContainer.Type
629 get { throw new NotImplementedException (); }
632 MemberCache IMemberContainer.BaseCache
634 get { throw new NotImplementedException (); }
637 bool IMemberContainer.IsInterface {
643 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
645 throw new NotImplementedException ();
652 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
654 public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
656 protected ConstructorInfo constructor_method;
657 protected MethodInfo delegate_method;
658 // We keep this to handle IsBase only
659 protected MethodGroupExpr method_group;
660 protected Expression delegate_instance_expression;
662 public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
664 ParameterData pd = TypeManager.GetParameterData (invoke_method);
665 ArrayList delegate_arguments = new ArrayList (pd.Count);
666 for (int i = 0; i < pd.Count; ++i) {
667 Argument.AType atype_modifier;
668 Type atype = pd.Types [i];
669 switch (pd.ParameterModifier (i)) {
670 case Parameter.Modifier.REF:
671 atype_modifier = Argument.AType.Ref;
672 atype = atype.GetElementType ();
674 case Parameter.Modifier.OUT:
675 atype_modifier = Argument.AType.Out;
676 atype = atype.GetElementType ();
678 case Parameter.Modifier.ARGLIST:
679 // __arglist is not valid
680 throw new InternalErrorException ("__arglist modifier");
682 atype_modifier = Argument.AType.Expression;
685 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
687 return delegate_arguments;
690 public override Expression CreateExpressionTree (EmitContext ec)
692 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
694 ArrayList args = new ArrayList (3);
695 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
696 args.Add (new Argument (new NullLiteral (loc)));
697 args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
698 Expression e = new Invocation (ma, args).Resolve (ec);
702 e = Convert.ExplicitConversion (ec, e, type, loc);
706 return e.CreateExpressionTree (ec);
709 public override Expression DoResolve (EmitContext ec)
711 constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
713 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
714 method_group.DelegateType = type;
715 method_group.CustomErrorHandler = this;
717 ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
718 method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
719 if (method_group == null)
722 delegate_method = (MethodInfo) method_group;
723 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
725 delegate_instance_expression = emg.ExtensionExpression;
726 Type e_type = delegate_instance_expression.Type;
727 if (TypeManager.IsValueType (e_type)) {
728 Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
729 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
733 Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
734 Expression ret_expr = new TypeExpression (rt, loc);
735 if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
736 Error_ConversionFailed (ec, delegate_method, ret_expr);
739 DoResolveInstanceExpression (ec);
740 eclass = ExprClass.Value;
744 void DoResolveInstanceExpression (EmitContext ec)
747 // Argument is another delegate
749 if (delegate_instance_expression != null)
752 if (method_group.InstanceExpression != null)
753 delegate_instance_expression = method_group.InstanceExpression;
754 else if (!delegate_method.IsStatic && !ec.IsStatic)
755 delegate_instance_expression = ec.GetThis (loc);
757 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
758 delegate_instance_expression = new BoxedCast (
759 delegate_instance_expression, TypeManager.object_type);
762 public override void Emit (EmitContext ec)
764 if (delegate_instance_expression == null)
765 ec.ig.Emit (OpCodes.Ldnull);
767 delegate_instance_expression.Emit (ec);
769 if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
770 ec.ig.Emit (OpCodes.Dup);
771 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
773 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
774 ec.ig.Emit (OpCodes.Newobj, constructor_method);
777 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
779 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
780 string member_name = delegate_instance_expression != null ?
781 Delegate.FullDelegateDesc (method) :
782 TypeManager.GetFullNameSignature (method);
784 Report.SymbolRelatedToPreviousError (type);
785 Report.SymbolRelatedToPreviousError (method);
786 if (RootContext.Version == LanguageVersion.ISO_1) {
787 Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
788 TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
789 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
792 if (return_type == null) {
793 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
794 member_name, Delegate.FullDelegateDesc (invoke_method));
798 Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
799 return_type.GetSignatureForError (), member_name,
800 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
803 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
805 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
808 foreach (MethodInfo mi in mg.Methods){
809 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
816 #region IErrorHandler Members
818 public bool NoExactMatch (EmitContext ec, MethodBase method)
820 if (TypeManager.IsGenericMethod (method))
823 Error_ConversionFailed (ec, method, null);
831 // Created from the conversion code
833 public class ImplicitDelegateCreation : DelegateCreation
835 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
838 this.method_group = mg;
842 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
843 Type target_type, Location loc)
845 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
846 return d.DoResolve (ec);
851 // A delegate-creation-expression, invoked from the `New' class
853 public class NewDelegate : DelegateCreation
855 public ArrayList Arguments;
858 // This constructor is invoked from the `New' expression
860 public NewDelegate (Type type, ArrayList Arguments, Location loc)
863 this.Arguments = Arguments;
867 public override Expression DoResolve (EmitContext ec)
869 if (Arguments == null) {
870 Error_InvalidDelegateArgument ();
874 Argument a = (Argument) Arguments [0];
875 if (!a.ResolveMethodGroup (ec))
878 Expression e = a.Expr;
879 if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1) {
883 method_group = e as MethodGroupExpr;
884 if (method_group == null) {
885 if (!TypeManager.IsDelegateType (e.Type)) {
886 Report.Error (149, loc, "Method name expected");
891 // An argument is not a method but another delegate
893 delegate_instance_expression = e;
894 method_group = new MethodGroupExpr (new MemberInfo [] {
895 Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
898 if (base.DoResolve (ec) == null)
901 if (TypeManager.IsNullableType (method_group.DeclaringType)) {
902 Report.Error (1728, loc, "Cannot use method `{0}' as delegate creation expression because it is member of Nullable type",
903 TypeManager.GetFullNameSignature (delegate_method));
906 if (Invocation.IsMethodExcluded (delegate_method)) {
907 Report.SymbolRelatedToPreviousError (delegate_method);
908 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
909 TypeManager.CSharpSignature (delegate_method));
915 void Error_InvalidDelegateArgument ()
917 Report.Error (149, loc, "Method name expected");
921 public class DelegateInvocation : ExpressionStatement {
923 readonly Expression InstanceExpr;
924 readonly ArrayList Arguments;
928 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
930 this.InstanceExpr = instance_expr;
931 this.Arguments = args;
935 public override Expression CreateExpressionTree (EmitContext ec)
938 if (Arguments == null)
939 args = new ArrayList (1);
941 args = new ArrayList (Arguments.Count + 1);
943 args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
944 if (Arguments != null) {
945 foreach (Argument a in Arguments)
946 args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
949 return CreateExpressionFactoryCall ("Invoke", args);
952 public override Expression DoResolve (EmitContext ec)
954 if (InstanceExpr is EventExpr) {
955 ((EventExpr) InstanceExpr).Error_CannotAssign ();
959 Type del_type = InstanceExpr.Type;
960 if (del_type == null)
963 if (Arguments != null){
964 foreach (Argument a in Arguments){
965 if (!a.Resolve (ec, loc))
970 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
973 method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
974 type = TypeManager.TypeToCoreType (method.ReturnType);
975 eclass = ExprClass.Value;
980 public override void Emit (EmitContext ec)
983 // Invocation on delegates call the virtual Invoke member
984 // so we are always `instance' calls
986 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
989 public override void EmitStatement (EmitContext ec)
993 // Pop the return value if there is one
995 if (type != TypeManager.void_type)
996 ec.ig.Emit (OpCodes.Pop);
999 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1001 method = storey.MutateGenericMethod (method);
1003 if (Arguments != null) {
1004 foreach (Argument a in Arguments) {
1005 a.Expr.MutateHoistedGenericType (storey);
1009 InstanceExpr.MutateHoistedGenericType (storey);