2 // delegate.cs: Delegate Handler
5 // Ravi Pratap (ravi@ximian.com)
6 // Miguel de Icaza (miguel@ximian.com)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001 Ximian, Inc (http://www.ximian.com)
15 using System.Collections;
16 using System.Reflection;
17 using System.Reflection.Emit;
20 namespace Mono.CSharp {
25 public class Delegate : DeclSpace {
26 public Expression ReturnType;
27 public Parameters Parameters;
29 public ConstructorBuilder ConstructorBuilder;
30 public MethodBuilder InvokeBuilder;
31 public MethodBuilder BeginInvokeBuilder;
32 public MethodBuilder EndInvokeBuilder;
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, TypeContainer parent, Expression type,
52 int mod_flags, MemberName name, Parameters param_list,
53 Attributes attrs, Location l)
54 : base (ns, parent, name, attrs, l)
57 this.ReturnType = type;
58 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
59 IsTopLevel ? Modifiers.INTERNAL :
60 Modifiers.PRIVATE, l);
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 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
85 foreach (TypeParameter type_param in TypeParameters)
86 if (!type_param.Resolve (this))
90 TypeAttributes attr = Modifiers.TypeAttr (ModFlags, IsTopLevel) |
91 TypeAttributes.Class | TypeAttributes.Sealed;
94 if (TypeManager.NamespaceClash (Name, Location))
97 ModuleBuilder builder = CodeGen.Module.Builder;
99 TypeBuilder = builder.DefineType (
100 Name, attr, TypeManager.multicast_delegate_type);
102 TypeBuilder builder = Parent.TypeBuilder;
104 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
105 TypeBuilder = builder.DefineNestedType (
106 name, attr, TypeManager.multicast_delegate_type);
109 TypeManager.AddDelegateType (Name, TypeBuilder, this);
112 string[] param_names = new string [TypeParameters.Length];
113 for (int i = 0; i < TypeParameters.Length; i++)
114 param_names [i] = TypeParameters [i].Name;
116 GenericTypeParameterBuilder[] gen_params;
117 gen_params = TypeBuilder.DefineGenericParameters (param_names);
119 int offset = CountTypeParameters - CurrentTypeParameters.Length;
120 for (int i = offset; i < gen_params.Length; i++)
121 CurrentTypeParameters [i - offset].Define (gen_params [i]);
123 foreach (TypeParameter type_param in CurrentTypeParameters) {
124 if (!type_param.Resolve (this))
128 for (int i = offset; i < gen_params.Length; i++)
129 CurrentTypeParameters [i - offset].DefineConstraints ();
131 TypeExpr current = new ConstructedType (Name, TypeParameters, Location);
132 current = current.ResolveAsTypeTerminal (ec);
136 CurrentType = current.Type;
142 public override bool DefineMembers (TypeContainer container)
147 public override bool Define ()
149 MethodAttributes mattr;
151 ec = new EmitContext (this, this, Location, null, null, ModFlags, false);
154 foreach (TypeParameter type_param in TypeParameters)
155 type_param.DefineType (ec);
158 // FIXME: POSSIBLY make this static, as it is always constant
160 Type [] const_arg_types = new Type [2];
161 const_arg_types [0] = TypeManager.object_type;
162 const_arg_types [1] = TypeManager.intptr_type;
164 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
165 MethodAttributes.HideBySig | MethodAttributes.Public;
167 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
168 CallingConventions.Standard,
171 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
172 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
174 // HACK because System.Reflection.Emit is lame
177 // FIXME: POSSIBLY make these static, as they are always the same
178 Parameter [] fixed_pars = new Parameter [2];
179 fixed_pars [0] = new Parameter (TypeManager.system_object_expr, "object",
180 Parameter.Modifier.NONE, null);
181 fixed_pars [1] = new Parameter (TypeManager.system_intptr_expr, "method",
182 Parameter.Modifier.NONE, null);
183 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
185 TypeManager.RegisterMethod (
187 new InternalParameters (const_arg_types, const_parameters),
191 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
194 // Here the various methods like Invoke, BeginInvoke etc are defined
196 // First, call the `out of band' special method for
197 // defining recursively any types we need:
199 if (!Parameters.ComputeAndDefineParameterTypes (ec))
202 param_types = Parameters.GetParameterInfo (ec);
203 if (param_types == null)
210 // Check accessibility
211 foreach (Type partype in param_types){
212 if (!Parent.AsAccessible (partype, ModFlags)) {
213 Report.Error (59, Location,
214 "Inconsistent accessibility: parameter type `" +
215 TypeManager.CSharpName (partype) + "` is less " +
216 "accessible than delegate `" + Name + "'");
219 if (partype.IsPointer && !UnsafeOK (Parent))
223 ReturnType = ReturnType.ResolveAsTypeTerminal (ec);
224 if (ReturnType == null)
227 ret_type = ReturnType.Type;
228 if (ret_type == null)
231 if (!Parent.AsAccessible (ret_type, ModFlags)) {
232 Report.Error (58, Location,
233 "Inconsistent accessibility: return type `" +
234 TypeManager.CSharpName (ret_type) + "` is less " +
235 "accessible than delegate `" + Name + "'");
239 if (ret_type.IsPointer && !UnsafeOK (Parent))
243 // We don't have to check any others because they are all
244 // guaranteed to be accessible - they are standard types.
247 CallingConventions cc = Parameters.GetCallingConvention ();
249 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
251 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
258 // Define parameters, and count out/ref parameters
262 if (Parameters.FixedParameters != null){
263 int top = Parameters.FixedParameters.Length;
266 for (; i < top; i++) {
267 p = Parameters.FixedParameters [i];
268 p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
270 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
274 if (Parameters.ArrayParameter != null){
275 Parameter p = Parameters.ArrayParameter;
276 p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
279 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
281 TypeManager.RegisterMethod (InvokeBuilder,
282 new InternalParameters (param_types, Parameters),
288 int params_num = param_types.Length;
289 Type [] async_param_types = new Type [params_num + 2];
291 param_types.CopyTo (async_param_types, 0);
293 async_param_types [params_num] = TypeManager.asynccallback_type;
294 async_param_types [params_num + 1] = TypeManager.object_type;
296 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
297 MethodAttributes.Virtual | MethodAttributes.NewSlot;
299 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
302 TypeManager.iasyncresult_type,
306 if (Parameters.FixedParameters != null){
307 int top = Parameters.FixedParameters.Length;
310 for (i = 0 ; i < top; i++) {
311 p = Parameters.FixedParameters [i];
313 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
316 if (Parameters.ArrayParameter != null){
317 Parameter p = Parameters.ArrayParameter;
318 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
323 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
324 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
326 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
328 Parameter [] async_params = new Parameter [params_num + 2];
330 if (Parameters.FixedParameters != null){
331 Parameters.FixedParameters.CopyTo (async_params, 0);
332 n = Parameters.FixedParameters.Length;
334 if (Parameters.ArrayParameter != null)
335 async_params [n] = Parameters.ArrayParameter;
337 async_params [params_num] = new Parameter (
338 TypeManager.system_asynccallback_expr, "callback",
339 Parameter.Modifier.NONE, null);
340 async_params [params_num + 1] = new Parameter (
341 TypeManager.system_object_expr, "object",
342 Parameter.Modifier.NONE, null);
344 Parameters async_parameters = new Parameters (async_params, null, Location);
345 async_parameters.ComputeAndDefineParameterTypes (ec);
347 TypeManager.RegisterMethod (BeginInvokeBuilder,
348 new InternalParameters (async_param_types, async_parameters),
352 // EndInvoke is a bit more interesting, all the parameters labeled as
353 // out or ref have to be duplicated here.
356 Type [] end_param_types = new Type [out_params + 1];
357 Parameter [] end_params = new Parameter [out_params + 1];
360 int top = Parameters.FixedParameters.Length;
361 for (i = 0; i < top; i++){
362 Parameter p = Parameters.FixedParameters [i];
363 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
366 end_param_types [param] = param_types [i];
367 end_params [param] = p;
371 end_param_types [out_params] = TypeManager.iasyncresult_type;
372 end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null);
375 // Create method, define parameters, register parameters with type system
377 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
378 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
381 // EndInvoke: Label the parameters
383 EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
384 for (i = 0; i < end_params.Length-1; i++){
385 EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
388 Parameters end_parameters = new Parameters (end_params, null, Location);
389 end_parameters.ComputeAndDefineParameterTypes (ec);
391 TypeManager.RegisterMethod (
393 new InternalParameters (end_param_types, end_parameters),
399 public override void Emit ()
401 if (OptAttributes != null) {
402 Parameters.LabelParameters (ec, InvokeBuilder, Location);
403 OptAttributes.Emit (ec, this);
409 public override string[] ValidAttributeTargets {
411 return attribute_targets;
416 protected override bool VerifyClsCompliance (DeclSpace ds)
418 if (!base.VerifyClsCompliance (ds)) {
422 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
424 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
425 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
431 // Returns the MethodBase for "Invoke" from a delegate type, this is used
432 // to extract the signature of a delegate.
434 public static MethodGroupExpr GetInvokeMethod (EmitContext ec, Type delegate_type,
437 Expression ml = Expression.MemberLookup (
438 ec, delegate_type, "Invoke", loc);
440 MethodGroupExpr mg = ml as MethodGroupExpr;
442 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
450 /// Verifies whether the method in question is compatible with the delegate
451 /// Returns the method itself if okay and null if not.
453 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
456 MethodGroupExpr mg = GetInvokeMethod (ec, delegate_type, loc);
460 MethodBase invoke_mb = mg.Methods [0];
461 ParameterData invoke_pd = Invocation.GetParameterData (invoke_mb);
463 if (!mg.HasTypeArguments &&
464 !TypeManager.InferTypeArguments (ec, invoke_pd, ref mb))
467 ParameterData pd = Invocation.GetParameterData (mb);
468 int pd_count = pd.Count;
470 if (invoke_pd.Count != pd_count)
473 for (int i = pd_count; i > 0; ) {
476 Type invoke_pd_type = invoke_pd.ParameterType (i);
477 Type pd_type = pd.ParameterType (i);
478 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
479 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
481 if (invoke_pd_type == pd_type &&
482 invoke_pd_type_mod == pd_type_mod)
485 if (invoke_pd_type.IsSubclassOf (pd_type) &&
486 invoke_pd_type_mod == pd_type_mod)
487 if (RootContext.Version == LanguageVersion.ISO_1) {
488 Report.FeatureIsNotStandardized (loc, "contravariance");
496 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
497 Type mb_retval = ((MethodInfo) mb).ReturnType;
498 if (invoke_mb_retval == mb_retval)
501 if (mb_retval.IsSubclassOf (invoke_mb_retval))
502 if (RootContext.Version == LanguageVersion.ISO_1) {
503 Report.FeatureIsNotStandardized (loc, "covariance");
513 // Verifies whether the invocation arguments are compatible with the
514 // delegate's target method
516 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
517 ArrayList args, Location loc)
524 arg_count = args.Count;
526 Expression ml = Expression.MemberLookup (
527 ec, delegate_type, "Invoke", loc);
529 if (!(ml is MethodGroupExpr)) {
530 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
534 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
535 ParameterData pd = Invocation.GetParameterData (mb);
537 int pd_count = pd.Count;
539 bool params_method = (pd_count != 0) &&
540 (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);
542 if (!params_method && pd_count != arg_count) {
543 Report.Error (1593, loc,
544 "Delegate '{0}' does not take {1} arguments",
545 delegate_type.ToString (), arg_count);
550 // Consider the case:
551 // delegate void FOO(param object[] args);
552 // FOO f = new FOO(...);
553 // f(new object[] {1, 2, 3});
555 // This should be treated like f(1,2,3). This is done by ignoring the
556 // 'param' modifier for that invocation. If that fails, then the
557 // 'param' modifier is considered.
559 // One issue is that 'VerifyArgumentsCompat' modifies the elements of
560 // the 'args' array. However, the modifications appear idempotent.
561 // Normal 'Invocation's also have the same behaviour, implicitly.
565 if (arg_count == pd_count)
566 ans = Invocation.VerifyArgumentsCompat (
567 ec, args, arg_count, mb, false,
568 delegate_type, false, loc);
569 if (!ans && params_method)
570 ans = Invocation.VerifyArgumentsCompat (
571 ec, args, arg_count, mb, true,
572 delegate_type, false, loc);
577 /// Verifies whether the delegate in question is compatible with this one in
578 /// order to determine if instantiation from the same is possible.
580 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
582 Expression ml = Expression.MemberLookup (
583 ec, delegate_type, "Invoke", loc);
585 if (!(ml is MethodGroupExpr)) {
586 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
590 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
591 ParameterData pd = Invocation.GetParameterData (mb);
593 Expression probe_ml = Expression.MemberLookup (
594 ec, delegate_type, "Invoke", loc);
596 if (!(probe_ml is MethodGroupExpr)) {
597 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
601 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
602 ParameterData probe_pd = Invocation.GetParameterData (probe_mb);
604 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
607 if (pd.Count != probe_pd.Count)
610 for (int i = pd.Count; i > 0; ) {
613 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
614 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
621 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
623 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
625 sb.Append (" " + del_type.ToString ());
628 int length = pd.Count;
630 for (int i = length; i > 0; ) {
633 sb.Append (pd.ParameterDesc (length - i - 1));
639 return sb.ToString ();
643 // Hack around System.Reflection as found everywhere else
644 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
645 MemberFilter filter, object criteria)
647 ArrayList members = new ArrayList ();
649 if ((mt & MemberTypes.Method) != 0) {
650 if (ConstructorBuilder != null)
651 if (filter (ConstructorBuilder, criteria))
652 members.Add (ConstructorBuilder);
654 if (InvokeBuilder != null)
655 if (filter (InvokeBuilder, criteria))
656 members.Add (InvokeBuilder);
658 if (BeginInvokeBuilder != null)
659 if (filter (BeginInvokeBuilder, criteria))
660 members.Add (BeginInvokeBuilder);
662 if (EndInvokeBuilder != null)
663 if (filter (EndInvokeBuilder, criteria))
664 members.Add (EndInvokeBuilder);
667 return new MemberList (members);
670 public override MemberCache MemberCache {
676 public Expression InstanceExpression {
678 return instance_expr;
681 instance_expr = value;
685 public MethodBase TargetMethod {
687 return delegate_method;
690 delegate_method = value;
694 public Type TargetReturnType {
700 public Type [] ParameterTypes {
706 public override AttributeTargets AttributeTargets {
708 return AttributeTargets.Delegate;
713 // Represents header string for documentation comment.
715 public override string DocCommentHeader {
719 protected override void VerifyObsoleteAttribute()
721 CheckUsageOfObsoleteAttribute (ret_type);
723 foreach (Type type in param_types) {
724 CheckUsageOfObsoleteAttribute (type);
730 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
732 public abstract class DelegateCreation : Expression {
733 protected MethodBase constructor_method;
734 protected MethodBase delegate_method;
735 protected MethodGroupExpr method_group;
736 protected Expression delegate_instance_expression;
738 public DelegateCreation () {}
740 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
744 MethodBase candidate = mg.Methods [0];
745 if (mg.Methods.Length > 1)
746 method_desc = candidate.Name;
748 method_desc = Invocation.FullMethodDesc (candidate);
750 Expression invoke_method = Expression.MemberLookup (
751 ec, type, "Invoke", MemberTypes.Method,
752 Expression.AllBindingFlags, loc);
753 MethodBase method = ((MethodGroupExpr) invoke_method).Methods [0];
754 ParameterData param = Invocation.GetParameterData (method);
755 string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
757 if (!mg.HasTypeArguments &&
758 !TypeManager.InferTypeArguments (ec, param, ref candidate))
759 Report.Error (411, loc, "The type arguments for " +
760 "method `{0}' cannot be infered from " +
761 "the usage. Try specifying the type " +
762 "arguments explicitly.", method_desc);
764 Report.Error (123, loc, "Method '{0}' does not " +
765 "match delegate '{1}'", method_desc,
769 public override void Emit (EmitContext ec)
771 if (delegate_instance_expression == null || delegate_method.IsStatic)
772 ec.ig.Emit (OpCodes.Ldnull);
774 delegate_instance_expression.Emit (ec);
776 if (delegate_method.IsVirtual && !method_group.IsBase) {
777 ec.ig.Emit (OpCodes.Dup);
778 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
780 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
781 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
784 protected bool ResolveConstructorMethod (EmitContext ec)
786 Expression ml = Expression.MemberLookup (
787 ec, type, ".ctor", loc);
789 if (!(ml is MethodGroupExpr)) {
790 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
794 constructor_method = ((MethodGroupExpr) ml).Methods [0];
798 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
800 foreach (MethodInfo mi in mg.Methods){
801 delegate_method = Delegate.VerifyMethod (
804 if (delegate_method != null)
808 if (delegate_method == null) {
809 Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
814 // Check safe/unsafe of the delegate
817 ParameterData param = Invocation.GetParameterData (delegate_method);
818 int count = param.Count;
820 for (int i = 0; i < count; i++){
821 if (param.ParameterType (i).IsPointer){
822 Expression.UnsafeError (loc);
828 //TODO: implement caching when performance will be low
829 IMethodData md = TypeManager.GetMethod (delegate_method);
831 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
832 Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
835 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
836 Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
840 if (mg.InstanceExpression != null)
841 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
842 else if (ec.IsStatic) {
843 if (!delegate_method.IsStatic) {
844 Report.Error (120, loc,
845 "An object reference is required for the non-static method " +
846 delegate_method.Name);
849 delegate_instance_expression = null;
851 delegate_instance_expression = ec.GetThis (loc);
853 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
854 delegate_instance_expression = new BoxedCast (delegate_instance_expression);
857 eclass = ExprClass.Value;
863 // Created from the conversion code
865 public class ImplicitDelegateCreation : DelegateCreation {
867 ImplicitDelegateCreation (Type t, Location l)
873 public override Expression DoResolve (EmitContext ec)
878 static public Expression Create (EmitContext ec, MethodGroupExpr mge, Type target_type, Location loc)
880 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
881 if (d.ResolveConstructorMethod (ec))
882 return d.ResolveMethodGroupExpr (ec, mge);
889 // A delegate-creation-expression, invoked from the `New' class
891 public class NewDelegate : DelegateCreation {
892 public ArrayList Arguments;
895 // This constructor is invoked from the `New' expression
897 public NewDelegate (Type type, ArrayList Arguments, Location loc)
900 this.Arguments = Arguments;
904 public override Expression DoResolve (EmitContext ec)
906 if (Arguments == null || Arguments.Count != 1) {
907 Report.Error (149, loc,
908 "Method name expected");
912 if (!ResolveConstructorMethod (ec))
915 Argument a = (Argument) Arguments [0];
917 if (!a.ResolveMethodGroup (ec, loc))
920 Expression e = a.Expr;
922 if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
923 return ((AnonymousMethod) e).Compatible (ec, type, false);
925 MethodGroupExpr mg = e as MethodGroupExpr;
927 return ResolveMethodGroupExpr (ec, mg);
929 Type e_type = e.Type;
931 if (!TypeManager.IsDelegateType (e_type)) {
932 Report.Error (149, loc, "Method name expected");
936 method_group = Expression.MemberLookup (
937 ec, type, "Invoke", MemberTypes.Method,
938 Expression.AllBindingFlags, loc) as MethodGroupExpr;
940 if (method_group == null) {
941 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
945 // This is what MS' compiler reports. We could always choose
946 // to be more verbose and actually give delegate-level specifics
947 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
948 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
949 "to type '" + type + "'");
953 delegate_instance_expression = e;
954 delegate_method = method_group.Methods [0];
956 eclass = ExprClass.Value;
961 public class DelegateInvocation : ExpressionStatement {
963 public Expression InstanceExpr;
964 public ArrayList Arguments;
968 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
970 this.InstanceExpr = instance_expr;
971 this.Arguments = args;
975 public override Expression DoResolve (EmitContext ec)
977 if (InstanceExpr is EventExpr) {
979 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
981 Expression ml = MemberLookup (
982 ec, ec.ContainerType, ei.Name,
983 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
987 // If this is the case, then the Event does not belong
988 // to this Type and so, according to the spec
989 // cannot be accessed directly
991 // Note that target will not appear as an EventExpr
992 // in the case it is being referenced within the same type container;
993 // it will appear as a FieldExpr in that case.
996 Assign.error70 (ei, loc);
1002 Type del_type = InstanceExpr.Type;
1003 if (del_type == null)
1006 if (Arguments != null){
1007 foreach (Argument a in Arguments){
1008 if (!a.Resolve (ec, loc))
1013 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1016 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
1017 if (!(lookup is MethodGroupExpr)) {
1018 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
1022 method = ((MethodGroupExpr) lookup).Methods [0];
1023 type = ((MethodInfo) method).ReturnType;
1024 eclass = ExprClass.Value;
1029 public override void Emit (EmitContext ec)
1032 // Invocation on delegates call the virtual Invoke member
1033 // so we are always `instance' calls
1035 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
1038 public override void EmitStatement (EmitContext ec)
1042 // Pop the return value if there is one
1044 if (method is MethodInfo){
1045 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
1046 ec.ig.Emit (OpCodes.Pop);