2 // delegate.cs: Delegate Handler
5 // Ravi Pratap (ravi@ximian.com)
6 // Miguel de Icaza (miguel@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // Dual licensed under the terms of the MIT X11 or GNU GPL
11 // Copyright 2001 Ximian, Inc (http://www.ximian.com)
12 // Copyright 2003-2009 Novell, Inc (http://www.novell.com)
13 // Copyright 2011 Xamarin Inc
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using System.Reflection;
23 using System.Reflection.Emit;
26 namespace Mono.CSharp {
29 // Delegate container implementation
31 public class Delegate : TypeContainer, IParametersMember
33 FullNamedExpression ReturnType;
34 readonly ParametersCompiled parameters;
36 Constructor Constructor;
38 Method BeginInvokeBuilder;
39 Method EndInvokeBuilder;
41 static readonly string[] attribute_targets = new string [] { "type", "return" };
43 public static readonly string InvokeMethodName = "Invoke";
45 Expression instance_expr;
46 ReturnParameter return_attributes;
48 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
50 const Modifiers AllowedModifiers =
58 public Delegate (NamespaceContainer ns, DeclSpace parent, FullNamedExpression type,
59 Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
61 : base (ns, parent, name, attrs, MemberKind.Delegate)
64 this.ReturnType = type;
65 ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
66 IsTopLevel ? Modifiers.INTERNAL :
67 Modifiers.PRIVATE, name.Location, Report);
68 parameters = param_list;
69 spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
73 public TypeSpec MemberType {
75 return ReturnType.Type;
79 public AParametersCollection Parameters {
86 public override void Accept (StructuralVisitor visitor)
91 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
93 if (a.Target == AttributeTargets.ReturnValue) {
94 if (return_attributes == null)
95 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
97 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
101 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
104 public override AttributeTargets AttributeTargets {
106 return AttributeTargets.Delegate;
110 protected override bool DoDefineMembers ()
112 var builtin_types = Compiler.BuiltinTypes;
114 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
116 new Parameter (new TypeExpression (builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
117 new Parameter (new TypeExpression (builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
120 builtin_types.Object,
125 Constructor = new Constructor (this, Constructor.ConstructorName,
126 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
127 Constructor.Define ();
130 // Here the various methods like Invoke, BeginInvoke etc are defined
132 // First, call the `out of band' special method for
133 // defining recursively any types we need:
137 if (!p.Resolve (this))
144 // Check accessibility
145 foreach (var partype in p.Types) {
146 if (!IsAccessibleAs (partype)) {
147 Report.SymbolRelatedToPreviousError (partype);
148 Report.Error (59, Location,
149 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
150 TypeManager.CSharpName (partype), GetSignatureForError ());
154 var ret_type = ReturnType.ResolveAsType (this);
155 if (ret_type == null)
159 // We don't have to check any others because they are all
160 // guaranteed to be accessible - they are standard types.
162 if (!IsAccessibleAs (ret_type)) {
163 Report.SymbolRelatedToPreviousError (ret_type);
164 Report.Error (58, Location,
165 "Inconsistent accessibility: return type `" +
166 TypeManager.CSharpName (ret_type) + "' is less " +
167 "accessible than delegate `" + GetSignatureForError () + "'");
171 CheckProtectedModifier ();
173 if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) {
174 Method.Error1599 (Location, ret_type, Report);
178 TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
180 var resolved_rt = new TypeExpression (ret_type, Location);
181 InvokeBuilder = new Method (this, null, resolved_rt, MethodModifiers, new MemberName (InvokeMethodName), p, null);
182 InvokeBuilder.Define ();
185 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
187 if (!IsCompilerGenerated) {
188 DefineAsyncMethods (Parameters.CallingConvention, resolved_rt);
194 void DefineAsyncMethods (CallingConventions cc, TypeExpression returnType)
196 var iasync_result = Module.PredefinedTypes.IAsyncResult;
197 var async_callback = Module.PredefinedTypes.AsyncCallback;
200 // It's ok when async types don't exist, the delegate will have Invoke method only
202 if (!iasync_result.Define () || !async_callback.Define ())
208 ParametersCompiled async_parameters;
209 if (Parameters.Count == 0) {
210 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
212 var compiled = new Parameter[Parameters.Count];
213 for (int i = 0; i < compiled.Length; ++i) {
214 var p = parameters[i];
215 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
217 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
218 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
221 async_parameters = new ParametersCompiled (compiled);
224 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
226 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
227 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, Location), "object", Parameter.Modifier.NONE, null, Location)
230 async_callback.TypeSpec,
231 Compiler.BuiltinTypes.Object
235 BeginInvokeBuilder = new Method (this, null,
236 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
237 new MemberName ("BeginInvoke"), async_parameters, null);
238 BeginInvokeBuilder.Define ();
241 // EndInvoke is a bit more interesting, all the parameters labeled as
242 // out or ref have to be duplicated here.
246 // Define parameters, and count out/ref parameters
248 ParametersCompiled end_parameters;
251 foreach (Parameter p in Parameters.FixedParameters) {
252 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
256 if (out_params > 0) {
257 Parameter[] end_params = new Parameter[out_params];
260 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
261 Parameter p = parameters [i];
262 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
265 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
267 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
268 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
271 end_parameters = new ParametersCompiled (end_params);
273 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
276 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
278 new TypeExpression (iasync_result.TypeSpec, Location),
279 "result", Parameter.Modifier.NONE, null, Location),
280 iasync_result.TypeSpec);
283 // Create method, define parameters, register parameters with type system
285 EndInvokeBuilder = new Method (this, null, returnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
286 EndInvokeBuilder.Define ();
289 public override void DefineConstants ()
291 if (!Parameters.IsEmpty) {
292 parameters.ResolveDefaultValues (this);
296 public override void EmitType ()
298 if (ReturnType.Type != null) {
299 if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
300 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
301 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
302 } else if (ReturnType.Type.HasDynamicElement) {
303 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
304 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
307 ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
310 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
311 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
313 parameters.CheckConstraints (this);
314 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
315 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
317 if (BeginInvokeBuilder != null) {
318 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
319 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
321 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
322 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
325 if (OptAttributes != null) {
326 OptAttributes.Emit ();
332 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
334 base_type = Compiler.BuiltinTypes.MulticastDelegate;
339 protected override TypeAttributes TypeAttr {
341 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
342 TypeAttributes.Class | TypeAttributes.Sealed |
347 public override string[] ValidAttributeTargets {
349 return attribute_targets;
354 protected override bool VerifyClsCompliance ()
356 if (!base.VerifyClsCompliance ()) {
360 parameters.VerifyClsCompliance (this);
362 if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
363 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
364 GetSignatureForError ());
370 public static MethodSpec GetConstructor (TypeSpec delType)
372 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
373 return (MethodSpec) ctor;
377 // Returns the "Invoke" from a delegate type
379 public static MethodSpec GetInvokeMethod (TypeSpec delType)
381 var invoke = MemberCache.FindMember (delType,
382 MemberFilter.Method (InvokeMethodName, 0, null, null),
383 BindingRestriction.DeclaredOnly);
385 return (MethodSpec) invoke;
388 public static AParametersCollection GetParameters (TypeSpec delType)
390 var invoke_mb = GetInvokeMethod (delType);
391 return invoke_mb.Parameters;
395 // 15.2 Delegate compatibility
397 public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
400 // For each value parameter (a parameter with no ref or out modifier), an
401 // identity conversion or implicit reference conversion exists from the
402 // parameter type in D to the corresponding parameter type in M
407 if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
410 if (a.IsGenericParameter && b.IsGenericParameter)
413 return Convert.ImplicitReferenceConversionExists (a, b);
416 public static string FullDelegateDesc (MethodSpec invoke_method)
418 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
421 public Expression InstanceExpression {
423 return instance_expr;
426 instance_expr = value;
432 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
434 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
436 protected MethodSpec constructor_method;
437 protected MethodGroupExpr method_group;
439 public override bool ContainsEmitWithAwait ()
444 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, TypeSpec[] types, Location loc)
446 Arguments delegate_arguments = new Arguments (pd.Count);
447 for (int i = 0; i < pd.Count; ++i) {
448 Argument.AType atype_modifier;
449 switch (pd.FixedParameters [i].ModFlags) {
450 case Parameter.Modifier.REF:
451 atype_modifier = Argument.AType.Ref;
453 case Parameter.Modifier.OUT:
454 atype_modifier = Argument.AType.Out;
461 delegate_arguments.Add (new Argument (new TypeExpression (types [i], loc), atype_modifier));
464 return delegate_arguments;
467 public override Expression CreateExpressionTree (ResolveContext ec)
469 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
471 Arguments args = new Arguments (3);
472 args.Add (new Argument (new TypeOf (type, loc)));
474 if (method_group.InstanceExpression == null)
475 args.Add (new Argument (new NullLiteral (loc)));
477 args.Add (new Argument (method_group.InstanceExpression));
479 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
480 Expression e = new Invocation (ma, args).Resolve (ec);
484 e = Convert.ExplicitConversion (ec, e, type, loc);
488 return e.CreateExpressionTree (ec);
491 protected override Expression DoResolve (ResolveContext ec)
493 constructor_method = Delegate.GetConstructor (type);
495 var invoke_method = Delegate.GetInvokeMethod (type);
497 Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, invoke_method.Parameters.Types, loc);
498 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
499 if (method_group == null)
502 var delegate_method = method_group.BestCandidate;
504 if (delegate_method.DeclaringType.IsNullableType) {
505 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
506 delegate_method.GetSignatureForError ());
510 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
512 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
514 method_group.InstanceExpression = emg.ExtensionExpression;
515 TypeSpec e_type = emg.ExtensionExpression.Type;
516 if (TypeSpec.IsValueType (e_type)) {
517 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
518 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
522 TypeSpec rt = delegate_method.ReturnType;
523 if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
524 Expression ret_expr = new TypeExpression (rt, loc);
525 Error_ConversionFailed (ec, delegate_method, ret_expr);
528 if (delegate_method.IsConditionallyExcluded (ec.Module.Compiler, loc)) {
529 ec.Report.SymbolRelatedToPreviousError (delegate_method);
530 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
531 if (m != null && m.IsPartialDefinition) {
532 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
533 delegate_method.GetSignatureForError ());
535 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
536 TypeManager.CSharpSignature (delegate_method));
540 var expr = method_group.InstanceExpression;
541 if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
542 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
544 eclass = ExprClass.Value;
548 public override void Emit (EmitContext ec)
550 if (method_group.InstanceExpression == null)
553 method_group.InstanceExpression.Emit (ec);
555 var delegate_method = method_group.BestCandidate;
557 // Any delegate must be sealed
558 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
559 ec.Emit (OpCodes.Dup);
560 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
562 ec.Emit (OpCodes.Ldftn, delegate_method);
565 ec.Emit (OpCodes.Newobj, constructor_method);
568 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
570 var invoke_method = Delegate.GetInvokeMethod (type);
571 string member_name = method_group.InstanceExpression != null ?
572 Delegate.FullDelegateDesc (method) :
573 TypeManager.GetFullNameSignature (method);
575 ec.Report.SymbolRelatedToPreviousError (type);
576 ec.Report.SymbolRelatedToPreviousError (method);
577 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
578 ec.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",
579 TypeManager.CSharpName (method.ReturnType), member_name,
580 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
584 if (return_type == null) {
585 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
586 member_name, Delegate.FullDelegateDesc (invoke_method));
590 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
591 return_type.GetSignatureForError (), member_name,
592 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
595 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
597 // if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
600 var invoke = Delegate.GetInvokeMethod (target_type);
602 Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, invoke.Parameters.Types, mg.Location);
603 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
606 #region IErrorHandler Members
608 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
613 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
615 Error_ConversionFailed (rc, best as MethodSpec, null);
619 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
621 Error_ConversionFailed (rc, best as MethodSpec, null);
625 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
634 // Created from the conversion code
636 public class ImplicitDelegateCreation : DelegateCreation
638 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
641 this.method_group = mg;
645 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
646 TypeSpec target_type, Location loc)
648 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
649 return d.DoResolve (ec);
654 // A delegate-creation-expression, invoked from the `New' class
656 public class NewDelegate : DelegateCreation
658 public Arguments Arguments;
661 // This constructor is invoked from the `New' expression
663 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
666 this.Arguments = Arguments;
670 protected override Expression DoResolve (ResolveContext ec)
672 if (Arguments == null || Arguments.Count != 1) {
673 ec.Report.Error (149, loc, "Method name expected");
677 Argument a = Arguments [0];
678 if (!a.ResolveMethodGroup (ec))
681 Expression e = a.Expr;
683 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
684 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
685 e = ame.Compatible (ec, type);
689 return e.Resolve (ec);
692 method_group = e as MethodGroupExpr;
693 if (method_group == null) {
694 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
695 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
696 } else if (!e.Type.IsDelegate) {
697 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
702 // An argument is not a method but another delegate
704 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
705 method_group.InstanceExpression = e;
708 return base.DoResolve (ec);
713 // Invocation converted to delegate Invoke call
715 class DelegateInvocation : ExpressionStatement
717 readonly Expression InstanceExpr;
721 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
723 this.InstanceExpr = instance_expr;
724 this.arguments = args;
728 public override bool ContainsEmitWithAwait ()
730 return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
733 public override Expression CreateExpressionTree (ResolveContext ec)
735 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
736 InstanceExpr.CreateExpressionTree (ec));
738 return CreateExpressionFactoryCall (ec, "Invoke", args);
741 protected override Expression DoResolve (ResolveContext ec)
743 TypeSpec del_type = InstanceExpr.Type;
744 if (del_type == null)
748 // Do only core overload resolution the rest of the checks has been
749 // done on primary expression
751 method = Delegate.GetInvokeMethod (del_type);
752 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
753 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
754 if (valid == null && !res.BestCandidateIsDynamic)
757 type = method.ReturnType;
758 eclass = ExprClass.Value;
762 public override void Emit (EmitContext ec)
765 // Invocation on delegates call the virtual Invoke member
766 // so we are always `instance' calls
768 var call = new CallEmitter ();
769 call.InstanceExpression = InstanceExpr;
770 call.EmitPredefined (ec, method, arguments);
773 public override void EmitStatement (EmitContext ec)
777 // Pop the return value if there is one
779 if (type.Kind != MemberKind.Void)
780 ec.Emit (OpCodes.Pop);
783 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
785 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);