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 DefineMembers (TypeContainer container)
156 public override bool Define ()
158 MethodAttributes mattr;
162 foreach (TypeParameter type_param in TypeParameters)
163 type_param.DefineType (ec);
167 throw new InternalErrorException ("Define called before DefineType?");
169 // FIXME: POSSIBLY make this static, as it is always constant
171 Type [] const_arg_types = new Type [2];
172 const_arg_types [0] = TypeManager.object_type;
173 const_arg_types [1] = TypeManager.intptr_type;
175 mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
176 MethodAttributes.HideBySig | MethodAttributes.Public;
178 ConstructorBuilder = TypeBuilder.DefineConstructor (mattr,
179 CallingConventions.Standard,
182 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
183 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
185 // HACK because System.Reflection.Emit is lame
188 // FIXME: POSSIBLY make these static, as they are always the same
189 Parameter [] fixed_pars = new Parameter [2];
190 fixed_pars [0] = new Parameter (TypeManager.system_object_expr, "object",
191 Parameter.Modifier.NONE, null);
192 fixed_pars [1] = new Parameter (TypeManager.system_intptr_expr, "method",
193 Parameter.Modifier.NONE, null);
194 Parameters const_parameters = new Parameters (fixed_pars, null, Location);
196 TypeManager.RegisterMethod (
198 new InternalParameters (const_arg_types, const_parameters),
202 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
205 // Here the various methods like Invoke, BeginInvoke etc are defined
207 // First, call the `out of band' special method for
208 // defining recursively any types we need:
210 param_types = Parameters.GetParameterInfo (ec);
211 if (param_types == null)
218 // Check accessibility
219 foreach (Type partype in param_types){
220 if (!Parent.AsAccessible (partype, ModFlags)) {
221 Report.Error (59, Location,
222 "Inconsistent accessibility: parameter type `" +
223 TypeManager.CSharpName (partype) + "` is less " +
224 "accessible than delegate `" + Name + "'");
227 if (partype.IsPointer && !UnsafeOK (Parent))
231 ReturnType = ReturnType.ResolveAsTypeTerminal (ec);
232 if (ReturnType == null)
235 ret_type = ReturnType.Type;
236 if (ret_type == null)
239 if (!Parent.AsAccessible (ret_type, ModFlags)) {
240 Report.Error (58, Location,
241 "Inconsistent accessibility: return type `" +
242 TypeManager.CSharpName (ret_type) + "` is less " +
243 "accessible than delegate `" + Name + "'");
247 if (ret_type.IsPointer && !UnsafeOK (Parent))
250 if (RootContext.StdLib && (ret_type == TypeManager.arg_iterator_type || ret_type == TypeManager.typed_reference_type)) {
251 Method.Error1599 (Location, ret_type);
256 // We don't have to check any others because they are all
257 // guaranteed to be accessible - they are standard types.
260 CallingConventions cc = Parameters.GetCallingConvention ();
262 mattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
264 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
271 // Define parameters, and count out/ref parameters
275 if (Parameters.FixedParameters != null){
276 int top = Parameters.FixedParameters.Length;
279 for (; i < top; i++) {
280 p = Parameters.FixedParameters [i];
281 p.DefineParameter (ec, InvokeBuilder, null, i + 1, Location);
283 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
287 if (Parameters.ArrayParameter != null){
288 Parameter p = Parameters.ArrayParameter;
290 if (TypeManager.param_array_type == null && !RootContext.StdLib) {
291 Namespace system = Namespace.LookupNamespace ("System", true);
292 TypeExpr expr = system.Lookup (this, "ParamArrayAttribute", Location) as TypeExpr;
293 TypeManager.param_array_type = expr.ResolveType (ec);
296 if (TypeManager.cons_param_array_attribute == null) {
297 Type [] void_arg = { };
298 TypeManager.cons_param_array_attribute = TypeManager.GetConstructor (
299 TypeManager.param_array_type, void_arg);
302 ParameterBuilder pb = InvokeBuilder.DefineParameter (
303 i + 1, Parameters.ArrayParameter.Attributes,Parameters.ArrayParameter.Name);
305 pb.SetCustomAttribute (
306 new CustomAttributeBuilder (TypeManager.cons_param_array_attribute, new object [0]));
309 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
311 TypeManager.RegisterMethod (InvokeBuilder,
312 new InternalParameters (param_types, Parameters),
318 int params_num = param_types.Length;
319 Type [] async_param_types = new Type [params_num + 2];
321 param_types.CopyTo (async_param_types, 0);
323 async_param_types [params_num] = TypeManager.asynccallback_type;
324 async_param_types [params_num + 1] = TypeManager.object_type;
326 mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
327 MethodAttributes.Virtual | MethodAttributes.NewSlot;
329 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
332 TypeManager.iasyncresult_type,
336 if (Parameters.FixedParameters != null){
337 int top = Parameters.FixedParameters.Length;
340 for (i = 0 ; i < top; i++) {
341 p = Parameters.FixedParameters [i];
343 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
346 if (Parameters.ArrayParameter != null){
347 Parameter p = Parameters.ArrayParameter;
348 p.DefineParameter (ec, BeginInvokeBuilder, null, i + 1, Location);
353 BeginInvokeBuilder.DefineParameter (i + 1, ParameterAttributes.None, "callback");
354 BeginInvokeBuilder.DefineParameter (i + 2, ParameterAttributes.None, "object");
356 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
358 Parameter [] async_params = new Parameter [params_num + 2];
360 if (Parameters.FixedParameters != null){
361 Parameters.FixedParameters.CopyTo (async_params, 0);
362 n = Parameters.FixedParameters.Length;
364 if (Parameters.ArrayParameter != null)
365 async_params [n] = Parameters.ArrayParameter;
367 async_params [params_num] = new Parameter (
368 TypeManager.system_asynccallback_expr, "callback",
369 Parameter.Modifier.NONE, null);
370 async_params [params_num + 1] = new Parameter (
371 TypeManager.system_object_expr, "object",
372 Parameter.Modifier.NONE, null);
374 Parameters async_parameters = new Parameters (async_params, null, Location);
376 TypeManager.RegisterMethod (BeginInvokeBuilder,
377 new InternalParameters (async_parameters.GetParameterInfo (ec), async_parameters),
381 // EndInvoke is a bit more interesting, all the parameters labeled as
382 // out or ref have to be duplicated here.
385 Type [] end_param_types = new Type [out_params + 1];
386 Parameter [] end_params = new Parameter [out_params + 1];
389 int top = Parameters.FixedParameters.Length;
390 for (i = 0; i < top; i++){
391 Parameter p = Parameters.FixedParameters [i];
392 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
395 end_param_types [param] = param_types [i];
396 end_params [param] = p;
400 end_param_types [out_params] = TypeManager.iasyncresult_type;
401 end_params [out_params] = new Parameter (TypeManager.system_iasyncresult_expr, "result", Parameter.Modifier.NONE, null);
404 // Create method, define parameters, register parameters with type system
406 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_param_types);
407 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
410 // EndInvoke: Label the parameters
412 EndInvokeBuilder.DefineParameter (out_params + 1, ParameterAttributes.None, "result");
413 for (i = 0; i < end_params.Length-1; i++){
414 EndInvokeBuilder.DefineParameter (i + 1, end_params [i].Attributes, end_params [i].Name);
417 Parameters end_parameters = new Parameters (end_params, null, Location);
419 TypeManager.RegisterMethod (
421 new InternalParameters (end_parameters.GetParameterInfo (ec), end_parameters),
427 public override void Emit ()
429 if (OptAttributes != null) {
430 Parameters.LabelParameters (ec, InvokeBuilder, Location);
431 OptAttributes.Emit (ec, this);
437 protected override TypeAttributes TypeAttr {
439 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
440 TypeAttributes.Class | TypeAttributes.Sealed |
445 public override string[] ValidAttributeTargets {
447 return attribute_targets;
452 protected override bool VerifyClsCompliance (DeclSpace ds)
454 if (!base.VerifyClsCompliance (ds)) {
458 AttributeTester.AreParametersCompliant (Parameters.FixedParameters, Location);
460 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
461 Report.Error (3002, Location, "Return type of '{0}' is not CLS-compliant", GetSignatureForError ());
467 // Returns the MethodBase for "Invoke" from a delegate type, this is used
468 // to extract the signature of a delegate.
470 public static MethodGroupExpr GetInvokeMethod (EmitContext ec, Type delegate_type,
473 Expression ml = Expression.MemberLookup (
474 ec, delegate_type, "Invoke", loc);
476 MethodGroupExpr mg = ml as MethodGroupExpr;
478 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
486 /// Verifies whether the method in question is compatible with the delegate
487 /// Returns the method itself if okay and null if not.
489 public static MethodBase VerifyMethod (EmitContext ec, Type delegate_type, MethodBase mb,
492 MethodGroupExpr mg = GetInvokeMethod (ec, delegate_type, loc);
496 MethodBase invoke_mb = mg.Methods [0];
497 ParameterData invoke_pd = TypeManager.GetParameterData (invoke_mb);
499 if (!mg.HasTypeArguments &&
500 !TypeManager.InferTypeArguments (ec, invoke_pd, ref mb))
503 ParameterData pd = TypeManager.GetParameterData (mb);
505 if (invoke_pd.Count != pd.Count)
508 for (int i = pd.Count; i > 0; ) {
511 Type invoke_pd_type = invoke_pd.ParameterType (i);
512 Type pd_type = pd.ParameterType (i);
513 Parameter.Modifier invoke_pd_type_mod = invoke_pd.ParameterModifier (i);
514 Parameter.Modifier pd_type_mod = pd.ParameterModifier (i);
516 if (invoke_pd_type == pd_type &&
517 invoke_pd_type_mod == pd_type_mod)
520 if (invoke_pd_type.IsSubclassOf (pd_type) &&
521 invoke_pd_type_mod == pd_type_mod)
522 if (RootContext.Version == LanguageVersion.ISO_1) {
523 Report.FeatureIsNotStandardized (loc, "contravariance");
531 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
532 Type mb_retval = ((MethodInfo) mb).ReturnType;
533 if (invoke_mb_retval == mb_retval)
536 if (mb_retval.IsSubclassOf (invoke_mb_retval))
537 if (RootContext.Version == LanguageVersion.ISO_1) {
538 Report.FeatureIsNotStandardized (loc, "covariance");
548 // Verifies whether the invocation arguments are compatible with the
549 // delegate's target method
551 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
552 ArrayList args, Location loc)
559 arg_count = args.Count;
561 Expression ml = Expression.MemberLookup (
562 ec, delegate_type, "Invoke", loc);
564 MethodGroupExpr me = ml as MethodGroupExpr;
566 Report.Error (-100, loc, "Internal error: could not find Invoke method!" + delegate_type);
570 MethodBase mb = me.Methods [0];
571 ParameterData pd = TypeManager.GetParameterData (mb);
573 int pd_count = pd.Count;
575 bool params_method = (pd_count != 0) &&
576 (pd.ParameterModifier (pd_count - 1) == Parameter.Modifier.PARAMS);
578 bool is_params_applicable = false;
579 bool is_applicable = Invocation.IsApplicable (ec, me, args, arg_count, ref mb);
581 if (!is_applicable && params_method &&
582 Invocation.IsParamsMethodApplicable (ec, me, args, arg_count, ref mb))
583 is_applicable = is_params_applicable = true;
585 if (!is_applicable && !params_method && arg_count != pd_count) {
586 Report.Error (1593, loc,
587 "Delegate '{0}' does not take {1} arguments",
588 delegate_type.ToString (), arg_count);
592 return Invocation.VerifyArgumentsCompat (
593 ec, args, arg_count, mb,
594 is_params_applicable || (!is_applicable && params_method),
595 delegate_type, false, loc);
599 /// Verifies whether the delegate in question is compatible with this one in
600 /// order to determine if instantiation from the same is possible.
602 public static bool VerifyDelegate (EmitContext ec, Type delegate_type, Type probe_type, Location loc)
604 Expression ml = Expression.MemberLookup (
605 ec, delegate_type, "Invoke", loc);
607 if (!(ml is MethodGroupExpr)) {
608 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
612 MethodBase mb = ((MethodGroupExpr) ml).Methods [0];
613 ParameterData pd = TypeManager.GetParameterData (mb);
615 Expression probe_ml = Expression.MemberLookup (
616 ec, delegate_type, "Invoke", loc);
618 if (!(probe_ml is MethodGroupExpr)) {
619 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
623 MethodBase probe_mb = ((MethodGroupExpr) probe_ml).Methods [0];
624 ParameterData probe_pd = TypeManager.GetParameterData (probe_mb);
626 if (((MethodInfo) mb).ReturnType != ((MethodInfo) probe_mb).ReturnType)
629 if (pd.Count != probe_pd.Count)
632 for (int i = pd.Count; i > 0; ) {
635 if (pd.ParameterType (i) != probe_pd.ParameterType (i) ||
636 pd.ParameterModifier (i) != probe_pd.ParameterModifier (i))
643 public static string FullDelegateDesc (Type del_type, MethodBase mb, ParameterData pd)
645 StringBuilder sb = new StringBuilder (TypeManager.CSharpName (((MethodInfo) mb).ReturnType));
647 sb.Append (" " + del_type.ToString ());
650 int length = pd.Count;
652 for (int i = length; i > 0; ) {
655 sb.Append (pd.ParameterDesc (length - i - 1));
661 return sb.ToString ();
665 // Hack around System.Reflection as found everywhere else
666 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
667 MemberFilter filter, object criteria)
669 ArrayList members = new ArrayList ();
671 if ((mt & MemberTypes.Method) != 0) {
672 if (ConstructorBuilder != null)
673 if (filter (ConstructorBuilder, criteria))
674 members.Add (ConstructorBuilder);
676 if (InvokeBuilder != null)
677 if (filter (InvokeBuilder, criteria))
678 members.Add (InvokeBuilder);
680 if (BeginInvokeBuilder != null)
681 if (filter (BeginInvokeBuilder, criteria))
682 members.Add (BeginInvokeBuilder);
684 if (EndInvokeBuilder != null)
685 if (filter (EndInvokeBuilder, criteria))
686 members.Add (EndInvokeBuilder);
689 return new MemberList (members);
692 public override MemberCache MemberCache {
698 public Expression InstanceExpression {
700 return instance_expr;
703 instance_expr = value;
707 public MethodBase TargetMethod {
709 return delegate_method;
712 delegate_method = value;
716 public Type TargetReturnType {
722 public Type [] ParameterTypes {
728 public override AttributeTargets AttributeTargets {
730 return AttributeTargets.Delegate;
735 // Represents header string for documentation comment.
737 public override string DocCommentHeader {
741 protected override void VerifyObsoleteAttribute()
743 CheckUsageOfObsoleteAttribute (ret_type);
745 foreach (Type type in param_types) {
746 CheckUsageOfObsoleteAttribute (type);
752 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
754 public abstract class DelegateCreation : Expression {
755 protected MethodBase constructor_method;
756 protected MethodBase delegate_method;
757 protected MethodGroupExpr method_group;
758 protected Expression delegate_instance_expression;
760 public DelegateCreation () {}
762 public static void Error_NoMatchingMethodForDelegate (EmitContext ec, MethodGroupExpr mg, Type type, Location loc)
765 MethodBase found_method = mg.Methods [0];
767 if (mg.Methods.Length > 1)
768 method_desc = found_method.Name;
770 method_desc = Invocation.FullMethodDesc (found_method);
772 Expression invoke_method = Expression.MemberLookup (
773 ec, type, "Invoke", MemberTypes.Method,
774 Expression.AllBindingFlags, loc);
775 MethodInfo method = ((MethodGroupExpr) invoke_method).Methods [0] as MethodInfo;
777 ParameterData param = TypeManager.GetParameterData (method);
778 string delegate_desc = Delegate.FullDelegateDesc (type, method, param);
780 if (!mg.HasTypeArguments &&
781 !TypeManager.InferTypeArguments (ec, param, ref found_method))
782 Report.Error (411, loc, "The type arguments for " +
783 "method `{0}' cannot be infered from " +
784 "the usage. Try specifying the type " +
785 "arguments explicitly.", method_desc);
786 else if (method.ReturnType != ((MethodInfo) found_method).ReturnType) {
787 Report.Error (407, loc, "'{0}' has the wrong return type to match delegate '{1}'", method_desc, delegate_desc);
789 Report.Error (123, loc, "Method '" + method_desc + "' does not " +
790 "match delegate '" + delegate_desc + "'");
794 public override void Emit (EmitContext ec)
796 if (delegate_instance_expression == null || delegate_method.IsStatic)
797 ec.ig.Emit (OpCodes.Ldnull);
799 delegate_instance_expression.Emit (ec);
801 if (delegate_method.IsVirtual && !method_group.IsBase) {
802 ec.ig.Emit (OpCodes.Dup);
803 ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method);
805 ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method);
806 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method);
809 protected bool ResolveConstructorMethod (EmitContext ec)
811 Expression ml = Expression.MemberLookup (
812 ec, type, ".ctor", loc);
814 if (!(ml is MethodGroupExpr)) {
815 Report.Error (-100, loc, "Internal error: Could not find delegate constructor!");
819 constructor_method = ((MethodGroupExpr) ml).Methods [0];
823 protected Expression ResolveMethodGroupExpr (EmitContext ec, MethodGroupExpr mg)
825 foreach (MethodInfo mi in mg.Methods){
826 delegate_method = Delegate.VerifyMethod (ec, type, mi, loc);
828 if (delegate_method != null)
832 if (delegate_method == null) {
833 Error_NoMatchingMethodForDelegate (ec, mg, type, loc);
838 // Check safe/unsafe of the delegate
841 ParameterData param = TypeManager.GetParameterData (delegate_method);
842 int count = param.Count;
844 for (int i = 0; i < count; i++){
845 if (param.ParameterType (i).IsPointer){
846 Expression.UnsafeError (loc);
852 //TODO: implement caching when performance will be low
853 IMethodData md = TypeManager.GetMethod (delegate_method);
855 if (System.Attribute.GetCustomAttribute (delegate_method, TypeManager.conditional_attribute_type) != null) {
856 Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
859 md.SetMemberIsUsed ();
860 if (md.OptAttributes != null && md.OptAttributes.Search (TypeManager.conditional_attribute_type, ec) != null) {
861 Report.Error (1618, loc, "Cannot create delegate with '{0}' because it has a Conditional attribute", TypeManager.CSharpSignature (delegate_method));
865 if (mg.InstanceExpression != null)
866 delegate_instance_expression = mg.InstanceExpression.Resolve (ec);
867 else if (ec.IsStatic) {
868 if (!delegate_method.IsStatic) {
869 Report.Error (120, loc,
870 "An object reference is required for the non-static method " +
871 delegate_method.Name);
874 delegate_instance_expression = null;
876 delegate_instance_expression = ec.GetThis (loc);
878 if (delegate_instance_expression != null && delegate_instance_expression.Type.IsValueType)
879 delegate_instance_expression = new BoxedCast (delegate_instance_expression);
882 eclass = ExprClass.Value;
888 // Created from the conversion code
890 public class ImplicitDelegateCreation : DelegateCreation {
892 ImplicitDelegateCreation (Type t, Location l)
898 public override Expression DoResolve (EmitContext ec)
903 static public Expression Create (EmitContext ec, MethodGroupExpr mge, Type target_type, Location loc)
905 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, loc);
906 if (d.ResolveConstructorMethod (ec))
907 return d.ResolveMethodGroupExpr (ec, mge);
914 // A delegate-creation-expression, invoked from the `New' class
916 public class NewDelegate : DelegateCreation {
917 public ArrayList Arguments;
920 // This constructor is invoked from the `New' expression
922 public NewDelegate (Type type, ArrayList Arguments, Location loc)
925 this.Arguments = Arguments;
929 public override Expression DoResolve (EmitContext ec)
931 if (Arguments == null || Arguments.Count != 1) {
932 Report.Error (149, loc,
933 "Method name expected");
937 if (!ResolveConstructorMethod (ec))
940 Argument a = (Argument) Arguments [0];
942 if (!a.ResolveMethodGroup (ec, loc))
945 Expression e = a.Expr;
947 if (e is AnonymousMethod && RootContext.Version != LanguageVersion.ISO_1)
948 return ((AnonymousMethod) e).Compatible (ec, type, false);
950 MethodGroupExpr mg = e as MethodGroupExpr;
952 return ResolveMethodGroupExpr (ec, mg);
954 Type e_type = e.Type;
956 if (!TypeManager.IsDelegateType (e_type)) {
957 Report.Error (149, loc, "Method name expected");
961 method_group = Expression.MemberLookup (
962 ec, type, "Invoke", MemberTypes.Method,
963 Expression.AllBindingFlags, loc) as MethodGroupExpr;
965 if (method_group == null) {
966 Report.Error (-200, loc, "Internal error ! Could not find Invoke method!");
970 // This is what MS' compiler reports. We could always choose
971 // to be more verbose and actually give delegate-level specifics
972 if (!Delegate.VerifyDelegate (ec, type, e_type, loc)) {
973 Report.Error (29, loc, "Cannot implicitly convert type '" + e_type + "' " +
974 "to type '" + type + "'");
978 delegate_instance_expression = e;
979 delegate_method = method_group.Methods [0];
981 eclass = ExprClass.Value;
986 public class DelegateInvocation : ExpressionStatement {
988 public Expression InstanceExpr;
989 public ArrayList Arguments;
993 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
995 this.InstanceExpr = instance_expr;
996 this.Arguments = args;
1000 public override Expression DoResolve (EmitContext ec)
1002 if (InstanceExpr is EventExpr) {
1004 EventInfo ei = ((EventExpr) InstanceExpr).EventInfo;
1006 Expression ml = MemberLookup (
1007 ec, ec.ContainerType, ei.Name,
1008 MemberTypes.Event, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
1012 // If this is the case, then the Event does not belong
1013 // to this Type and so, according to the spec
1014 // cannot be accessed directly
1016 // Note that target will not appear as an EventExpr
1017 // in the case it is being referenced within the same type container;
1018 // it will appear as a FieldExpr in that case.
1021 Assign.error70 (ei, loc);
1027 Type del_type = InstanceExpr.Type;
1028 if (del_type == null)
1031 if (Arguments != null){
1032 foreach (Argument a in Arguments){
1033 if (!a.Resolve (ec, loc))
1038 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1041 Expression lookup = Expression.MemberLookup (ec, del_type, "Invoke", loc);
1042 if (!(lookup is MethodGroupExpr)) {
1043 Report.Error (-100, loc, "Internal error: could not find Invoke method!");
1047 method = ((MethodGroupExpr) lookup).Methods [0];
1048 type = ((MethodInfo) method).ReturnType;
1049 eclass = ExprClass.Value;
1054 public override void Emit (EmitContext ec)
1057 // Invocation on delegates call the virtual Invoke member
1058 // so we are always `instance' calls
1060 Invocation.EmitCall (ec, false, false, InstanceExpr, method, Arguments, loc);
1063 public override void EmitStatement (EmitContext ec)
1067 // Pop the return value if there is one
1069 if (method is MethodInfo){
1070 if (((MethodInfo) method).ReturnType != TypeManager.void_type)
1071 ec.ig.Emit (OpCodes.Pop);