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))
152 member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
154 // FIXME: POSSIBLY make this static, as it is always constant
156 Type [] const_arg_types = new Type [2];
157 const_arg_types [0] = TypeManager.object_type;
158 const_arg_types [1] = TypeManager.intptr_type;
160 const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
161 MethodAttributes.HideBySig | MethodAttributes.Public;
163 ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
164 CallingConventions.Standard,
167 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
168 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
170 // HACK because System.Reflection.Emit is lame
172 IParameterData [] fixed_pars = new IParameterData [] {
173 new ParameterData ("object", Parameter.Modifier.NONE),
174 new ParameterData ("method", Parameter.Modifier.NONE)
177 AParametersCollection const_parameters = new ParametersCollection (
179 new Type[] { TypeManager.object_type, TypeManager.intptr_type });
181 TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
182 member_cache.AddMember (ConstructorBuilder, this);
184 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
187 // Here the various methods like Invoke, BeginInvoke etc are defined
189 // First, call the `out of band' special method for
190 // defining recursively any types we need:
192 if (!Parameters.Resolve (this))
199 // Check accessibility
200 foreach (Type partype in Parameters.Types){
201 if (!IsAccessibleAs (partype)) {
202 Report.SymbolRelatedToPreviousError (partype);
203 Report.Error (59, Location,
204 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
205 TypeManager.CSharpName (partype),
206 GetSignatureForError ());
211 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
212 if (ReturnType == null)
215 ret_type = ReturnType.Type;
217 if (!IsAccessibleAs (ret_type)) {
218 Report.SymbolRelatedToPreviousError (ret_type);
219 Report.Error (58, Location,
220 "Inconsistent accessibility: return type `" +
221 TypeManager.CSharpName (ret_type) + "' is less " +
222 "accessible than delegate `" + GetSignatureForError () + "'");
226 CheckProtectedModifier ();
228 if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
229 Method.Error1599 (Location, ret_type);
234 // We don't have to check any others because they are all
235 // guaranteed to be accessible - they are standard types.
238 CallingConventions cc = Parameters.CallingConvention;
240 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
244 Parameters.GetEmitTypes ());
246 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
248 TypeManager.RegisterMethod (InvokeBuilder, Parameters);
249 member_cache.AddMember (InvokeBuilder, this);
251 if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null) {
252 DefineAsyncMethods (cc);
258 void DefineAsyncMethods (CallingConventions cc)
263 Parameters async_parameters = Parameters.MergeGenerated (Parameters, false,
265 new Parameter (null, "callback", Parameter.Modifier.NONE, null, Location),
266 new Parameter (null, "object", Parameter.Modifier.NONE, null, Location)
269 TypeManager.asynccallback_type,
270 TypeManager.object_type
274 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
275 mattr, cc, TypeManager.iasyncresult_type, async_parameters.GetEmitTypes ());
277 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
278 TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
279 member_cache.AddMember (BeginInvokeBuilder, this);
282 // EndInvoke is a bit more interesting, all the parameters labeled as
283 // out or ref have to be duplicated here.
287 // Define parameters, and count out/ref parameters
289 Parameters end_parameters;
292 foreach (Parameter p in Parameters.FixedParameters) {
293 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
297 if (out_params > 0) {
298 Type [] end_param_types = new Type [out_params];
299 Parameter[] end_params = new Parameter [out_params];
302 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
303 Parameter p = Parameters [i];
304 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
307 end_param_types [param] = Parameters.Types [i];
308 end_params [param] = p;
311 end_parameters = Parameters.CreateFullyResolved (end_params, end_param_types);
313 end_parameters = Parameters.EmptyReadOnlyParameters;
316 end_parameters = Parameters.MergeGenerated (end_parameters, false,
317 new Parameter (null, "result", Parameter.Modifier.NONE, null, Location), TypeManager.iasyncresult_type);
320 // Create method, define parameters, register parameters with type system
322 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.GetEmitTypes ());
323 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
325 end_parameters.ApplyAttributes (EndInvokeBuilder);
326 TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
327 member_cache.AddMember (EndInvokeBuilder, this);
330 public override void Emit ()
332 Parameters.ApplyAttributes (InvokeBuilder);
334 if (BeginInvokeBuilder != null) {
335 Parameters p = (Parameters) TypeManager.GetParameterData (BeginInvokeBuilder);
336 p.ApplyAttributes (BeginInvokeBuilder);
339 if (OptAttributes != null) {
340 OptAttributes.Emit ();
346 protected override TypeAttributes TypeAttr {
348 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
349 TypeAttributes.Class | TypeAttributes.Sealed |
354 public override string[] ValidAttributeTargets {
356 return attribute_targets;
361 protected override bool VerifyClsCompliance ()
363 if (!base.VerifyClsCompliance ()) {
367 Parameters.VerifyClsCompliance ();
369 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
370 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
371 GetSignatureForError ());
377 public static ConstructorInfo GetConstructor (Type container_type, Type delegate_type)
379 Type dt = delegate_type;
381 Type[] g_args = null;
382 if (delegate_type.IsGenericType) {
383 g_args = delegate_type.GetGenericArguments ();
384 delegate_type = delegate_type.GetGenericTypeDefinition ();
388 Delegate d = TypeManager.LookupDelegate (delegate_type);
392 return TypeBuilder.GetConstructor (dt, d.ConstructorBuilder);
394 return d.ConstructorBuilder;
397 Expression ml = Expression.MemberLookup (container_type,
398 null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
399 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
401 MethodGroupExpr mg = ml as MethodGroupExpr;
403 Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
404 // FIXME: null will cause a crash later
408 return (ConstructorInfo) mg.Methods[0];
412 // Returns the MethodBase for "Invoke" from a delegate type, this is used
413 // to extract the signature of a delegate.
415 public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
417 Type dt = delegate_type;
419 Type[] g_args = null;
420 if (delegate_type.IsGenericType) {
421 g_args = delegate_type.GetGenericArguments ();
422 delegate_type = delegate_type.GetGenericTypeDefinition ();
425 Delegate d = TypeManager.LookupDelegate (delegate_type);
428 if (g_args != null) {
429 MethodInfo invoke = TypeBuilder.GetMethod (dt, d.InvokeBuilder);
431 Parameters p = (Parameters) d.Parameters.InflateTypes (g_args, g_args);
432 TypeManager.RegisterMethod (invoke, p);
437 return d.InvokeBuilder;
440 Expression ml = Expression.MemberLookup (container_type, null, dt,
441 "Invoke", Location.Null);
443 MethodGroupExpr mg = ml as MethodGroupExpr;
445 Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
446 // FIXME: null will cause a crash later
450 return (MethodInfo) mg.Methods[0];
454 // 15.2 Delegate compatibility
456 public static bool IsTypeCovariant (Expression a, Type b)
459 // For each value parameter (a parameter with no ref or out modifier), an
460 // identity conversion or implicit reference conversion exists from the
461 // parameter type in D to the corresponding parameter type in M
466 if (RootContext.Version == LanguageVersion.ISO_1)
469 return Convert.ImplicitReferenceConversionExists (a, b);
473 /// Verifies whether the method in question is compatible with the delegate
474 /// Returns the method itself if okay and null if not.
476 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
477 MethodGroupExpr old_mg, MethodBase mb)
479 MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
480 if (invoke_mb == null)
483 AParametersCollection invoke_pd = TypeManager.GetParameterData (invoke_mb);
486 if (old_mg.type_arguments == null &&
487 !TypeManager.InferTypeArguments (invoke_pd, ref mb))
491 AParametersCollection pd = TypeManager.GetParameterData (mb);
493 if (invoke_pd.Count != pd.Count)
496 for (int i = pd.Count; i > 0; ) {
499 Type invoke_pd_type = invoke_pd.Types [i];
500 Type pd_type = pd.Types [i];
501 Parameter.Modifier invoke_pd_type_mod = invoke_pd.FixedParameters [i].ModFlags;
502 Parameter.Modifier pd_type_mod = pd.FixedParameters [i].ModFlags;
504 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
505 pd_type_mod &= ~Parameter.Modifier.PARAMS;
507 if (invoke_pd_type_mod != pd_type_mod)
510 if (invoke_pd_type == pd_type)
513 //if (!IsTypeCovariant (invoke_pd_type, pd_type))
516 if (RootContext.Version == LanguageVersion.ISO_1)
520 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
521 Type mb_retval = ((MethodInfo) mb).ReturnType;
522 if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
525 //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
528 if (RootContext.Version == LanguageVersion.ISO_1)
535 // Verifies whether the invocation arguments are compatible with the
536 // delegate's target method
538 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
539 ArrayList args, Location loc)
546 arg_count = args.Count;
548 Expression ml = Expression.MemberLookup (
549 ec.ContainerType, delegate_type, "Invoke", loc);
551 MethodGroupExpr me = ml as MethodGroupExpr;
553 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
557 MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
558 AParametersCollection pd = TypeManager.GetParameterData (mb);
560 int pd_count = pd.Count;
562 bool params_method = pd.HasParams;
563 bool is_params_applicable = false;
564 me.DelegateType = delegate_type;
565 bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
567 if (!is_applicable && !params_method && arg_count != pd_count) {
568 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
569 TypeManager.CSharpName (delegate_type), arg_count.ToString ());
573 return me.VerifyArgumentsCompat (
574 ec, ref args, arg_count, mb,
575 is_params_applicable || (!is_applicable && params_method),
579 public static string FullDelegateDesc (MethodBase invoke_method)
581 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
584 public override MemberCache MemberCache {
590 public Expression InstanceExpression {
592 return instance_expr;
595 instance_expr = value;
599 public MethodBase TargetMethod {
601 return delegate_method;
604 delegate_method = value;
608 public Type TargetReturnType {
614 public override AttributeTargets AttributeTargets {
616 return AttributeTargets.Delegate;
621 // Represents header string for documentation comment.
623 public override string DocCommentHeader {
627 #region IMemberContainer Members
629 string IMemberContainer.Name
631 get { throw new NotImplementedException (); }
634 Type IMemberContainer.Type
636 get { throw new NotImplementedException (); }
639 MemberCache IMemberContainer.BaseCache
641 get { throw new NotImplementedException (); }
644 bool IMemberContainer.IsInterface {
650 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
652 throw new NotImplementedException ();
659 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
661 public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
663 protected ConstructorInfo constructor_method;
664 protected MethodInfo delegate_method;
665 // We keep this to handle IsBase only
666 protected MethodGroupExpr method_group;
667 protected Expression delegate_instance_expression;
669 public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
671 AParametersCollection pd = TypeManager.GetParameterData (invoke_method);
672 ArrayList delegate_arguments = new ArrayList (pd.Count);
673 for (int i = 0; i < pd.Count; ++i) {
674 Argument.AType atype_modifier;
675 Type atype = pd.Types [i];
676 switch (pd.FixedParameters [i].ModFlags) {
677 case Parameter.Modifier.REF:
678 atype_modifier = Argument.AType.Ref;
679 //atype = atype.GetElementType ();
681 case Parameter.Modifier.OUT:
682 atype_modifier = Argument.AType.Out;
683 //atype = atype.GetElementType ();
685 case Parameter.Modifier.ARGLIST:
686 // __arglist is not valid
687 throw new InternalErrorException ("__arglist modifier");
689 atype_modifier = Argument.AType.Expression;
692 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
694 return delegate_arguments;
697 public override Expression CreateExpressionTree (EmitContext ec)
699 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
701 ArrayList args = new ArrayList (3);
702 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
703 args.Add (new Argument (new NullLiteral (loc)));
704 args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
705 Expression e = new Invocation (ma, args).Resolve (ec);
709 e = Convert.ExplicitConversion (ec, e, type, loc);
713 return e.CreateExpressionTree (ec);
716 public override Expression DoResolve (EmitContext ec)
718 constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
720 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
721 method_group.DelegateType = type;
722 method_group.CustomErrorHandler = this;
724 ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
725 method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
726 if (method_group == null)
729 delegate_method = (MethodInfo) method_group;
731 if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
732 Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
733 TypeManager.GetFullNameSignature (delegate_method));
737 Invocation.IsSpecialMethodInvocation (delegate_method, loc);
739 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
741 delegate_instance_expression = emg.ExtensionExpression;
742 Type e_type = delegate_instance_expression.Type;
743 if (TypeManager.IsValueType (e_type)) {
744 Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
745 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
749 Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
750 Expression ret_expr = new TypeExpression (rt, loc);
751 if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
752 Error_ConversionFailed (ec, delegate_method, ret_expr);
755 if (Invocation.IsMethodExcluded (delegate_method, loc)) {
756 Report.SymbolRelatedToPreviousError (delegate_method);
757 MethodOrOperator m = TypeManager.GetMethod (delegate_method) as MethodOrOperator;
758 if (m != null && m.IsPartialDefinition) {
759 Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
760 TypeManager.CSharpSignature (delegate_method));
762 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
763 TypeManager.CSharpSignature (delegate_method));
767 DoResolveInstanceExpression (ec);
768 eclass = ExprClass.Value;
772 void DoResolveInstanceExpression (EmitContext ec)
775 // Argument is another delegate
777 if (delegate_instance_expression != null)
780 Expression instance = method_group.InstanceExpression;
781 if (instance != null && instance != EmptyExpression.Null) {
782 delegate_instance_expression = instance;
783 Type instance_type = delegate_instance_expression.Type;
784 if (TypeManager.IsValueType (instance_type) || TypeManager.IsGenericParameter (instance_type)) {
785 delegate_instance_expression = new BoxedCast (
786 delegate_instance_expression, TypeManager.object_type);
788 } else if (!delegate_method.IsStatic && !ec.IsStatic) {
789 delegate_instance_expression = ec.GetThis (loc);
793 public override void Emit (EmitContext ec)
795 if (delegate_instance_expression == null)
796 ec.ig.Emit (OpCodes.Ldnull);
798 delegate_instance_expression.Emit (ec);
800 if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
801 ec.ig.Emit (OpCodes.Dup);
802 ec.ig.Emit (OpCodes.Ldvirtftn, delegate_method);
804 ec.ig.Emit (OpCodes.Ldftn, delegate_method);
807 ec.ig.Emit (OpCodes.Newobj, constructor_method);
810 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
812 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
813 string member_name = delegate_instance_expression != null ?
814 Delegate.FullDelegateDesc (method) :
815 TypeManager.GetFullNameSignature (method);
817 Report.SymbolRelatedToPreviousError (type);
818 Report.SymbolRelatedToPreviousError (method);
819 if (RootContext.Version == LanguageVersion.ISO_1) {
820 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",
821 TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
822 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
825 if (return_type == null) {
826 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
827 member_name, Delegate.FullDelegateDesc (invoke_method));
831 Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
832 return_type.GetSignatureForError (), member_name,
833 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
836 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
838 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
841 foreach (MethodInfo mi in mg.Methods){
842 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi);
849 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
851 if (delegate_instance_expression != null)
852 delegate_instance_expression.MutateHoistedGenericType (storey);
854 delegate_method = storey.MutateGenericMethod (delegate_method);
855 constructor_method = storey.MutateConstructor (constructor_method);
858 #region IErrorHandler Members
860 public bool NoExactMatch (EmitContext ec, MethodBase method)
862 if (TypeManager.IsGenericMethod (method))
865 Error_ConversionFailed (ec, method, null);
873 // Created from the conversion code
875 public class ImplicitDelegateCreation : DelegateCreation
877 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
880 this.method_group = mg;
884 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
885 Type target_type, Location loc)
887 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
888 return d.DoResolve (ec);
893 // A delegate-creation-expression, invoked from the `New' class
895 public class NewDelegate : DelegateCreation
897 public ArrayList Arguments;
900 // This constructor is invoked from the `New' expression
902 public NewDelegate (Type type, ArrayList Arguments, Location loc)
905 this.Arguments = Arguments;
909 public override Expression DoResolve (EmitContext ec)
911 if (Arguments == null || Arguments.Count != 1) {
912 Error_InvalidDelegateArgument ();
916 Argument a = (Argument) Arguments [0];
917 if (!a.ResolveMethodGroup (ec))
920 Expression e = a.Expr;
922 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
923 if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
924 e = ame.Compatible (ec, type);
928 return e.Resolve (ec);
931 method_group = e as MethodGroupExpr;
932 if (method_group == null) {
933 if (!TypeManager.IsDelegateType (e.Type)) {
934 e.Error_UnexpectedKind (ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
939 // An argument is not a method but another delegate
941 delegate_instance_expression = e;
942 method_group = new MethodGroupExpr (new MemberInfo [] {
943 Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
946 return base.DoResolve (ec);
949 void Error_InvalidDelegateArgument ()
951 Report.Error (149, loc, "Method name expected");
955 public class DelegateInvocation : ExpressionStatement {
957 readonly Expression InstanceExpr;
958 readonly ArrayList Arguments;
962 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
964 this.InstanceExpr = instance_expr;
965 this.Arguments = args;
969 public override Expression CreateExpressionTree (EmitContext ec)
972 if (Arguments == null)
973 args = new ArrayList (1);
975 args = new ArrayList (Arguments.Count + 1);
977 args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
978 if (Arguments != null) {
979 foreach (Argument a in Arguments)
980 args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
983 return CreateExpressionFactoryCall ("Invoke", args);
986 public override Expression DoResolve (EmitContext ec)
988 if (InstanceExpr is EventExpr) {
989 ((EventExpr) InstanceExpr).Error_CannotAssign ();
993 Type del_type = InstanceExpr.Type;
994 if (del_type == null)
997 if (Arguments != null){
998 foreach (Argument a in Arguments){
999 if (!a.Resolve (ec, loc))
1004 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1007 method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
1008 type = TypeManager.TypeToCoreType (method.ReturnType);
1009 eclass = ExprClass.Value;
1014 public override void Emit (EmitContext ec)
1017 // Invocation on delegates call the virtual Invoke member
1018 // so we are always `instance' calls
1020 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
1023 public override void EmitStatement (EmitContext ec)
1027 // Pop the return value if there is one
1029 if (type != TypeManager.void_type)
1030 ec.ig.Emit (OpCodes.Pop);
1033 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1035 method = storey.MutateGenericMethod (method);
1036 type = storey.MutateType (type);
1038 if (Arguments != null) {
1039 foreach (Argument a in Arguments) {
1040 a.Expr.MutateHoistedGenericType (storey);
1044 InstanceExpr.MutateHoistedGenericType (storey);