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 // Licensed under the terms of the GNU GPL
11 // (C) 2001 Ximian, 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 {
27 public Expression ReturnType;
28 public Parameters Parameters;
30 public ConstructorBuilder ConstructorBuilder;
31 public MethodBuilder InvokeBuilder;
32 public MethodBuilder BeginInvokeBuilder;
33 public MethodBuilder EndInvokeBuilder;
37 static string[] attribute_targets = new string [] { "type", "return" };
39 Expression instance_expr;
40 MethodBase delegate_method;
41 ReturnParameter return_attributes;
43 const int AllowedModifiers =
51 public Delegate (NamespaceEntry ns, DeclSpace parent, Expression type,
52 int mod_flags, MemberName name, Parameters param_list,
54 : base (ns, parent, name, attrs)
57 this.ReturnType = type;
58 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
59 IsTopLevel ? Modifiers.INTERNAL :
60 Modifiers.PRIVATE, name.Location);
61 Parameters = param_list;
64 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
66 if (a.Target == AttributeTargets.ReturnValue) {
67 if (return_attributes == null)
68 return_attributes = new ReturnParameter (InvokeBuilder, Location);
70 return_attributes.ApplyAttributeBuilder (a, cb);
74 base.ApplyAttributeBuilder (a, cb);
77 public override TypeBuilder DefineType ()
79 if (TypeBuilder != null)
82 if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
83 Namespace system = RootNamespace.Global.GetNamespace ("System", true);
84 TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
85 TypeManager.multicast_delegate_type = expr.Type;
88 if (TypeManager.multicast_delegate_type == null)
89 Report.Error (-100, Location, "Internal error: delegate used before " +
90 "System.MulticastDelegate is resolved. This can only " +
91 "happen during corlib compilation, when using a delegate " +
92 "in any of the `core' classes. See bug #72015 for details.");
95 if (TypeManager.NamespaceClash (Name, Location))
98 ModuleBuilder builder = CodeGen.Module.Builder;
100 TypeBuilder = builder.DefineType (
101 Name, TypeAttr, TypeManager.multicast_delegate_type);
103 TypeBuilder builder = Parent.TypeBuilder;
105 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
106 TypeBuilder = builder.DefineNestedType (
107 name, TypeAttr, TypeManager.multicast_delegate_type);
110 TypeManager.AddUserType (this);
114 string[] param_names = new string [TypeParameters.Length];
115 for (int i = 0; i < TypeParameters.Length; i++)
116 param_names [i] = TypeParameters [i].Name;
118 GenericTypeParameterBuilder[] gen_params;
119 gen_params = TypeBuilder.DefineGenericParameters (param_names);
121 int offset = CountTypeParameters - CurrentTypeParameters.Length;
122 for (int i = offset; i < gen_params.Length; i++)
123 CurrentTypeParameters [i - offset].Define (gen_params [i]);
125 foreach (TypeParameter type_param in CurrentTypeParameters) {
126 if (!type_param.Resolve (this))
130 Expression current = new SimpleName (
131 MemberName.Basename, TypeParameters, Location);
132 current = current.ResolveAsTypeTerminal (this, false);
136 CurrentType = current.Type;
143 public override bool Define ()
147 foreach (TypeParameter type_param in TypeParameters) {
148 if (!type_param.Resolve (this))
152 foreach (TypeParameter type_param in TypeParameters) {
153 if (!type_param.DefineType (this))
157 foreach (TypeParameter type_param in TypeParameters) {
158 if (!type_param.CheckDependencies ())
164 // FIXME: POSSIBLY make this static, as it is always constant
166 Type [] const_arg_types = new Type [2];
167 const_arg_types [0] = TypeManager.object_type;
168 const_arg_types [1] = TypeManager.intptr_type;
170 const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
171 MethodAttributes.HideBySig | MethodAttributes.Public;
173 ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
174 CallingConventions.Standard,
177 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
178 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
180 // HACK because System.Reflection.Emit is lame
182 Parameter [] fixed_pars = new Parameter [2];
183 fixed_pars [0] = new Parameter (TypeManager.object_type, "object",
184 Parameter.Modifier.NONE, null, Location);
185 fixed_pars [1] = new Parameter (TypeManager.intptr_type, "method",
186 Parameter.Modifier.NONE, null, Location);
187 Parameters const_parameters = new Parameters (fixed_pars);
188 const_parameters.Resolve (null);
190 TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
193 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
196 // Here the various methods like Invoke, BeginInvoke etc are defined
198 // First, call the `out of band' special method for
199 // defining recursively any types we need:
201 if (!Parameters.Resolve (this))
208 // Check accessibility
209 foreach (Type partype in Parameters.Types){
210 if (!Parent.AsAccessible (partype, ModFlags)) {
211 Report.Error (59, Location,
212 "Inconsistent accessibility: parameter type `" +
213 TypeManager.CSharpName (partype) + "' is less " +
214 "accessible than delegate `" + Name + "'");
219 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
220 if (ReturnType == null)
223 ret_type = ReturnType.Type;
225 if (!Parent.AsAccessible (ret_type, ModFlags)) {
226 Report.Error (58, Location,
227 "Inconsistent accessibility: return type `" +
228 TypeManager.CSharpName (ret_type) + "' is less " +
229 "accessible than delegate `" + Name + "'");
233 if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
234 Method.Error1599 (Location, ret_type);
239 // We don't have to check any others because they are all
240 // guaranteed to be accessible - they are standard types.
243 CallingConventions cc = Parameters.CallingConvention;
245 const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
247 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
253 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
255 TypeManager.RegisterMethod (InvokeBuilder, Parameters);
261 Parameters async_parameters = Parameters.MergeGenerated (Parameters,
262 new Parameter (TypeManager.asynccallback_type, "callback", Parameter.Modifier.NONE, null, Location),
263 new Parameter (TypeManager.object_type, "object", Parameter.Modifier.NONE, null, Location));
265 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
266 mattr, cc, TypeManager.iasyncresult_type, async_parameters.Types);
268 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
269 TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
272 // EndInvoke is a bit more interesting, all the parameters labeled as
273 // out or ref have to be duplicated here.
277 // Define parameters, and count out/ref parameters
279 Parameters end_parameters;
282 foreach (Parameter p in Parameters.FixedParameters) {
283 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
287 if (out_params > 0) {
288 Type [] end_param_types = new Type [out_params];
289 Parameter [] end_params = new Parameter [out_params ];
292 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
293 Parameter p = Parameters.FixedParameters [i];
294 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
297 end_param_types [param] = p.ExternalType();
298 end_params [param] = p;
301 end_parameters = Parameters.CreateFullyResolved (end_params, end_param_types);
304 end_parameters = Parameters.EmptyReadOnlyParameters;
307 end_parameters = Parameters.MergeGenerated (end_parameters,
308 new Parameter (TypeManager.iasyncresult_type, "result", Parameter.Modifier.NONE, null, Location));
311 // Create method, define parameters, register parameters with type system
313 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.Types);
314 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
316 end_parameters.ApplyAttributes (EndInvokeBuilder);
317 TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
322 public override void Emit ()
324 Parameters.ApplyAttributes (InvokeBuilder);
326 Parameters p = (Parameters)TypeManager.GetParameterData (BeginInvokeBuilder);
327 p.ApplyAttributes (BeginInvokeBuilder);
329 if (OptAttributes != null) {
330 OptAttributes.Emit ();
336 protected override TypeAttributes TypeAttr {
338 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
339 TypeAttributes.Class | TypeAttributes.Sealed |
344 public override string[] ValidAttributeTargets {
346 return attribute_targets;
351 protected override bool VerifyClsCompliance ()
353 if (!base.VerifyClsCompliance ()) {
357 Parameters.VerifyClsCompliance ();
359 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
360 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant", GetSignatureForError ());
366 public static ConstructorInfo GetConstructor (Type containerType, Type delegateType)
368 Type dt = delegateType;
370 Type[] g_args = null;
371 if (delegateType.IsGenericType) {
372 g_args = delegateType.GetGenericArguments ();
373 delegateType = delegateType.GetGenericTypeDefinition ();
377 Delegate d = TypeManager.LookupDelegate (delegateType);
381 return TypeBuilder.GetConstructor (dt, d.ConstructorBuilder);
383 return d.ConstructorBuilder;
386 Expression ml = Expression.MemberLookup (containerType,
387 null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
388 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
390 MethodGroupExpr mg = ml as MethodGroupExpr;
392 Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
393 // FIXME: null will cause a crash later
397 return (ConstructorInfo) mg.Methods[0];
401 // Returns the MethodBase for "Invoke" from a delegate type, this is used
402 // to extract the signature of a delegate.
404 public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
406 Type dt = delegate_type;
408 Type[] g_args = null;
409 if (delegate_type.IsGenericType) {
410 g_args = delegate_type.GetGenericArguments ();
411 delegate_type = delegate_type.GetGenericTypeDefinition ();
414 Delegate d = TypeManager.LookupDelegate (delegate_type);
417 if (g_args != null) {
418 MethodInfo invoke = TypeBuilder.GetMethod (dt, d.InvokeBuilder);
420 Parameters p = (Parameters) d.Parameters.InflateTypes (g_args, g_args);
421 TypeManager.RegisterMethod (invoke, p);
426 return d.InvokeBuilder;
429 Expression ml = Expression.MemberLookup (container_type, null, dt,
430 "Invoke", Location.Null);
432 MethodGroupExpr mg = ml as MethodGroupExpr;
434 Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
435 // FIXME: null will cause a crash later
439 return (MethodInfo) mg.Methods[0];
443 /// Verifies whether the method in question is compatible with the delegate
444 /// Returns the method itself if okay and null if not.
446 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
447 MethodGroupExpr old_mg, MethodBase mb,
450 MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
451 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
454 if (!old_mg.HasTypeArguments &&
455 !TypeManager.InferTypeArguments (invoke_pd, ref mb))
459 ParameterData pd = TypeManager.GetParameterData (mb);
461 if (invoke_pd.Count != pd.Count)
464 for (int i = pd.Count; i > 0; ) {
467 Type invoke_pd_type = invoke_pd.ParameterType (i);
468 Type pd_type = pd.ParameterType (i);
469 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
470 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
472 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
473 pd_type_mod &= ~Parameter.Modifier.PARAMS;
475 if (invoke_pd_type_mod != pd_type_mod)
478 if (invoke_pd_type == pd_type)
481 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (invoke_pd_type), pd_type))
484 if (RootContext.Version == LanguageVersion.ISO_1)
488 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
489 Type mb_retval = ((MethodInfo) mb).ReturnType;
490 if (invoke_mb_retval == mb_retval)
493 if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (mb_retval), invoke_mb_retval))
496 if (RootContext.Version == LanguageVersion.ISO_1)
503 // Verifies whether the invocation arguments are compatible with the
504 // delegate's target method
506 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
507 ArrayList args, Location loc)
514 arg_count = args.Count;
516 Expression ml = Expression.MemberLookup (
517 ec.ContainerType, delegate_type, "Invoke", loc);
519 MethodGroupExpr me = ml as MethodGroupExpr;
521 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
525 MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
526 ParameterData pd = TypeManager.GetParameterData (mb);
528 int pd_count = pd.Count;
530 bool params_method = pd.HasParams;
531 bool is_params_applicable = false;
532 bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb) == 0;
534 if (!is_applicable && params_method &&
535 me.IsParamsMethodApplicable (ec, args, arg_count, ref mb))
536 is_applicable = is_params_applicable = true;
538 if (!is_applicable && !params_method && arg_count != pd_count) {
539 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
540 TypeManager.CSharpName (delegate_type), arg_count.ToString ());
544 return me.VerifyArgumentsCompat (
545 ec, args, arg_count, mb,
546 is_params_applicable || (!is_applicable && params_method),
547 delegate_type, false, loc);
551 /// Verifies whether the delegate in question is compatible with this one in
552 /// order to determine if instantiation from the same is possible.
554 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Location loc)
556 Expression ml = Expression.MemberLookup (
557 ec.ContainerType, delegate_type, "Invoke", loc);
559 if (!(ml is MethodGroupExpr)) {
560 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
564 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
565 ParameterData pd = TypeManager.GetParameterData (mb);
567 Expression probe_ml = Expression.MemberLookup (
568 ec.ContainerType, delegate_type, "Invoke", loc);
570 if (!(probe_ml is MethodGroupExpr)) {
571 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
575 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
576 ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
578 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
581 if (pd.Count != probe_pd.Count)
584 for (int i = pd.Count; i > 0; ) {
587 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
588 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
595 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
597 StringBuilder sb = new StringBuilder ();
598 sb.Append (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
600 sb.Append (TypeManager.CSharpName (del_type));
601 sb.Append (pd.GetSignatureForError ());
602 return sb.ToString ();
605 // Hack around System.Reflection as found everywhere else
606 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
607 MemberFilter filter, object criteria)
609 ArrayList members = new ArrayList (2);
611 if ((mt & MemberTypes.Constructor) != 0) {
612 if (ConstructorBuilder != null && filter (ConstructorBuilder, criteria))
613 members.Add (ConstructorBuilder);
616 if ((mt & MemberTypes.Method) != 0) {
617 if (InvokeBuilder != null)
618 if (filter (InvokeBuilder, criteria))
619 members.Add (InvokeBuilder);
621 if (BeginInvokeBuilder != null)
622 if (filter (BeginInvokeBuilder, criteria))
623 members.Add (BeginInvokeBuilder);
625 if (EndInvokeBuilder != null)
626 if (filter (EndInvokeBuilder, criteria))
627 members.Add (EndInvokeBuilder);
630 return new MemberList (members);
633 public override MemberCache MemberCache {
639 public Expression InstanceExpression {
641 return instance_expr;
644 instance_expr = value;
648 public MethodBase TargetMethod {
650 return delegate_method;
653 delegate_method = value;
657 public Type TargetReturnType {
663 public override AttributeTargets AttributeTargets {
665 return AttributeTargets.Delegate;
670 // Represents header string for documentation comment.
672 public override string DocCommentHeader {
678 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
680 public abstract class DelegateCreation : Expression {
681 protected ConstructorInfo constructor_method;
682 protected MethodBase delegate_method;
683 // We keep this to handle IsBase only
684 protected MethodGroupExpr method_group;
685 protected Expression delegate_instance_expression;
687 protected DelegateCreation () {}
689 static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
692 MethodBase found_method = mg.Methods [0];
694 if (mg.Methods.Length > 1)
695 method_desc = found_method.Name;
697 method_desc = Invocation.FullMethodDesc (found_method);
699 MethodInfo method = Delegate.GetInvokeMethod (ec.ContainerType, type);
700 ParameterData param = TypeManager.GetParameterData (method);
702 string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
705 if (!mg.HasTypeArguments &&
706 !TypeManager.InferTypeArguments (param, ref found_method)) {
707 Report.Error (411, loc, "The type arguments for " +
708 "method `{0}' cannot be inferred from " +
709 "the usage. Try specifying the type " +
710 "arguments explicitly.", method_desc);
714 Report.SymbolRelatedToPreviousError (found_method);
716 if (RootContext.Version == LanguageVersion.ISO_1) {
717 Report.Error (410, loc, "The method `{0}' parameters and return type must be same as delegate `{1}' parameters and return type",
718 method_desc, delegate_desc);
722 Type delegateType = method.ReturnType;
723 Type methodType = ((MethodInfo) found_method).ReturnType;
724 if (delegateType != methodType &&
725 !Convert.ImplicitReferenceConversionExists (new EmptyExpression (methodType), delegateType)) {
726 Report.Error (407, loc, "`{0}' has the wrong return type to match the delegate `{1}'", method_desc, delegate_desc);
728 Report.Error (123, loc, "The method `{0}' parameters do not match delegate `{1}' parameters",
729 TypeManager.CSharpSignature (found_method), delegate_desc);
733 public override void Emit (EmitContext ec)
735 if (delegate_instance_expression == null || delegate_method.IsStatic)
736 ec.ig.Emit (OpCodes.Ldnull);
738 delegate_instance_expression.Emit (ec);
740 if (delegate_method.IsVirtual && !method_group.IsBase) {
741 ec.ig.Emit (OpCodes.Dup);
742 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
744 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
745 ec.ig.Emit (OpCodes.Newobj, constructor_method);
748 protected bool ResolveConstructorMethod (EmitContext ec)
750 constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
754 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type targetType)
756 foreach (MethodInfo mi in mg.Methods){
757 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, targetType, mg, mi, Location.Null);
764 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
766 delegate_method = ImplicitStandardConversionExists (mg, type);
768 if (delegate_method == null) {
769 Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
774 // Check safe/unsafe of the delegate
777 ParameterData param = TypeManager.GetParameterData (delegate_method);
778 int count = param.Count;
780 for (int i = 0; i < count; i++){
781 if (param.ParameterType (i).IsPointer){
782 Expression.UnsafeError (loc);
788 //TODO: implement caching when performance will be low
789 IMethodData md = TypeManager.GetMethod (
790 TypeManager.DropGenericMethodArguments (delegate_method));
792 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
793 Report.SymbolRelatedToPreviousError (delegate_method);
794 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
798 md.SetMemberIsUsed ();
799 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type) != null) {
800 Report.SymbolRelatedToPreviousError (delegate_method);
801 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
806 if (mg.InstanceExpression != null)
807 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
808 else if (ec.IsStatic) {
809 if (!delegate_method.IsStatic) {
810 Report.Error (120, loc, "`{0}': An object reference is required for the nonstatic field, method or property",
811 TypeManager.CSharpSignature (delegate_method));
814 delegate_instance_expression = null;
816 delegate_instance_expression = ec.GetThis (loc);
818 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
819 delegate_instance_expression = new BoxedCast (
820 delegate_instance_expression, TypeManager.object_type);
823 eclass = ExprClass.Value;
829 // Created from the conversion code
831 public class ImplicitDelegateCreation : DelegateCreation {
833 ImplicitDelegateCreation (Type t, Location l)
839 public override Expression DoResolve (EmitContext ec)
844 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
845 Type target_type, Location loc)
847 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
848 if (!d.ResolveConstructorMethod (ec))
851 return d.ResolveMethodGroupExpr (ec, mge);
856 // A delegate-creation-expression, invoked from the `New' class
858 public class NewDelegate : DelegateCreation {
859 public ArrayList Arguments;
862 // This constructor is invoked from the `New' expression
864 public NewDelegate (Type type, ArrayList Arguments, Location loc)
867 this.Arguments = Arguments;
871 public override Expression DoResolve (EmitContext ec)
873 if (Arguments == null) {
874 Invocation.Error_WrongNumArguments (loc, GetSignatureForError (), 0);
878 if (!ResolveConstructorMethod (ec))
881 Argument a = (Argument) Arguments [0];
883 if (!a.ResolveMethodGroup (ec))
886 Expression e = a.Expr;
888 if (e is AnonymousMethodExpression && RootContext.Version != LanguageVersion.ISO_1)
889 return ((AnonymousMethodExpression) e).Compatible (ec, type).Resolve (ec);
891 MethodGroupExpr mg = e as MethodGroupExpr;
893 if (TypeManager.IsNullableType (mg.DeclaringType)) {
894 Report.Error (1728, loc, "Cannot use method `{0}' as delegate creation expression because it is member of Nullable type",
895 mg.GetSignatureForError ());
899 return ResolveMethodGroupExpr (ec, mg);
902 if (!TypeManager.IsDelegateType (e.Type)) {
903 Report.Error (149, loc, "Method name expected");
907 // This is what MS' compiler reports. We could always choose
908 // to be more verbose and actually give delegate-level specifics
909 if (!Delegate.VerifyDelegate (ec, type, loc)) {
910 Report.Error (29, loc, "Cannot implicitly convert type '" + e.Type + "' " +
911 "to type '" + type + "'");
915 delegate_instance_expression = e;
916 delegate_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
917 method_group = new MethodGroupExpr (new MemberInfo[] { delegate_method }, type, loc);
919 eclass = ExprClass.Value;
924 public class DelegateInvocation : ExpressionStatement {
926 readonly Expression InstanceExpr;
927 readonly ArrayList Arguments;
931 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
933 this.InstanceExpr = instance_expr;
934 this.Arguments = args;
938 public override Expression DoResolve (EmitContext ec)
940 if (InstanceExpr is EventExpr) {
942 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
944 Expression ml = MemberLookup (
945 ec.ContainerType, ec.ContainerType, ei.Name,
946 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
950 // If this is the case, then the Event does not belong
951 // to this Type and so, according to the spec
952 // cannot be accessed directly
954 // Note that target will not appear as an EventExpr
955 // in the case it is being referenced within the same type container;
956 // it will appear as a FieldExpr in that case.
959 Assign.error70 (ei, loc);
965 Type del_type = InstanceExpr.Type;
966 if (del_type == null)
969 if (Arguments != null){
970 foreach (Argument a in Arguments){
971 if (!a.Resolve (ec, loc))
976 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
979 method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
980 type = ((MethodInfo) method).ReturnType;
981 eclass = ExprClass.Value;
986 public override void Emit (EmitContext ec)
989 // Invocation on delegates call the virtual Invoke member
990 // so we are always `instance' calls
992 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
995 public override void EmitStatement (EmitContext ec)
999 // Pop the return value if there is one
1001 if (method is MethodInfo){
1002 Type ret = ((MethodInfo)method).ReturnType;
1003 if (TypeManager.TypeToCoreType (ret) != TypeManager.void_type)
1004 ec.ig.Emit (OpCodes.Pop);