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)
18 using IKVM.Reflection;
19 using IKVM.Reflection.Emit;
21 using System.Reflection;
22 using System.Reflection.Emit;
25 namespace Mono.CSharp {
28 // Delegate container implementation
30 public class Delegate : TypeContainer, IParametersMember
32 FullNamedExpression ReturnType;
33 readonly ParametersCompiled parameters;
35 Constructor Constructor;
37 Method BeginInvokeBuilder;
38 Method EndInvokeBuilder;
40 static readonly string[] attribute_targets = new string [] { "type", "return" };
42 public static readonly string InvokeMethodName = "Invoke";
44 Expression instance_expr;
45 ReturnParameter return_attributes;
47 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
49 const Modifiers AllowedModifiers =
57 public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
58 Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
60 : base (ns, parent, name, attrs, MemberKind.Delegate)
63 this.ReturnType = type;
64 ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
65 IsTopLevel ? Modifiers.INTERNAL :
66 Modifiers.PRIVATE, name.Location, Report);
67 parameters = param_list;
68 spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
72 public TypeSpec MemberType {
74 return ReturnType.Type;
78 public AParametersCollection Parameters {
85 public override void Accept (StructuralVisitor visitor)
90 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
92 if (a.Target == AttributeTargets.ReturnValue) {
93 if (return_attributes == null)
94 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
96 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
100 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
103 public override AttributeTargets AttributeTargets {
105 return AttributeTargets.Delegate;
109 protected override bool DoDefineMembers ()
111 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
113 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
114 new Parameter (new TypeExpression (TypeManager.intptr_type, Location), "method", Parameter.Modifier.NONE, null, Location)
117 TypeManager.object_type,
118 TypeManager.intptr_type
122 Constructor = new Constructor (this, Constructor.ConstructorName,
123 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
124 Constructor.Define ();
127 // Here the various methods like Invoke, BeginInvoke etc are defined
129 // First, call the `out of band' special method for
130 // defining recursively any types we need:
134 if (!p.Resolve (this))
141 // Check accessibility
142 foreach (var partype in p.Types) {
143 if (!IsAccessibleAs (partype)) {
144 Report.SymbolRelatedToPreviousError (partype);
145 Report.Error (59, Location,
146 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
147 TypeManager.CSharpName (partype), GetSignatureForError ());
151 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
152 if (ReturnType == null)
155 var ret_type = ReturnType.Type;
158 // We don't have to check any others because they are all
159 // guaranteed to be accessible - they are standard types.
161 if (!IsAccessibleAs (ret_type)) {
162 Report.SymbolRelatedToPreviousError (ret_type);
163 Report.Error (58, Location,
164 "Inconsistent accessibility: return type `" +
165 TypeManager.CSharpName (ret_type) + "' is less " +
166 "accessible than delegate `" + GetSignatureForError () + "'");
170 CheckProtectedModifier ();
172 if (Compiler.Settings.StdLib && TypeManager.IsSpecialType (ret_type)) {
173 Method.Error1599 (Location, ret_type, Report);
177 TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
179 InvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName (InvokeMethodName), p, null);
180 InvokeBuilder.Define ();
183 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
185 if (!IsCompilerGenerated) {
186 DefineAsyncMethods (Parameters.CallingConvention);
192 void DefineAsyncMethods (CallingConventions cc)
194 var iasync_result = Module.PredefinedTypes.IAsyncResult;
195 var async_callback = Module.PredefinedTypes.AsyncCallback;
198 // It's ok when async types don't exist, the delegate will have Invoke method only
200 if (!iasync_result.Define () || !async_callback.Define ())
206 ParametersCompiled async_parameters;
207 if (Parameters.Count == 0) {
208 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
210 var compiled = new Parameter[Parameters.Count];
211 for (int i = 0; i < compiled.Length; ++i) {
212 var p = parameters[i];
213 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
215 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
216 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
219 async_parameters = new ParametersCompiled (compiled);
222 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
224 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
225 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location)
228 async_callback.TypeSpec,
229 TypeManager.object_type
233 BeginInvokeBuilder = new Method (this, null,
234 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
235 new MemberName ("BeginInvoke"), async_parameters, null);
236 BeginInvokeBuilder.Define ();
239 // EndInvoke is a bit more interesting, all the parameters labeled as
240 // out or ref have to be duplicated here.
244 // Define parameters, and count out/ref parameters
246 ParametersCompiled end_parameters;
249 foreach (Parameter p in Parameters.FixedParameters) {
250 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
254 if (out_params > 0) {
255 Parameter[] end_params = new Parameter[out_params];
258 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
259 Parameter p = parameters [i];
260 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
263 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
265 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
266 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
269 end_parameters = new ParametersCompiled (end_params);
271 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
274 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
276 new TypeExpression (iasync_result.TypeSpec, Location),
277 "result", Parameter.Modifier.NONE, null, Location),
278 iasync_result.TypeSpec);
281 // Create method, define parameters, register parameters with type system
283 EndInvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
284 EndInvokeBuilder.Define ();
287 public override void DefineConstants ()
289 if (!Parameters.IsEmpty) {
290 parameters.ResolveDefaultValues (this);
294 public override void EmitType ()
296 if (ReturnType.Type != null) {
297 if (ReturnType.Type == InternalType.Dynamic) {
298 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
299 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
300 } else if (ReturnType.Type.HasDynamicElement) {
301 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
302 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
306 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
307 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
309 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
310 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
312 if (BeginInvokeBuilder != null) {
313 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
314 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
316 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
317 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
320 if (OptAttributes != null) {
321 OptAttributes.Emit ();
327 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
329 base_type = TypeManager.multicast_delegate_type;
334 protected override TypeAttributes TypeAttr {
336 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
337 TypeAttributes.Class | TypeAttributes.Sealed |
342 public override string[] ValidAttributeTargets {
344 return attribute_targets;
349 protected override bool VerifyClsCompliance ()
351 if (!base.VerifyClsCompliance ()) {
355 parameters.VerifyClsCompliance (this);
357 if (!ReturnType.Type.IsCLSCompliant ()) {
358 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
359 GetSignatureForError ());
365 public static MethodSpec GetConstructor (TypeSpec delType)
367 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
368 return (MethodSpec) ctor;
372 // Returns the "Invoke" from a delegate type
374 public static MethodSpec GetInvokeMethod (TypeSpec delType)
376 var invoke = MemberCache.FindMember (delType,
377 MemberFilter.Method (InvokeMethodName, 0, null, null),
378 BindingRestriction.DeclaredOnly);
380 return (MethodSpec) invoke;
383 public static AParametersCollection GetParameters (TypeSpec delType)
385 var invoke_mb = GetInvokeMethod (delType);
386 return invoke_mb.Parameters;
390 // 15.2 Delegate compatibility
392 public static bool IsTypeCovariant (ResolveContext rc, Expression a, TypeSpec b)
395 // For each value parameter (a parameter with no ref or out modifier), an
396 // identity conversion or implicit reference conversion exists from the
397 // parameter type in D to the corresponding parameter type in M
402 if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
405 return Convert.ImplicitReferenceConversionExists (a, b);
408 public static string FullDelegateDesc (MethodSpec invoke_method)
410 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
413 public Expression InstanceExpression {
415 return instance_expr;
418 instance_expr = value;
424 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
426 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
428 protected MethodSpec constructor_method;
429 protected MethodGroupExpr method_group;
431 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, TypeSpec[] types, Location loc)
433 Arguments delegate_arguments = new Arguments (pd.Count);
434 for (int i = 0; i < pd.Count; ++i) {
435 Argument.AType atype_modifier;
436 switch (pd.FixedParameters [i].ModFlags) {
437 case Parameter.Modifier.REF:
438 atype_modifier = Argument.AType.Ref;
440 case Parameter.Modifier.OUT:
441 atype_modifier = Argument.AType.Out;
448 delegate_arguments.Add (new Argument (new TypeExpression (types [i], loc), atype_modifier));
451 return delegate_arguments;
454 public override Expression CreateExpressionTree (ResolveContext ec)
456 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
458 Arguments args = new Arguments (3);
459 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
461 if (method_group.InstanceExpression == null)
462 args.Add (new Argument (new NullLiteral (loc)));
464 args.Add (new Argument (method_group.InstanceExpression));
466 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
467 Expression e = new Invocation (ma, args).Resolve (ec);
471 e = Convert.ExplicitConversion (ec, e, type, loc);
475 return e.CreateExpressionTree (ec);
478 protected override Expression DoResolve (ResolveContext ec)
480 constructor_method = Delegate.GetConstructor (type);
482 var invoke_method = Delegate.GetInvokeMethod (type);
484 Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, invoke_method.Parameters.Types, loc);
485 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
486 if (method_group == null)
489 var delegate_method = method_group.BestCandidate;
491 if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
492 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
493 delegate_method.GetSignatureForError ());
497 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
499 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
501 method_group.InstanceExpression = emg.ExtensionExpression;
502 TypeSpec e_type = emg.ExtensionExpression.Type;
503 if (TypeManager.IsValueType (e_type)) {
504 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
505 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
509 TypeSpec rt = delegate_method.ReturnType;
510 Expression ret_expr = new TypeExpression (rt, loc);
511 if (!Delegate.IsTypeCovariant (ec, ret_expr, invoke_method.ReturnType)) {
512 Error_ConversionFailed (ec, delegate_method, ret_expr);
515 if (delegate_method.IsConditionallyExcluded (loc)) {
516 ec.Report.SymbolRelatedToPreviousError (delegate_method);
517 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
518 if (m != null && m.IsPartialDefinition) {
519 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
520 delegate_method.GetSignatureForError ());
522 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
523 TypeManager.CSharpSignature (delegate_method));
527 var expr = method_group.InstanceExpression;
528 if (expr != null && (expr.Type.IsGenericParameter || !TypeManager.IsReferenceType (expr.Type)))
529 method_group.InstanceExpression = new BoxedCast (expr, TypeManager.object_type);
531 eclass = ExprClass.Value;
535 public override void Emit (EmitContext ec)
537 if (method_group.InstanceExpression == null)
538 ec.Emit (OpCodes.Ldnull);
540 method_group.InstanceExpression.Emit (ec);
542 var delegate_method = method_group.BestCandidate;
544 // Any delegate must be sealed
545 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
546 ec.Emit (OpCodes.Dup);
547 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
549 ec.Emit (OpCodes.Ldftn, delegate_method);
552 ec.Emit (OpCodes.Newobj, constructor_method);
555 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
557 var invoke_method = Delegate.GetInvokeMethod (type);
558 string member_name = method_group.InstanceExpression != null ?
559 Delegate.FullDelegateDesc (method) :
560 TypeManager.GetFullNameSignature (method);
562 ec.Report.SymbolRelatedToPreviousError (type);
563 ec.Report.SymbolRelatedToPreviousError (method);
564 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
565 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",
566 TypeManager.CSharpName (method.ReturnType), member_name,
567 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
571 if (return_type == null) {
572 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
573 member_name, Delegate.FullDelegateDesc (invoke_method));
577 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
578 return_type.GetSignatureForError (), member_name,
579 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
582 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
584 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
587 var invoke = Delegate.GetInvokeMethod (target_type);
589 Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, invoke.Parameters.Types, mg.Location);
590 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
593 #region IErrorHandler Members
595 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
600 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
602 Error_ConversionFailed (rc, best as MethodSpec, null);
606 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
608 Error_ConversionFailed (rc, best as MethodSpec, null);
612 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
621 // Created from the conversion code
623 public class ImplicitDelegateCreation : DelegateCreation
625 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
628 this.method_group = mg;
632 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
633 TypeSpec target_type, Location loc)
635 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
636 return d.DoResolve (ec);
641 // A delegate-creation-expression, invoked from the `New' class
643 public class NewDelegate : DelegateCreation
645 public Arguments Arguments;
648 // This constructor is invoked from the `New' expression
650 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
653 this.Arguments = Arguments;
657 protected override Expression DoResolve (ResolveContext ec)
659 if (Arguments == null || Arguments.Count != 1) {
660 ec.Report.Error (149, loc, "Method name expected");
664 Argument a = Arguments [0];
665 if (!a.ResolveMethodGroup (ec))
668 Expression e = a.Expr;
670 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
671 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
672 e = ame.Compatible (ec, type);
676 return e.Resolve (ec);
679 method_group = e as MethodGroupExpr;
680 if (method_group == null) {
681 if (e.Type == InternalType.Dynamic) {
682 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
683 } else if (!e.Type.IsDelegate) {
684 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
689 // An argument is not a method but another delegate
691 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
692 method_group.InstanceExpression = e;
695 return base.DoResolve (ec);
700 // Invocation converted to delegate Invoke call
702 class DelegateInvocation : ExpressionStatement
704 readonly Expression InstanceExpr;
708 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
710 this.InstanceExpr = instance_expr;
711 this.arguments = args;
715 public override Expression CreateExpressionTree (ResolveContext ec)
717 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
718 InstanceExpr.CreateExpressionTree (ec));
720 return CreateExpressionFactoryCall (ec, "Invoke", args);
723 protected override Expression DoResolve (ResolveContext ec)
725 TypeSpec del_type = InstanceExpr.Type;
726 if (del_type == null)
730 // Do only core overload resolution the rest of the checks has been
731 // done on primary expression
733 method = Delegate.GetInvokeMethod (del_type);
734 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
735 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
736 if (valid == null && !res.BestCandidateIsDynamic)
739 type = method.ReturnType;
740 eclass = ExprClass.Value;
744 public override void Emit (EmitContext ec)
747 // Invocation on delegates call the virtual Invoke member
748 // so we are always `instance' calls
750 Invocation.EmitCall (ec, InstanceExpr, method, arguments, loc);
753 public override void EmitStatement (EmitContext ec)
757 // Pop the return value if there is one
759 if (type != TypeManager.void_type)
760 ec.Emit (OpCodes.Pop);
763 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
765 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);