2009-03-11 Zoltan Varga <vargaz@gmail.com>
[mcs.git] / mcs / delegate.cs
blob6c60659b99ae9722b06543426fa790b138c4df0d
1 //
2 // delegate.cs: Delegate Handler
3 //
4 // Authors:
5 // Ravi Pratap (ravi@ximian.com)
6 // Miguel de Icaza (miguel@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
8 //
9 // Dual licensed under the terms of the MIT X11 or GNU GPL
11 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
12 // Copyright 2003-2008 Novell, Inc (http://www.ximian.com)
15 using System;
16 using System.Collections;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Text;
21 namespace Mono.CSharp {
23 /// <summary>
24 /// Holds Delegates
25 /// </summary>
26 public class Delegate : DeclSpace, IMemberContainer
28 FullNamedExpression ReturnType;
29 public ParametersCompiled Parameters;
31 public ConstructorBuilder ConstructorBuilder;
32 public MethodBuilder InvokeBuilder;
33 public MethodBuilder BeginInvokeBuilder;
34 public MethodBuilder EndInvokeBuilder;
36 Type ret_type;
38 static string[] attribute_targets = new string [] { "type", "return" };
40 Expression instance_expr;
41 MethodBase delegate_method;
42 ReturnParameter return_attributes;
44 MemberCache member_cache;
46 const MethodAttributes mattr = MethodAttributes.Public | MethodAttributes.HideBySig |
47 MethodAttributes.Virtual | MethodAttributes.NewSlot;
49 const int AllowedModifiers =
50 Modifiers.NEW |
51 Modifiers.PUBLIC |
52 Modifiers.PROTECTED |
53 Modifiers.INTERNAL |
54 Modifiers.UNSAFE |
55 Modifiers.PRIVATE;
57 public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
58 int mod_flags, MemberName name, ParametersCompiled param_list,
59 Attributes attrs)
60 : base (ns, parent, name, attrs)
63 this.ReturnType = type;
64 ModFlags = Modifiers.Check (AllowedModifiers, mod_flags,
65 IsTopLevel ? Modifiers.INTERNAL :
66 Modifiers.PRIVATE, name.Location);
67 Parameters = param_list;
70 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
72 if (a.Target == AttributeTargets.ReturnValue) {
73 if (return_attributes == null)
74 return_attributes = new ReturnParameter (InvokeBuilder, Location);
76 return_attributes.ApplyAttributeBuilder (a, cb, pa);
77 return;
80 base.ApplyAttributeBuilder (a, cb, pa);
83 public override TypeBuilder DefineType ()
85 if (TypeBuilder != null)
86 return TypeBuilder;
88 if (IsTopLevel) {
89 if (TypeManager.NamespaceClash (Name, Location))
90 return null;
92 ModuleBuilder builder = CodeGen.Module.Builder;
94 TypeBuilder = builder.DefineType (
95 Name, TypeAttr, TypeManager.multicast_delegate_type);
96 } else {
97 TypeBuilder builder = Parent.TypeBuilder;
99 string name = Name.Substring (1 + Name.LastIndexOf ('.'));
100 TypeBuilder = builder.DefineNestedType (
101 name, TypeAttr, TypeManager.multicast_delegate_type);
104 TypeManager.AddUserType (this);
106 #if GMCS_SOURCE
107 if (IsGeneric) {
108 string[] param_names = new string [TypeParameters.Length];
109 for (int i = 0; i < TypeParameters.Length; i++)
110 param_names [i] = TypeParameters [i].Name;
112 GenericTypeParameterBuilder[] gen_params;
113 gen_params = TypeBuilder.DefineGenericParameters (param_names);
115 int offset = CountTypeParameters - CurrentTypeParameters.Length;
116 for (int i = offset; i < gen_params.Length; i++)
117 CurrentTypeParameters [i - offset].Define (gen_params [i]);
119 foreach (TypeParameter type_param in CurrentTypeParameters) {
120 if (!type_param.Resolve (this))
121 return null;
124 Expression current = new SimpleName (
125 MemberName.Basename, TypeParameters, Location);
126 current = current.ResolveAsTypeTerminal (this, false);
127 if (current == null)
128 return null;
130 CurrentType = current.Type;
132 #endif
134 return TypeBuilder;
137 public override bool Define ()
139 #if GMCS_SOURCE
140 if (IsGeneric) {
141 foreach (TypeParameter type_param in TypeParameters) {
142 if (!type_param.Resolve (this))
143 return false;
146 foreach (TypeParameter type_param in TypeParameters) {
147 if (!type_param.DefineType (this))
148 return false;
151 #endif
152 member_cache = new MemberCache (TypeManager.multicast_delegate_type, this);
154 // FIXME: POSSIBLY make this static, as it is always constant
156 Type [] const_arg_types = new Type [2];
157 const_arg_types [0] = TypeManager.object_type;
158 const_arg_types [1] = TypeManager.intptr_type;
160 const MethodAttributes ctor_mattr = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName |
161 MethodAttributes.HideBySig | MethodAttributes.Public;
163 ConstructorBuilder = TypeBuilder.DefineConstructor (ctor_mattr,
164 CallingConventions.Standard,
165 const_arg_types);
167 ConstructorBuilder.DefineParameter (1, ParameterAttributes.None, "object");
168 ConstructorBuilder.DefineParameter (2, ParameterAttributes.None, "method");
170 // HACK because System.Reflection.Emit is lame
172 IParameterData [] fixed_pars = new IParameterData [] {
173 new ParameterData ("object", Parameter.Modifier.NONE),
174 new ParameterData ("method", Parameter.Modifier.NONE)
177 AParametersCollection const_parameters = new ParametersImported (
178 fixed_pars,
179 new Type[] { TypeManager.object_type, TypeManager.intptr_type });
181 TypeManager.RegisterMethod (ConstructorBuilder, const_parameters);
182 member_cache.AddMember (ConstructorBuilder, this);
184 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
187 // Here the various methods like Invoke, BeginInvoke etc are defined
189 // First, call the `out of band' special method for
190 // defining recursively any types we need:
192 if (!Parameters.Resolve (this))
193 return false;
196 // Invoke method
199 // Check accessibility
200 foreach (Type partype in Parameters.Types){
201 if (!IsAccessibleAs (partype)) {
202 Report.SymbolRelatedToPreviousError (partype);
203 Report.Error (59, Location,
204 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
205 TypeManager.CSharpName (partype),
206 GetSignatureForError ());
207 return false;
211 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
212 if (ReturnType == null)
213 return false;
215 ret_type = ReturnType.Type;
217 if (!IsAccessibleAs (ret_type)) {
218 Report.SymbolRelatedToPreviousError (ret_type);
219 Report.Error (58, Location,
220 "Inconsistent accessibility: return type `" +
221 TypeManager.CSharpName (ret_type) + "' is less " +
222 "accessible than delegate `" + GetSignatureForError () + "'");
223 return false;
226 CheckProtectedModifier ();
228 if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
229 Method.Error1599 (Location, ret_type);
230 return false;
233 #if GMCS_SOURCE
234 if (ret_type.IsGenericParameter && (ret_type.GenericParameterAttributes & GenericParameterAttributes.Contravariant) != 0) {
235 Report.Error (-33, Location, "Contravariant type parameters can only be used in input positions");
236 return false;
238 #endif
241 // We don't have to check any others because they are all
242 // guaranteed to be accessible - they are standard types.
245 CallingConventions cc = Parameters.CallingConvention;
247 InvokeBuilder = TypeBuilder.DefineMethod ("Invoke",
248 mattr,
250 ret_type,
251 Parameters.GetEmitTypes ());
253 InvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
255 TypeManager.RegisterMethod (InvokeBuilder, Parameters);
256 member_cache.AddMember (InvokeBuilder, this);
258 if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null) {
259 DefineAsyncMethods (cc);
262 return true;
265 void DefineAsyncMethods (CallingConventions cc)
268 // BeginInvoke
270 ParametersCompiled async_parameters = ParametersCompiled.MergeGenerated (Parameters, false,
271 new Parameter [] {
272 new Parameter (null, "callback", Parameter.Modifier.NONE, null, Location),
273 new Parameter (null, "object", Parameter.Modifier.NONE, null, Location)
275 new Type [] {
276 TypeManager.asynccallback_type,
277 TypeManager.object_type
281 BeginInvokeBuilder = TypeBuilder.DefineMethod ("BeginInvoke",
282 mattr, cc, TypeManager.iasyncresult_type, async_parameters.GetEmitTypes ());
284 BeginInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
285 TypeManager.RegisterMethod (BeginInvokeBuilder, async_parameters);
286 member_cache.AddMember (BeginInvokeBuilder, this);
289 // EndInvoke is a bit more interesting, all the parameters labeled as
290 // out or ref have to be duplicated here.
294 // Define parameters, and count out/ref parameters
296 ParametersCompiled end_parameters;
297 int out_params = 0;
299 foreach (Parameter p in Parameters.FixedParameters) {
300 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
301 ++out_params;
304 if (out_params > 0) {
305 Type [] end_param_types = new Type [out_params];
306 Parameter[] end_params = new Parameter [out_params];
308 int param = 0;
309 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
310 Parameter p = Parameters [i];
311 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
312 continue;
314 end_param_types [param] = Parameters.Types [i];
315 end_params [param] = p;
316 ++param;
318 end_parameters = ParametersCompiled.CreateFullyResolved (end_params, end_param_types);
319 } else {
320 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
323 end_parameters = ParametersCompiled.MergeGenerated (end_parameters, false,
324 new Parameter (null, "result", Parameter.Modifier.NONE, null, Location), TypeManager.iasyncresult_type);
327 // Create method, define parameters, register parameters with type system
329 EndInvokeBuilder = TypeBuilder.DefineMethod ("EndInvoke", mattr, cc, ret_type, end_parameters.GetEmitTypes ());
330 EndInvokeBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
332 end_parameters.ApplyAttributes (EndInvokeBuilder);
333 TypeManager.RegisterMethod (EndInvokeBuilder, end_parameters);
334 member_cache.AddMember (EndInvokeBuilder, this);
337 public override void Emit ()
339 Parameters.ApplyAttributes (InvokeBuilder);
341 if (BeginInvokeBuilder != null) {
342 ParametersCompiled p = (ParametersCompiled) TypeManager.GetParameterData (BeginInvokeBuilder);
343 p.ApplyAttributes (BeginInvokeBuilder);
346 if (OptAttributes != null) {
347 OptAttributes.Emit ();
350 base.Emit ();
353 protected override TypeAttributes TypeAttr {
354 get {
355 return Modifiers.TypeAttr (ModFlags, IsTopLevel) |
356 TypeAttributes.Class | TypeAttributes.Sealed |
357 base.TypeAttr;
361 public override string[] ValidAttributeTargets {
362 get {
363 return attribute_targets;
367 //TODO: duplicate
368 protected override bool VerifyClsCompliance ()
370 if (!base.VerifyClsCompliance ()) {
371 return false;
374 Parameters.VerifyClsCompliance ();
376 if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
377 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
378 GetSignatureForError ());
380 return true;
384 public static ConstructorInfo GetConstructor (Type container_type, Type delegate_type)
386 Type dt = delegate_type;
387 #if GMCS_SOURCE
388 Type[] g_args = null;
389 if (delegate_type.IsGenericType) {
390 g_args = delegate_type.GetGenericArguments ();
391 delegate_type = delegate_type.GetGenericTypeDefinition ();
393 #endif
395 Delegate d = TypeManager.LookupDelegate (delegate_type);
396 if (d != null) {
397 #if GMCS_SOURCE
398 if (g_args != null)
399 return TypeBuilder.GetConstructor (dt, d.ConstructorBuilder);
400 #endif
401 return d.ConstructorBuilder;
404 Expression ml = Expression.MemberLookup (container_type,
405 null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
406 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
408 MethodGroupExpr mg = ml as MethodGroupExpr;
409 if (mg == null) {
410 Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
411 // FIXME: null will cause a crash later
412 return null;
415 return (ConstructorInfo) mg.Methods[0];
419 // Returns the MethodBase for "Invoke" from a delegate type, this is used
420 // to extract the signature of a delegate.
422 public static MethodInfo GetInvokeMethod (Type container_type, Type delegate_type)
424 Type dt = delegate_type;
425 #if GMCS_SOURCE
426 Type[] g_args = null;
427 if (delegate_type.IsGenericType) {
428 g_args = delegate_type.GetGenericArguments ();
429 delegate_type = delegate_type.GetGenericTypeDefinition ();
431 #endif
432 Delegate d = TypeManager.LookupDelegate (delegate_type);
433 MethodInfo invoke;
434 if (d != null) {
435 #if GMCS_SOURCE
436 if (g_args != null) {
437 invoke = TypeBuilder.GetMethod (dt, d.InvokeBuilder);
438 #if MS_COMPATIBLE
439 ParametersCompiled p = (ParametersCompiled) d.Parameters.InflateTypes (g_args, g_args);
440 TypeManager.RegisterMethod (invoke, p);
441 #endif
442 return invoke;
444 #endif
445 return d.InvokeBuilder;
448 Expression ml = Expression.MemberLookup (container_type, null, dt,
449 "Invoke", Location.Null);
451 MethodGroupExpr mg = ml as MethodGroupExpr;
452 if (mg == null) {
453 Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
454 // FIXME: null will cause a crash later
455 return null;
458 invoke = (MethodInfo) mg.Methods[0];
459 #if MS_COMPATIBLE
460 if (g_args != null) {
461 AParametersCollection p = TypeManager.GetParameterData (invoke);
462 p = p.InflateTypes (g_args, g_args);
463 TypeManager.RegisterMethod (invoke, p);
464 return invoke;
466 #endif
468 return invoke;
472 // 15.2 Delegate compatibility
474 public static bool IsTypeCovariant (Expression a, Type b)
477 // For each value parameter (a parameter with no ref or out modifier), an
478 // identity conversion or implicit reference conversion exists from the
479 // parameter type in D to the corresponding parameter type in M
481 if (a.Type == b)
482 return true;
484 if (RootContext.Version == LanguageVersion.ISO_1)
485 return false;
487 return Convert.ImplicitReferenceConversionExists (a, b);
490 /// <summary>
491 /// Verifies whether the method in question is compatible with the delegate
492 /// Returns the method itself if okay and null if not.
493 /// </summary>
494 public static MethodBase VerifyMethod (Type container_type, Type delegate_type,
495 MethodGroupExpr old_mg, MethodBase mb)
497 bool is_method_definition = TypeManager.IsGenericMethodDefinition (mb);
499 MethodInfo invoke_mb = GetInvokeMethod (container_type, delegate_type);
500 if (invoke_mb == null)
501 return null;
503 if (is_method_definition)
504 invoke_mb = (MethodInfo) TypeManager.DropGenericMethodArguments (invoke_mb);
506 AParametersCollection invoke_pd = TypeManager.GetParameterData (invoke_mb);
508 #if GMCS_SOURCE
509 if (!is_method_definition && old_mg.type_arguments == null &&
510 !TypeManager.InferTypeArguments (invoke_pd, ref mb))
511 return null;
512 #endif
513 AParametersCollection pd = TypeManager.GetParameterData (mb);
515 if (invoke_pd.Count != pd.Count)
516 return null;
518 for (int i = pd.Count; i > 0; ) {
519 i--;
521 Type invoke_pd_type = invoke_pd.Types [i];
522 Type pd_type = pd.Types [i];
523 Parameter.Modifier invoke_pd_type_mod = invoke_pd.FixedParameters [i].ModFlags;
524 Parameter.Modifier pd_type_mod = pd.FixedParameters [i].ModFlags;
526 invoke_pd_type_mod &= ~Parameter.Modifier.PARAMS;
527 pd_type_mod &= ~Parameter.Modifier.PARAMS;
529 if (invoke_pd_type_mod != pd_type_mod)
530 return null;
532 if (TypeManager.IsEqual (invoke_pd_type, pd_type))
533 continue;
535 if (IsTypeCovariant (new EmptyExpression (invoke_pd_type), pd_type))
536 continue;
538 return null;
541 Type invoke_mb_retval = ((MethodInfo) invoke_mb).ReturnType;
542 Type mb_retval = ((MethodInfo) mb).ReturnType;
543 if (TypeManager.TypeToCoreType (invoke_mb_retval) == TypeManager.TypeToCoreType (mb_retval))
544 return mb;
546 //if (!IsTypeCovariant (mb_retval, invoke_mb_retval))
547 // return null;
549 if (RootContext.Version == LanguageVersion.ISO_1)
550 return null;
552 return mb;
555 // <summary>
556 // Verifies whether the invocation arguments are compatible with the
557 // delegate's target method
558 // </summary>
559 public static bool VerifyApplicability (EmitContext ec, Type delegate_type,
560 ArrayList args, Location loc)
562 int arg_count;
564 if (args == null)
565 arg_count = 0;
566 else
567 arg_count = args.Count;
569 MethodBase mb = GetInvokeMethod (ec.ContainerType, delegate_type);
570 MethodGroupExpr me = new MethodGroupExpr (new MemberInfo [] { mb }, delegate_type, loc);
572 AParametersCollection pd = TypeManager.GetParameterData (mb);
574 int pd_count = pd.Count;
576 bool params_method = pd.HasParams;
577 bool is_params_applicable = false;
578 bool is_applicable = me.IsApplicable (ec, args, arg_count, ref mb, ref is_params_applicable) == 0;
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.ToString ());
583 return false;
586 return me.VerifyArgumentsCompat (
587 ec, ref args, arg_count, mb,
588 is_params_applicable || (!is_applicable && params_method),
589 false, loc);
592 public static string FullDelegateDesc (MethodBase invoke_method)
594 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
597 public override MemberCache MemberCache {
598 get {
599 return member_cache;
603 public Expression InstanceExpression {
604 get {
605 return instance_expr;
607 set {
608 instance_expr = value;
612 public MethodBase TargetMethod {
613 get {
614 return delegate_method;
616 set {
617 delegate_method = value;
621 public Type TargetReturnType {
622 get {
623 return ret_type;
627 public override AttributeTargets AttributeTargets {
628 get {
629 return AttributeTargets.Delegate;
634 // Represents header string for documentation comment.
636 public override string DocCommentHeader {
637 get { return "T:"; }
640 #region IMemberContainer Members
642 string IMemberContainer.Name
644 get { throw new NotImplementedException (); }
647 Type IMemberContainer.Type
649 get { throw new NotImplementedException (); }
652 MemberCache IMemberContainer.BaseCache
654 get { throw new NotImplementedException (); }
657 bool IMemberContainer.IsInterface {
658 get {
659 return false;
663 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
665 throw new NotImplementedException ();
668 #endregion
672 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
674 public abstract class DelegateCreation : Expression, MethodGroupExpr.IErrorHandler
676 protected ConstructorInfo constructor_method;
677 protected MethodInfo delegate_method;
678 // We keep this to handle IsBase only
679 protected MethodGroupExpr method_group;
680 protected Expression delegate_instance_expression;
682 public static ArrayList CreateDelegateMethodArguments (MethodInfo invoke_method, Location loc)
684 AParametersCollection pd = TypeManager.GetParameterData (invoke_method);
685 ArrayList delegate_arguments = new ArrayList (pd.Count);
686 for (int i = 0; i < pd.Count; ++i) {
687 Argument.AType atype_modifier;
688 Type atype = pd.Types [i];
689 switch (pd.FixedParameters [i].ModFlags) {
690 case Parameter.Modifier.REF:
691 atype_modifier = Argument.AType.Ref;
692 //atype = atype.GetElementType ();
693 break;
694 case Parameter.Modifier.OUT:
695 atype_modifier = Argument.AType.Out;
696 //atype = atype.GetElementType ();
697 break;
698 case Parameter.Modifier.ARGLIST:
699 // __arglist is not valid
700 throw new InternalErrorException ("__arglist modifier");
701 default:
702 atype_modifier = Argument.AType.Expression;
703 break;
705 delegate_arguments.Add (new Argument (new TypeExpression (atype, loc), atype_modifier));
707 return delegate_arguments;
710 public override Expression CreateExpressionTree (EmitContext ec)
712 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
714 ArrayList args = new ArrayList (3);
715 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
716 args.Add (new Argument (new NullLiteral (loc)));
717 args.Add (new Argument (new TypeOfMethodInfo (delegate_method, loc)));
718 Expression e = new Invocation (ma, args).Resolve (ec);
719 if (e == null)
720 return null;
722 e = Convert.ExplicitConversion (ec, e, type, loc);
723 if (e == null)
724 return null;
726 return e.CreateExpressionTree (ec);
729 public override Expression DoResolve (EmitContext ec)
731 constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
733 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
734 method_group.DelegateType = type;
735 method_group.CustomErrorHandler = this;
737 ArrayList arguments = CreateDelegateMethodArguments (invoke_method, loc);
738 method_group = method_group.OverloadResolve (ec, ref arguments, false, loc);
739 if (method_group == null)
740 return null;
742 delegate_method = (MethodInfo) method_group;
744 if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
745 Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
746 TypeManager.GetFullNameSignature (delegate_method));
747 return null;
750 Invocation.IsSpecialMethodInvocation (delegate_method, loc);
752 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
753 if (emg != null) {
754 delegate_instance_expression = emg.ExtensionExpression;
755 Type e_type = delegate_instance_expression.Type;
756 if (TypeManager.IsValueType (e_type)) {
757 Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
758 TypeManager.CSharpSignature (delegate_method), TypeManager.CSharpName (e_type));
762 Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
763 Expression ret_expr = new TypeExpression (rt, loc);
764 if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
765 Error_ConversionFailed (ec, delegate_method, ret_expr);
768 if (Invocation.IsMethodExcluded (delegate_method, loc)) {
769 Report.SymbolRelatedToPreviousError (delegate_method);
770 MethodOrOperator m = TypeManager.GetMethod (delegate_method) as MethodOrOperator;
771 if (m != null && m.IsPartialDefinition) {
772 Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
773 TypeManager.CSharpSignature (delegate_method));
774 } else {
775 Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
776 TypeManager.CSharpSignature (delegate_method));
780 DoResolveInstanceExpression (ec);
781 eclass = ExprClass.Value;
782 return this;
785 void DoResolveInstanceExpression (EmitContext ec)
788 // Argument is another delegate
790 if (delegate_instance_expression != null)
791 return;
793 Expression instance = method_group.InstanceExpression;
794 if (instance != null && instance != EmptyExpression.Null) {
795 delegate_instance_expression = instance;
796 Type instance_type = delegate_instance_expression.Type;
797 if (TypeManager.IsValueType (instance_type) || TypeManager.IsGenericParameter (instance_type)) {
798 delegate_instance_expression = new BoxedCast (
799 delegate_instance_expression, TypeManager.object_type);
801 } else if (!delegate_method.IsStatic && !ec.IsStatic) {
802 delegate_instance_expression = ec.GetThis (loc);
806 public override void Emit (EmitContext ec)
808 if (delegate_instance_expression == null)
809 ec.ig.Emit (OpCodes.Ldnull);
810 else
811 delegate_instance_expression.Emit (ec);
813 if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
814 ec.ig.Emit (OpCodes.Dup);
815 ec.ig.Emit (OpCodes.Ldvirtftn, delegate_method);
816 } else {
817 ec.ig.Emit (OpCodes.Ldftn, delegate_method);
820 ec.ig.Emit (OpCodes.Newobj, constructor_method);
823 void Error_ConversionFailed (EmitContext ec, MethodBase method, Expression return_type)
825 MethodInfo invoke_method = Delegate.GetInvokeMethod (ec.ContainerType, type);
826 string member_name = delegate_instance_expression != null ?
827 Delegate.FullDelegateDesc (method) :
828 TypeManager.GetFullNameSignature (method);
830 Report.SymbolRelatedToPreviousError (type);
831 Report.SymbolRelatedToPreviousError (method);
832 if (RootContext.Version == LanguageVersion.ISO_1) {
833 Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
834 TypeManager.CSharpName (((MethodInfo) method).ReturnType), member_name,
835 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
836 return;
838 if (return_type == null) {
839 Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
840 member_name, Delegate.FullDelegateDesc (invoke_method));
841 return;
844 Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
845 return_type.GetSignatureForError (), member_name,
846 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
849 public static MethodBase ImplicitStandardConversionExists (MethodGroupExpr mg, Type target_type)
851 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
852 return null;
854 foreach (MethodInfo mi in mg.Methods){
855 MethodBase mb = Delegate.VerifyMethod (mg.DeclaringType, target_type, mg, mi);
856 if (mb != null)
857 return mb;
859 return null;
862 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
864 if (delegate_instance_expression != null)
865 delegate_instance_expression.MutateHoistedGenericType (storey);
867 delegate_method = storey.MutateGenericMethod (delegate_method);
868 constructor_method = storey.MutateConstructor (constructor_method);
871 #region IErrorHandler Members
873 public bool NoExactMatch (EmitContext ec, MethodBase method)
875 if (TypeManager.IsGenericMethod (method))
876 return false;
878 Error_ConversionFailed (ec, method, null);
879 return true;
882 public bool AmbiguousCall (MethodBase ambiguous)
884 return false;
887 #endregion
891 // Created from the conversion code
893 public class ImplicitDelegateCreation : DelegateCreation
895 ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
897 type = t;
898 this.method_group = mg;
899 loc = l;
902 static public Expression Create (EmitContext ec, MethodGroupExpr mge,
903 Type target_type, Location loc)
905 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
906 return d.DoResolve (ec);
911 // A delegate-creation-expression, invoked from the `New' class
913 public class NewDelegate : DelegateCreation
915 public ArrayList Arguments;
918 // This constructor is invoked from the `New' expression
920 public NewDelegate (Type type, ArrayList Arguments, Location loc)
922 this.type = type;
923 this.Arguments = Arguments;
924 this.loc = loc;
927 public override Expression DoResolve (EmitContext ec)
929 if (Arguments == null || Arguments.Count != 1) {
930 Error_InvalidDelegateArgument ();
931 return null;
934 Argument a = (Argument) Arguments [0];
935 if (!a.ResolveMethodGroup (ec))
936 return null;
938 Expression e = a.Expr;
940 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
941 if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
942 e = ame.Compatible (ec, type);
943 if (e == null)
944 return null;
946 return e.Resolve (ec);
949 method_group = e as MethodGroupExpr;
950 if (method_group == null) {
951 if (!TypeManager.IsDelegateType (e.Type)) {
952 e.Error_UnexpectedKind (ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
953 return null;
957 // An argument is not a method but another delegate
959 delegate_instance_expression = e;
960 method_group = new MethodGroupExpr (new MemberInfo [] {
961 Delegate.GetInvokeMethod (ec.ContainerType, e.Type) }, e.Type, loc);
964 return base.DoResolve (ec);
967 void Error_InvalidDelegateArgument ()
969 Report.Error (149, loc, "Method name expected");
973 public class DelegateInvocation : ExpressionStatement {
975 readonly Expression InstanceExpr;
976 readonly ArrayList Arguments;
978 MethodInfo method;
980 public DelegateInvocation (Expression instance_expr, ArrayList args, Location loc)
982 this.InstanceExpr = instance_expr;
983 this.Arguments = args;
984 this.loc = loc;
987 public override Expression CreateExpressionTree (EmitContext ec)
989 ArrayList args;
990 if (Arguments == null)
991 args = new ArrayList (1);
992 else
993 args = new ArrayList (Arguments.Count + 1);
995 args.Add (new Argument (InstanceExpr.CreateExpressionTree (ec)));
996 if (Arguments != null) {
997 foreach (Argument a in Arguments)
998 args.Add (new Argument (a.Expr.CreateExpressionTree (ec)));
1001 return CreateExpressionFactoryCall ("Invoke", args);
1004 public override Expression DoResolve (EmitContext ec)
1006 if (InstanceExpr is EventExpr) {
1007 ((EventExpr) InstanceExpr).Error_CannotAssign ();
1008 return null;
1011 Type del_type = InstanceExpr.Type;
1012 if (del_type == null)
1013 return null;
1015 if (Arguments != null){
1016 foreach (Argument a in Arguments){
1017 if (!a.Resolve (ec, loc))
1018 return null;
1022 if (!Delegate.VerifyApplicability (ec, del_type, Arguments, loc))
1023 return null;
1025 method = Delegate.GetInvokeMethod (ec.ContainerType, del_type);
1026 type = TypeManager.TypeToCoreType (method.ReturnType);
1027 eclass = ExprClass.Value;
1029 return this;
1032 public override void Emit (EmitContext ec)
1035 // Invocation on delegates call the virtual Invoke member
1036 // so we are always `instance' calls
1038 Invocation.EmitCall (ec, false, InstanceExpr, method, Arguments, loc);
1041 public override void EmitStatement (EmitContext ec)
1043 Emit (ec);
1045 // Pop the return value if there is one
1047 if (type != TypeManager.void_type)
1048 ec.ig.Emit (OpCodes.Pop);
1051 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1053 method = storey.MutateGenericMethod (method);
1054 type = storey.MutateType (type);
1056 if (Arguments != null) {
1057 foreach (Argument a in Arguments) {
1058 a.Expr.MutateHoistedGenericType (storey);
1062 InstanceExpr.MutateHoistedGenericType (storey);