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 if (TypeManager.multicast_delegate_type == null && !RootContext.StdLib) {
91 Namespace system = Namespace.LookupNamespace ("System", true);
92 TypeExpr expr = system.Lookup (this, "MulticastDelegate", Location) as TypeExpr;
93 TypeManager.multicast_delegate_type = expr.ResolveType (ec);
96 if (TypeManager.multicast_delegate_type == null)
97 Report.Error (-100, Location, "Internal error: delegate used before " +
98 "System.MulticastDelegate is resolved. This can only " +
99 "happen during corlib compilation, when using a delegate " +
100 "in any of the `core' classes. See bug #72015 for details.");
103 if (TypeManager.NamespaceClash (Name, Location))
106 ModuleBuilder builder = CodeGen.Module.Builder;
108 TypeBuilder = builder.DefineType (
109 Name, TypeAttr, TypeManager.multicast_delegate_type);
111 TypeBuilder builder = Parent.TypeBuilder;
113 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
114 TypeBuilder = builder.DefineNestedType (
115 name, TypeAttr, TypeManager.multicast_delegate_type);
118 TypeManager.AddDelegateType (Name, TypeBuilder, this);
121 string[] param_names = new string [TypeParameters.Length];
122 for (int i = 0; i < TypeParameters.Length; i++)
123 param_names [i] = TypeParameters [i].Name;
125 GenericTypeParameterBuilder[] gen_params;
126 gen_params = TypeBuilder.DefineGenericParameters (param_names);
128 int offset = CountTypeParameters - CurrentTypeParameters.Length;
129 for (int i = offset; i < gen_params.Length; i++)
130 CurrentTypeParameters [i - offset].Define (gen_params [i]);
132 foreach (TypeParameter type_param in CurrentTypeParameters) {
133 if (!type_param.Resolve (this))
137 for (int i = offset; i < gen_params.Length; i++)
138 CurrentTypeParameters [i - offset].DefineConstraints ();
140 Expression current = new SimpleName (Name, TypeParameters, Location);
141 current = current.ResolveAsTypeTerminal (ec);
145 CurrentType = current.Type;
151 public override bool Define ()
153 MethodAttributes mattr;
157 foreach (TypeParameter type_param in TypeParameters)
158 type_param.DefineType (ec);
162 throw new InternalErrorException ("Define called before DefineType?");
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 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
171 MethodAttributes.HideBySig | MethodAttributes.Public;
173 ConstructorBuilder = TypeBuilder.DefineConstructor (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.system_object_expr, "object",
184 Parameter.Modifier.NONE, null, Location);
185 fixed_pars [1] = new Parameter (TypeManager.system_intptr_expr, "method",
186 Parameter.Modifier.NONE, null, Location);
187 Parameters const_parameters = new Parameters (fixed_pars, null);
189 TypeManager.RegisterMethod (
191 new InternalParameters (const_arg_types, const_parameters),
195 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
198 // Here the various methods like Invoke, BeginInvoke etc are defined
200 // First, call the `out of band' special method for
201 // defining recursively any types we need:
203 param_types = Parameters.GetParameterInfo (ec);
204 if (param_types == null)
211 // Check accessibility
212 foreach (Type partype in param_types){
213 if (!Parent.AsAccessible (partype, ModFlags)) {
214 Report.Error (59, Location,
215 "Inconsistent accessibility: parameter type `" +
216 TypeManager.CSharpName (partype) + "' is less " +
217 "accessible than delegate `" + Name + "'");
220 if (partype.IsPointer && !UnsafeOK (Parent))
224 ReturnType = ReturnType.ResolveAsTypeTerminal (ec);
225 if (ReturnType == null)
228 ret_type = ReturnType.Type;
229 if (ret_type == null)
232 if (!Parent.AsAccessible (ret_type, ModFlags)) {
233 Report.Error (58, Location,
234 "Inconsistent accessibility: return type `" +
235 TypeManager.CSharpName (ret_type) + "' is less " +
236 "accessible than delegate `" + Name + "'");
240 if (ret_type.IsPointer && !UnsafeOK (Parent))
243 if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
244 Method.Error1599 (Location, ret_type);
249 // We don't have to check any others because they are all
250 // guaranteed to be accessible - they are standard types.
253 CallingConventions cc = Parameters.GetCallingConvention ();
255 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
257 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
264 // Define parameters, and count out/ref parameters
268 if (Parameters.FixedParameters != null){
269 int top = Parameters.FixedParameters.Length;
272 for (; i < top; i++) {
273 p = Parameters.FixedParameters [i];
274 p.DefineParameter (ec, InvokeBuilder, null, i + 1);
276 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
280 if (Parameters.ArrayParameter != null){
281 if (TypeManager.param_array_type == null && !RootContext.StdLib) {
282 Namespace system = Namespace.LookupNamespace ("System", true);
283 TypeExpr expr = system.Lookup (this, "ParamArrayAttribute", Location) as TypeExpr;
284 TypeManager.param_array_type = expr.ResolveType (ec);
287 if (TypeManager.cons_param_array_attribute == null) {
288 Type [] void_arg = { };
289 TypeManager.cons_param_array_attribute = TypeManager.GetConstructor (
290 TypeManager.param_array_type, void_arg);
293 ParameterBuilder pb = InvokeBuilder.DefineParameter (
294 i + 1, Parameters.ArrayParameter.Attributes,Parameters.ArrayParameter.Name);
296 pb.SetCustomAttribute (
297 new CustomAttributeBuilder (TypeManager.cons_param_array_attribute, new object [0]));
300 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
302 TypeManager.RegisterMethod (InvokeBuilder,
303 new InternalParameters (param_types, Parameters),
309 int params_num = param_types.Length;
310 Type [] async_param_types = new Type [params_num + 2];
312 param_types.CopyTo (async_param_types, 0);
314 async_param_types [params_num] = TypeManager.asynccallback_type;
315 async_param_types [params_num + 1] = TypeManager.object_type;
317 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
318 MethodAttributes.Virtual | MethodAttributes.NewSlot;
320 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
323 TypeManager.iasyncresult_type,
327 if (Parameters.FixedParameters != null){
328 int top = Parameters.FixedParameters.Length;
331 for (i = 0 ; i < top; i++) {
332 p = Parameters.FixedParameters [i];
334 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1);
337 if (Parameters.ArrayParameter != null){
338 Parameter p = Parameters.ArrayParameter;
339 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1);
344 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
345 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
347 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
349 Parameter [] async_params = new Parameter [params_num + 2];
351 if (Parameters.FixedParameters != null){
352 Parameters.FixedParameters.CopyTo (async_params, 0);
353 n = Parameters.FixedParameters.Length;
355 if (Parameters.ArrayParameter != null)
356 async_params [n] = Parameters.ArrayParameter;
358 async_params [params_num] = new Parameter (
359 TypeManager.system_asynccallback_expr, "callback",
360 Parameter.Modifier.NONE, null, Location);
361 async_params [params_num + 1] = new Parameter (
362 TypeManager.system_object_expr, "object",
363 Parameter.Modifier.NONE, null, Location);
365 Parameters async_parameters = new Parameters (async_params, null);
367 TypeManager.RegisterMethod (BeginInvokeBuilder,
368 new InternalParameters (async_parameters.GetParameterInfo (ec), async_parameters),
372 // EndInvoke is a bit more interesting, all the parameters labeled as
373 // out or ref have to be duplicated here.
376 Type [] end_param_types = new Type [out_params + 1];
377 Parameter [] end_params = new Parameter [out_params + 1];
380 int top = Parameters.FixedParameters.Length;
381 for (i = 0; i < top; i++){
382 Parameter p = Parameters.FixedParameters [i];
383 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
386 end_param_types [param] = param_types [i];
387 end_params [param] = p;
391 end_param_types [out_params] = TypeManager.iasyncresult_type;
392 end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null, Location);
395 // Create method, define parameters, register parameters with type system
397 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
398 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
401 // EndInvoke: Label the parameters
403 EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
404 for (i = 0; i < end_params.Length-1; i++){
405 EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
408 Parameters end_parameters = new Parameters (end_params, null);
410 TypeManager.RegisterMethod (
412 new InternalParameters (end_parameters.GetParameterInfo (ec), end_parameters),
418 public override void Emit ()
420 if (OptAttributes != null) {
421 Parameters.LabelParameters (ec, InvokeBuilder);
422 OptAttributes.Emit (ec, this);
428 protected override TypeAttributes TypeAttr {
430 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
431 TypeAttributes.Class | TypeAttributes.Sealed |
436 public override string[] ValidAttributeTargets {
438 return attribute_targets;
443 protected override bool VerifyClsCompliance (DeclSpace ds)
445 if (!base.VerifyClsCompliance (ds)) {
449 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
451 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
452 Report.Error (3002, Location, "Return type of `{0}' is not CLS-compliant", GetSignatureForError ());
458 // Returns the MethodBase for "Invoke" from a delegate type, this is used
459 // to extract the signature of a delegate.
461 public static MethodGroupExpr GetInvokeMethod (EmitContext ec, Type delegate_type,
464 Expression ml = Expression.MemberLookup (
465 ec, delegate_type, "Invoke", loc);
467 MethodGroupExpr mg = ml as MethodGroupExpr;
469 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
477 /// Verifies whether the method in question is compatible with the delegate
478 /// Returns the method itself if okay and null if not.
480 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type,
481 MethodGroupExpr old_mg, MethodBase mb,
484 MethodGroupExpr mg = GetInvokeMethod (ec, delegate_type, loc);
488 if (old_mg.HasTypeArguments)
489 mg.HasTypeArguments = true;
491 MethodBase invoke_mb = mg.Methods [0];
492 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
494 if (!mg.HasTypeArguments &&
495 !TypeManager.InferTypeArguments (ec, invoke_pd, ref mb))
498 ParameterData pd = TypeManager.GetParameterData (mb);
500 if (invoke_pd.Count != pd.Count)
503 for (int i = pd.Count; i > 0; ) {
506 Type invoke_pd_type = invoke_pd.ParameterType (i);
507 Type pd_type = pd.ParameterType (i);
508 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
509 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
511 if (invoke_pd_type == pd_type &&
512 invoke_pd_type_mod == pd_type_mod)
515 if (invoke_pd_type.IsSubclassOf (pd_type) &&
516 invoke_pd_type_mod == pd_type_mod)
517 if (RootContext.Version == LanguageVersion.ISO_1) {
518 Report.FeatureIsNotStandardized (loc, "contravariance");
526 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
527 Type mb_retval = ((MethodInfo) mb).ReturnType;
528 if (invoke_mb_retval == mb_retval)
531 if (mb_retval.IsSubclassOf (invoke_mb_retval))
532 if (RootContext.Version == LanguageVersion.ISO_1) {
533 Report.FeatureIsNotStandardized (loc, "covariance");
543 // Verifies whether the invocation arguments are compatible with the
544 // delegate's target method
546 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
547 ArrayList args, Location loc)
554 arg_count = args.Count;
556 Expression ml = Expression.MemberLookup (
557 ec, delegate_type, "Invoke", loc);
559 MethodGroupExpr me = ml as MethodGroupExpr;
561 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
565 MethodBase mb = me.Methods [0];
566 ParameterData pd = TypeManager.GetParameterData (mb);
568 int pd_count = pd.Count;
570 bool params_method = (pd_count != 0) &&
571 (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);
573 bool is_params_applicable = false;
574 bool is_applicable = Invocation.IsApplicable (ec, me, args, arg_count, ref mb);
576 if (!is_applicable && params_method &&
577 Invocation.IsParamsMethodApplicable (ec, me, args, arg_count, ref mb))
578 is_applicable = is_params_applicable = true;
580 if (!is_applicable && !params_method && arg_count != pd_count) {
581 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
582 TypeManager.CSharpName (delegate_type), arg_count);
586 return Invocation.VerifyArgumentsCompat (
587 ec, args, arg_count, mb,
588 is_params_applicable || (!is_applicable && params_method),
589 delegate_type, false, loc);
593 /// Verifies whether the delegate in question is compatible with this one in
594 /// order to determine if instantiation from the same is possible.
596 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
598 Expression ml = Expression.MemberLookup (
599 ec, delegate_type, "Invoke", loc);
601 if (!(ml is MethodGroupExpr)) {
602 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
606 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
607 ParameterData pd = TypeManager.GetParameterData (mb);
609 Expression probe_ml = Expression.MemberLookup (
610 ec, delegate_type, "Invoke", loc);
612 if (!(probe_ml is MethodGroupExpr)) {
613 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
617 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
618 ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
620 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
623 if (pd.Count != probe_pd.Count)
626 for (int i = pd.Count; i > 0; ) {
629 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
630 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
637 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
639 StringBuilder sb = new StringBuilder ();
640 sb.Append (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
642 sb.Append (TypeManager.CSharpName (del_type));
643 sb.Append (pd.GetSignatureForError ());
644 return sb.ToString ();
647 // Hack around System.Reflection as found everywhere else
648 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
649 MemberFilter filter, object criteria)
651 ArrayList members = new ArrayList ();
653 if ((mt & MemberTypes.Method) != 0) {
654 if (ConstructorBuilder != null)
655 if (filter (ConstructorBuilder, criteria))
656 members.Add (ConstructorBuilder);
658 if (InvokeBuilder != null)
659 if (filter (InvokeBuilder, criteria))
660 members.Add (InvokeBuilder);
662 if (BeginInvokeBuilder != null)
663 if (filter (BeginInvokeBuilder, criteria))
664 members.Add (BeginInvokeBuilder);
666 if (EndInvokeBuilder != null)
667 if (filter (EndInvokeBuilder, criteria))
668 members.Add (EndInvokeBuilder);
671 return new MemberList (members);
674 public override MemberCache MemberCache {
680 public Expression InstanceExpression {
682 return instance_expr;
685 instance_expr = value;
689 public MethodBase TargetMethod {
691 return delegate_method;
694 delegate_method = value;
698 public Type TargetReturnType {
704 public Type [] ParameterTypes {
710 public override AttributeTargets AttributeTargets {
712 return AttributeTargets.Delegate;
717 // Represents header string for documentation comment.
719 public override string DocCommentHeader {
723 protected override void VerifyObsoleteAttribute()
725 CheckUsageOfObsoleteAttribute (ret_type);
727 foreach (Type type in param_types) {
728 CheckUsageOfObsoleteAttribute (type);
734 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
736 public abstract class DelegateCreation : Expression {
737 protected MethodBase constructor_method;
738 protected MethodBase delegate_method;
739 protected MethodGroupExpr method_group;
740 protected Expression delegate_instance_expression;
742 public DelegateCreation () {}
744 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
747 MethodBase found_method = mg.Methods [0];
749 if (mg.Methods.Length > 1)
750 method_desc = found_method.Name;
752 method_desc = Invocation.FullMethodDesc (found_method);
754 Expression invoke_method = Expression.MemberLookup (
755 ec, type, "Invoke", MemberTypes.Method,
756 Expression.AllBindingFlags, loc);
757 MethodInfo method = ((MethodGroupExpr) invoke_method).Methods [0] as MethodInfo;
759 ParameterData param = TypeManager.GetParameterData (method);
760 string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
762 if (!mg.HasTypeArguments &&
763 !TypeManager.InferTypeArguments (ec, param, ref found_method))
764 Report.Error (411, loc, "The type arguments for " +
765 "method `{0}' cannot be infered from " +
766 "the usage. Try specifying the type " +
767 "arguments explicitly.", method_desc);
768 else if (method.ReturnType != ((MethodInfo) found_method).ReturnType) {
769 Report.Error (407, loc, "`{0}' has the wrong return type to match the delegate `{1}'", method_desc, delegate_desc);
771 Report.Error (123, loc, "Method `{0}' does not match delegate `{1}'", method_desc, delegate_desc);
775 public override void Emit (EmitContext ec)
777 if (delegate_instance_expression == null || delegate_method.IsStatic)
778 ec.ig.Emit (OpCodes.Ldnull);
780 delegate_instance_expression.Emit (ec);
782 if (delegate_method.IsVirtual && !method_group.IsBase) {
783 ec.ig.Emit (OpCodes.Dup);
784 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
786 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
787 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
790 protected bool ResolveConstructorMethod (EmitContext ec)
792 Expression ml = Expression.MemberLookup (
793 ec, type, ".ctor", loc);
795 if (!(ml is MethodGroupExpr)) {
796 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
800 constructor_method = ((MethodGroupExpr) ml).Methods [0];
804 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg,
807 foreach (MethodInfo mi in mg.Methods){
808 delegate_method = Delegate.VerifyMethod (ec, type, mg, mi, loc);
810 if (delegate_method != null)
814 if (delegate_method == null) {
816 Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
821 // Check safe/unsafe of the delegate
824 ParameterData param = TypeManager.GetParameterData (delegate_method);
825 int count = param.Count;
827 for (int i = 0; i < count; i++){
828 if (param.ParameterType (i).IsPointer){
829 Expression.UnsafeError (loc);
835 //TODO: implement caching when performance will be low
836 IMethodData md = TypeManager.GetMethod (delegate_method);
838 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
839 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
842 md.SetMemberIsUsed ();
843 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
844 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
848 if (mg.InstanceExpression != null)
849 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
850 else if (ec.IsStatic) {
851 if (!delegate_method.IsStatic) {
852 Report.Error (120, loc, "`{0}': An object reference is required for the nonstatic field, method or property",
853 TypeManager.CSharpSignature (delegate_method));
856 delegate_instance_expression = null;
858 delegate_instance_expression = ec.GetThis (loc);
860 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
861 delegate_instance_expression = new BoxedCast (delegate_instance_expression);
864 eclass = ExprClass.Value;
870 // Created from the conversion code
872 public class ImplicitDelegateCreation : DelegateCreation {
874 ImplicitDelegateCreation (Type t, Location l)
880 public override Expression DoResolve (EmitContext ec)
885 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
886 Type target_type, bool check_only, Location loc)
888 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
889 if (d.ResolveConstructorMethod (ec))
890 return d.ResolveMethodGroupExpr (ec, mge, check_only);
897 // A delegate-creation-expression, invoked from the `New' class
899 public class NewDelegate : DelegateCreation {
900 public ArrayList Arguments;
903 // This constructor is invoked from the `New' expression
905 public NewDelegate (Type type, ArrayList Arguments, Location loc)
908 this.Arguments = Arguments;
912 public override Expression DoResolve (EmitContext ec)
914 if (Arguments == null || Arguments.Count != 1) {
915 Report.Error (149, loc,
916 "Method name expected");
920 if (!ResolveConstructorMethod (ec))
923 Argument a = (Argument) Arguments [0];
925 if (!a.ResolveMethodGroup (ec, loc))
928 Expression e = a.Expr;
930 if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
931 return ((AnonymousMethod) e).Compatible (ec, type, false);
933 MethodGroupExpr mg = e as MethodGroupExpr;
935 return ResolveMethodGroupExpr (ec, mg, false);
937 Type e_type = e.Type;
939 if (!TypeManager.IsDelegateType (e_type)) {
940 Report.Error (149, loc, "Method name expected");
944 method_group = Expression.MemberLookup (
945 ec, type, "Invoke", MemberTypes.Method,
946 Expression.AllBindingFlags, loc) as MethodGroupExpr;
948 if (method_group == null) {
949 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
953 // This is what MS' compiler reports. We could always choose
954 // to be more verbose and actually give delegate-level specifics
955 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
956 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
957 "to type '" + type + "'");
961 delegate_instance_expression = e;
962 delegate_method = method_group.Methods [0];
964 eclass = ExprClass.Value;
969 public class DelegateInvocation : ExpressionStatement {
971 public Expression InstanceExpr;
972 public ArrayList Arguments;
976 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
978 this.InstanceExpr = instance_expr;
979 this.Arguments = args;
983 public override Expression DoResolve (EmitContext ec)
985 if (InstanceExpr is EventExpr) {
987 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
989 Expression ml = MemberLookup (
990 ec, ec.ContainerType, ei.Name,
991 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
995 // If this is the case, then the Event does not belong
996 // to this Type and so, according to the spec
997 // cannot be accessed directly
999 // Note that target will not appear as an EventExpr
1000 // in the case it is being referenced within the same type container;
1001 // it will appear as a FieldExpr in that case.
1004 Assign.error70 (ei, loc);
1010 Type del_type = InstanceExpr.Type;
1011 if (del_type == null)
1014 if (Arguments != null){
1015 foreach (Argument a in Arguments){
1016 if (!a.Resolve (ec, loc))
1021 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1024 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
1025 if (!(lookup is MethodGroupExpr)) {
1026 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
1030 method = ((MethodGroupExpr) lookup).Methods [0];
1031 type = ((MethodInfo) method).ReturnType;
1032 eclass = ExprClass.Value;
1037 public override void Emit (EmitContext ec)
1040 // Invocation on delegates call the virtual Invoke member
1041 // so we are always `instance' calls
1043 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
1046 public override void EmitStatement (EmitContext ec)
1050 // Pop the return value if there is one
1052 if (method is MethodInfo){
1053 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
1054 ec.ig.Emit (OpCodes.Pop);