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 (a.Type.IsValueType)
461 return Convert.ImplicitReferenceConversionCore (
466 /// Verifies whether the method in question is compatible with the delegate
467 /// Returns the method itself if okay and null if not.
469 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
470 MethodGroupExpr old_mg, MethodBase mb,
473 MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
474 if (invoke_mb == null)
477 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
480 if (old_mg.type_arguments == null &&
481 !TypeManager.InferTypeArguments (invoke_pd, ref mb))
485 ParameterData pd = TypeManager.GetParameterData (mb);
487 if (invoke_pd.Count != pd.Count)
490 for (int i = pd.Count; i > 0; ) {
493 Type invoke_pd_type = invoke_pd.ParameterType (i);
494 Type pd_type = pd.ParameterType (i);
495 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
496 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
498 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
499 pd_type_mod &= ~Parameter.Modifier.PARAMS;
501 if (invoke_pd_type_mod != pd_type_mod)
504 if (invoke_pd_type == pd_type)
507 //if (!IsTypeCovariant (invoke_pd_type, pd_type))
510 if (RootContext.Version == LanguageVersion.ISO_1)
514 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
515 Type mb_retval = ((MethodInfo) mb).ReturnType;
516 if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
519 //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
522 if (RootContext.Version == LanguageVersion.ISO_1)
529 // Verifies whether the invocation arguments are compatible with the
530 // delegate's target method
532 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
533 ArrayList args, Location loc)
540 arg_count = args.Count;
542 Expression ml = Expression.MemberLookup (
543 ec.ContainerType, delegate_type, "Invoke", loc);
545 MethodGroupExpr me = ml as MethodGroupExpr;
547 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
551 MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
552 ParameterData pd = TypeManager.GetParameterData (mb);
554 int pd_count = pd.Count;
556 bool params_method = pd.HasParams;
557 bool is_params_applicable = false;
558 me.DelegateType = delegate_type;
559 bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
561 if (!is_applicable && !params_method && arg_count != pd_count) {
562 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
563 TypeManager.CSharpName (delegate_type), arg_count.ToString ());
567 return me.VerifyArgumentsCompat (
568 ec, ref args, arg_count, mb,
569 is_params_applicable || (!is_applicable && params_method),
573 public static string FullDelegateDesc (MethodBase invoke_method)
575 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
578 public override MemberCache MemberCache {
584 public Expression InstanceExpression {
586 return instance_expr;
589 instance_expr = value;
593 public MethodBase TargetMethod {
595 return delegate_method;
598 delegate_method = value;
602 public Type TargetReturnType {
608 public override AttributeTargets AttributeTargets {
610 return AttributeTargets.Delegate;
615 // Represents header string for documentation comment.
617 public override string DocCommentHeader {
621 #region IMemberContainer Members
623 string IMemberContainer.Name
625 get { throw new NotImplementedException (); }
628 Type IMemberContainer.Type
630 get { throw new NotImplementedException (); }
633 MemberCache IMemberContainer.BaseCache
635 get { throw new NotImplementedException (); }
638 bool IMemberContainer.IsInterface {
644 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
646 throw new NotImplementedException ();
653 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
655 public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
657 protected ConstructorInfo constructor_method;
658 protected MethodInfo delegate_method;
659 // We keep this to handle IsBase only
660 protected MethodGroupExpr method_group;
661 protected Expression delegate_instance_expression;
663 public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
665 ParameterData pd = TypeManager.GetParameterData (invoke_method);
666 ArrayList delegate_arguments = new ArrayList (pd.Count);
667 for (int i = 0; i < pd.Count; ++i) {
668 Argument.AType atype_modifier;
669 Type atype = pd.Types [i];
670 switch (pd.ParameterModifier (i)) {
671 case Parameter.Modifier.REF:
672 atype_modifier = Argument.AType.Ref;
673 atype = atype.GetElementType ();
675 case Parameter.Modifier.OUT:
676 atype_modifier = Argument.AType.Out;
677 atype = atype.GetElementType ();
679 case Parameter.Modifier.ARGLIST:
680 // __arglist is not valid
681 throw new InternalErrorException ("__arglist modifier");
683 atype_modifier = Argument.AType.Expression;
686 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
688 return delegate_arguments;
691 public override Expression CreateExpressionTree (EmitContext ec)
693 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
695 ArrayList args = new ArrayList (3);
696 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
697 args.Add (new Argument (new NullLiteral (loc)));
698 args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
699 Expression e = new Invocation (ma, args).Resolve (ec);
703 e = Convert.ExplicitConversion (ec, e, type, loc);
707 return e.CreateExpressionTree (ec);
710 public override Expression DoResolve (EmitContext ec)
712 constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
714 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
715 method_group.DelegateType = type;
716 method_group.CustomErrorHandler = this;
718 ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
719 method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
720 if (method_group == null)
723 delegate_method = (MethodInfo) method_group;
724 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
726 delegate_instance_expression = emg.ExtensionExpression;
727 Type e_type = delegate_instance_expression.Type;
728 if (TypeManager.IsValueType (e_type)) {
729 Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
730 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
734 Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
735 Expression ret_expr = new TypeExpression (rt, loc);
736 if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
737 Error_ConversionFailed (ec, delegate_method, ret_expr);
740 DoResolveInstanceExpression (ec);
741 eclass = ExprClass.Value;
745 void DoResolveInstanceExpression (EmitContext ec)
748 // Argument is another delegate
750 if (delegate_instance_expression != null)
753 if (method_group.InstanceExpression != null)
754 delegate_instance_expression = method_group.InstanceExpression;
755 else if (!delegate_method.IsStatic && !ec.IsStatic)
756 delegate_instance_expression = ec.GetThis (loc);
758 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
759 delegate_instance_expression = new BoxedCast (
760 delegate_instance_expression, TypeManager.object_type);
763 public override void Emit (EmitContext ec)
765 if (delegate_instance_expression == null)
766 ec.ig.Emit (OpCodes.Ldnull);
768 delegate_instance_expression.Emit (ec);
770 if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
771 ec.ig.Emit (OpCodes.Dup);
772 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
774 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
775 ec.ig.Emit (OpCodes.Newobj, constructor_method);
778 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
780 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
781 string member_name = delegate_instance_expression != null ?
782 Delegate.FullDelegateDesc (method) :
783 TypeManager.GetFullNameSignature (method);
785 Report.SymbolRelatedToPreviousError (type);
786 Report.SymbolRelatedToPreviousError (method);
787 if (RootContext.Version == LanguageVersion.ISO_1) {
788 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",
789 TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
790 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
793 if (return_type == null) {
794 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
795 member_name, Delegate.FullDelegateDesc (invoke_method));
799 Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
800 return_type.GetSignatureForError (), member_name,
801 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
804 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
806 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
809 foreach (MethodInfo mi in mg.Methods){
810 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi, Location.Null);
817 #region IErrorHandler Members
819 public bool NoExactMatch (EmitContext ec, MethodBase method)
821 if (TypeManager.IsGenericMethod (method))
824 Error_ConversionFailed (ec, method, null);
832 // Created from the conversion code
834 public class ImplicitDelegateCreation : DelegateCreation
836 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
839 this.method_group = mg;
843 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
844 Type target_type, Location loc)
846 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
847 return d.DoResolve (ec);
852 // A delegate-creation-expression, invoked from the `New' class
854 public class NewDelegate : DelegateCreation
856 public ArrayList Arguments;
859 // This constructor is invoked from the `New' expression
861 public NewDelegate (Type type, ArrayList Arguments, Location loc)
864 this.Arguments = Arguments;
868 public override Expression DoResolve (EmitContext ec)
870 if (Arguments == null) {
871 Error_InvalidDelegateArgument ();
875 Argument a = (Argument) Arguments [0];
876 if (!a.ResolveMethodGroup (ec))
879 Expression e = a.Expr;
880 if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1) {
881 e = ((AnonymousMethodExpression) e).Compatible (ec, type);
884 return e.Resolve (ec);
887 method_group = e as MethodGroupExpr;
888 if (method_group == null) {
889 if (!TypeManager.IsDelegateType (e.Type)) {
890 Report.Error (149, loc, "Method name expected");
895 // An argument is not a method but another delegate
897 delegate_instance_expression = e;
898 method_group = new MethodGroupExpr (new MemberInfo [] {
899 Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
902 if (base.DoResolve (ec) == null)
905 if (TypeManager.IsNullableType (method_group.DeclaringType)) {
906 Report.Error (1728, loc, "Cannot use method `{0}' as delegate creation expression because it is member of Nullable type",
907 TypeManager.GetFullNameSignature (delegate_method));
910 if (Invocation.IsMethodExcluded (delegate_method)) {
911 Report.SymbolRelatedToPreviousError (delegate_method);
912 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
913 TypeManager.CSharpSignature (delegate_method));
919 void Error_InvalidDelegateArgument ()
921 Report.Error (149, loc, "Method name expected");
925 public class DelegateInvocation : ExpressionStatement {
927 readonly Expression InstanceExpr;
928 readonly ArrayList Arguments;
932 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
934 this.InstanceExpr = instance_expr;
935 this.Arguments = args;
939 public override Expression CreateExpressionTree (EmitContext ec)
942 if (Arguments == null)
943 args = new ArrayList (1);
945 args = new ArrayList (Arguments.Count + 1);
947 args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
948 if (Arguments != null) {
949 foreach (Argument a in Arguments)
950 args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
953 return CreateExpressionFactoryCall ("Invoke", args);
956 public override Expression DoResolve (EmitContext ec)
958 if (InstanceExpr is EventExpr) {
959 ((EventExpr) InstanceExpr).Error_CannotAssign ();
963 Type del_type = InstanceExpr.Type;
964 if (del_type == null)
967 if (Arguments != null){
968 foreach (Argument a in Arguments){
969 if (!a.Resolve (ec, loc))
974 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
977 method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
978 type = ((MethodInfo) method).ReturnType;
979 type = TypeManager.TypeToCoreType (type);
980 eclass = ExprClass.Value;
985 public override void Emit (EmitContext ec)
988 // Invocation on delegates call the virtual Invoke member
989 // so we are always `instance' calls
991 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
994 public override void EmitStatement (EmitContext ec)
998 // Pop the return value if there is one
1000 if (method is MethodInfo){
1001 Type ret = ((MethodInfo)method).ReturnType;
1002 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
1003 ec.ig.Emit (OpCodes.Pop);