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 ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
87 if (a.Target == AttributeTargets.ReturnValue) {
88 if (return_attributes == null)
89 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
91 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
95 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
98 public override AttributeTargets AttributeTargets {
100 return AttributeTargets.Delegate;
104 protected override bool DoDefineMembers ()
106 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
108 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
109 new Parameter (new TypeExpression (TypeManager.intptr_type, Location), "method", Parameter.Modifier.NONE, null, Location)
112 TypeManager.object_type,
113 TypeManager.intptr_type
117 Constructor = new Constructor (this, Constructor.ConstructorName,
118 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
119 Constructor.Define ();
122 // Here the various methods like Invoke, BeginInvoke etc are defined
124 // First, call the `out of band' special method for
125 // defining recursively any types we need:
129 if (!p.Resolve (this))
136 // Check accessibility
137 foreach (var partype in p.Types) {
138 if (!IsAccessibleAs (partype)) {
139 Report.SymbolRelatedToPreviousError (partype);
140 Report.Error (59, Location,
141 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
142 TypeManager.CSharpName (partype), GetSignatureForError ());
146 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
147 if (ReturnType == null)
150 var ret_type = ReturnType.Type;
153 // We don't have to check any others because they are all
154 // guaranteed to be accessible - they are standard types.
156 if (!IsAccessibleAs (ret_type)) {
157 Report.SymbolRelatedToPreviousError (ret_type);
158 Report.Error (58, Location,
159 "Inconsistent accessibility: return type `" +
160 TypeManager.CSharpName (ret_type) + "' is less " +
161 "accessible than delegate `" + GetSignatureForError () + "'");
165 CheckProtectedModifier ();
167 if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
168 Method.Error1599 (Location, ret_type, Report);
172 TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
174 InvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName (InvokeMethodName), p, null);
175 InvokeBuilder.Define ();
178 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
180 if (!IsCompilerGenerated) {
181 DefineAsyncMethods (Parameters.CallingConvention);
187 void DefineAsyncMethods (CallingConventions cc)
189 var iasync_result = Module.PredefinedTypes.IAsyncResult;
190 var async_callback = Module.PredefinedTypes.AsyncCallback;
193 // It's ok when async types don't exist, the delegate will have Invoke method only
195 if (!iasync_result.Define () || !async_callback.Define ())
201 ParametersCompiled async_parameters;
202 if (Parameters.Count == 0) {
203 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
205 var compiled = new Parameter[Parameters.Count];
206 for (int i = 0; i < compiled.Length; ++i) {
207 var p = parameters[i];
208 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
210 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
211 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
214 async_parameters = new ParametersCompiled (compiled);
217 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
219 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
220 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location)
223 async_callback.TypeSpec,
224 TypeManager.object_type
228 BeginInvokeBuilder = new Method (this, null,
229 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
230 new MemberName ("BeginInvoke"), async_parameters, null);
231 BeginInvokeBuilder.Define ();
234 // EndInvoke is a bit more interesting, all the parameters labeled as
235 // out or ref have to be duplicated here.
239 // Define parameters, and count out/ref parameters
241 ParametersCompiled end_parameters;
244 foreach (Parameter p in Parameters.FixedParameters) {
245 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
249 if (out_params > 0) {
250 Parameter[] end_params = new Parameter[out_params];
253 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
254 Parameter p = parameters [i];
255 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
258 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
260 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
261 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
264 end_parameters = new ParametersCompiled (end_params);
266 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
269 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
271 new TypeExpression (iasync_result.TypeSpec, Location),
272 "result", Parameter.Modifier.NONE, null, Location),
273 iasync_result.TypeSpec);
276 // Create method, define parameters, register parameters with type system
278 EndInvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
279 EndInvokeBuilder.Define ();
282 public override void DefineConstants ()
284 if (!Parameters.IsEmpty) {
285 parameters.ResolveDefaultValues (this);
289 public override void EmitType ()
291 if (ReturnType.Type != null) {
292 if (ReturnType.Type == InternalType.Dynamic) {
293 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
294 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
295 } else if (ReturnType.Type.HasDynamicElement) {
296 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
297 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
301 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
302 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
304 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
305 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
307 if (BeginInvokeBuilder != null) {
308 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
309 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
311 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
312 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
315 if (OptAttributes != null) {
316 OptAttributes.Emit ();
322 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
324 base_type = TypeManager.multicast_delegate_type;
329 protected override TypeAttributes TypeAttr {
331 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
332 TypeAttributes.Class | TypeAttributes.Sealed |
337 public override string[] ValidAttributeTargets {
339 return attribute_targets;
344 protected override bool VerifyClsCompliance ()
346 if (!base.VerifyClsCompliance ()) {
350 parameters.VerifyClsCompliance (this);
352 if (!ReturnType.Type.IsCLSCompliant ()) {
353 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
354 GetSignatureForError ());
360 public static MethodSpec GetConstructor (CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
362 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
363 return (MethodSpec) ctor;
367 // Returns the "Invoke" from a delegate type
369 public static MethodSpec GetInvokeMethod (CompilerContext ctx, TypeSpec delType)
371 var invoke = MemberCache.FindMember (delType,
372 MemberFilter.Method (InvokeMethodName, 0, null, null),
373 BindingRestriction.DeclaredOnly);
375 return (MethodSpec) invoke;
378 public static AParametersCollection GetParameters (CompilerContext ctx, TypeSpec delType)
380 var invoke_mb = GetInvokeMethod (ctx, delType);
381 return invoke_mb.Parameters;
385 // 15.2 Delegate compatibility
387 public static bool IsTypeCovariant (Expression a, TypeSpec b)
390 // For each value parameter (a parameter with no ref or out modifier), an
391 // identity conversion or implicit reference conversion exists from the
392 // parameter type in D to the corresponding parameter type in M
397 if (RootContext.Version == LanguageVersion.ISO_1)
400 return Convert.ImplicitReferenceConversionExists (a, b);
403 public static string FullDelegateDesc (MethodSpec invoke_method)
405 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
408 public Expression InstanceExpression {
410 return instance_expr;
413 instance_expr = value;
419 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
421 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
423 protected MethodSpec constructor_method;
424 protected MethodGroupExpr method_group;
426 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, TypeSpec[] types, Location loc)
428 Arguments delegate_arguments = new Arguments (pd.Count);
429 for (int i = 0; i < pd.Count; ++i) {
430 Argument.AType atype_modifier;
431 switch (pd.FixedParameters [i].ModFlags) {
432 case Parameter.Modifier.REF:
433 atype_modifier = Argument.AType.Ref;
435 case Parameter.Modifier.OUT:
436 atype_modifier = Argument.AType.Out;
443 delegate_arguments.Add (new Argument (new TypeExpression (types [i], loc), atype_modifier));
446 return delegate_arguments;
449 public override Expression CreateExpressionTree (ResolveContext ec)
451 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
453 Arguments args = new Arguments (3);
454 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
456 if (method_group.InstanceExpression == null)
457 args.Add (new Argument (new NullLiteral (loc)));
459 args.Add (new Argument (method_group.InstanceExpression));
461 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
462 Expression e = new Invocation (ma, args).Resolve (ec);
466 e = Convert.ExplicitConversion (ec, e, type, loc);
470 return e.CreateExpressionTree (ec);
473 protected override Expression DoResolve (ResolveContext ec)
475 constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
477 var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
479 Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, invoke_method.Parameters.Types, loc);
480 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
481 if (method_group == null)
484 var delegate_method = method_group.BestCandidate;
486 if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
487 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
488 delegate_method.GetSignatureForError ());
492 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
494 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
496 method_group.InstanceExpression = emg.ExtensionExpression;
497 TypeSpec e_type = emg.ExtensionExpression.Type;
498 if (TypeManager.IsValueType (e_type)) {
499 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
500 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
504 TypeSpec rt = delegate_method.ReturnType;
505 Expression ret_expr = new TypeExpression (rt, loc);
506 if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
507 Error_ConversionFailed (ec, delegate_method, ret_expr);
510 if (delegate_method.IsConditionallyExcluded (loc)) {
511 ec.Report.SymbolRelatedToPreviousError (delegate_method);
512 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
513 if (m != null && m.IsPartialDefinition) {
514 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
515 delegate_method.GetSignatureForError ());
517 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
518 TypeManager.CSharpSignature (delegate_method));
522 var expr = method_group.InstanceExpression;
523 if (expr != null && (expr.Type.IsGenericParameter || !TypeManager.IsReferenceType (expr.Type)))
524 method_group.InstanceExpression = new BoxedCast (expr, TypeManager.object_type);
526 eclass = ExprClass.Value;
530 public override void Emit (EmitContext ec)
532 if (method_group.InstanceExpression == null)
533 ec.Emit (OpCodes.Ldnull);
535 method_group.InstanceExpression.Emit (ec);
537 var delegate_method = method_group.BestCandidate;
539 // Any delegate must be sealed
540 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
541 ec.Emit (OpCodes.Dup);
542 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
544 ec.Emit (OpCodes.Ldftn, delegate_method);
547 ec.Emit (OpCodes.Newobj, constructor_method);
550 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
552 var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
553 string member_name = method_group.InstanceExpression != null ?
554 Delegate.FullDelegateDesc (method) :
555 TypeManager.GetFullNameSignature (method);
557 ec.Report.SymbolRelatedToPreviousError (type);
558 ec.Report.SymbolRelatedToPreviousError (method);
559 if (RootContext.Version == LanguageVersion.ISO_1) {
560 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",
561 TypeManager.CSharpName (method.ReturnType), member_name,
562 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
566 if (return_type == null) {
567 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
568 member_name, Delegate.FullDelegateDesc (invoke_method));
572 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
573 return_type.GetSignatureForError (), member_name,
574 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
577 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
579 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
582 var invoke = Delegate.GetInvokeMethod (ec.Compiler, target_type);
584 Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, invoke.Parameters.Types, mg.Location);
585 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
588 #region IErrorHandler Members
590 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
595 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
597 Error_ConversionFailed (rc, best as MethodSpec, null);
601 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
603 Error_ConversionFailed (rc, best as MethodSpec, null);
607 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
616 // Created from the conversion code
618 public class ImplicitDelegateCreation : DelegateCreation
620 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
623 this.method_group = mg;
627 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
628 TypeSpec target_type, Location loc)
630 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
631 return d.DoResolve (ec);
636 // A delegate-creation-expression, invoked from the `New' class
638 public class NewDelegate : DelegateCreation
640 public Arguments Arguments;
643 // This constructor is invoked from the `New' expression
645 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
648 this.Arguments = Arguments;
652 protected override Expression DoResolve (ResolveContext ec)
654 if (Arguments == null || Arguments.Count != 1) {
655 ec.Report.Error (149, loc, "Method name expected");
659 Argument a = Arguments [0];
660 if (!a.ResolveMethodGroup (ec))
663 Expression e = a.Expr;
665 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
666 if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
667 e = ame.Compatible (ec, type);
671 return e.Resolve (ec);
674 method_group = e as MethodGroupExpr;
675 if (method_group == null) {
676 if (e.Type == InternalType.Dynamic) {
677 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
678 } else if (!e.Type.IsDelegate) {
679 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
684 // An argument is not a method but another delegate
686 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (ec.Compiler, e.Type), e.Type, loc);
687 method_group.InstanceExpression = e;
690 return base.DoResolve (ec);
695 // Invocation converted to delegate Invoke call
697 class DelegateInvocation : ExpressionStatement
699 readonly Expression InstanceExpr;
703 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
705 this.InstanceExpr = instance_expr;
706 this.arguments = args;
710 public override Expression CreateExpressionTree (ResolveContext ec)
712 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
713 InstanceExpr.CreateExpressionTree (ec));
715 return CreateExpressionFactoryCall (ec, "Invoke", args);
718 protected override Expression DoResolve (ResolveContext ec)
720 TypeSpec del_type = InstanceExpr.Type;
721 if (del_type == null)
725 // Do only core overload resolution the rest of the checks has been
726 // done on primary expression
728 method = Delegate.GetInvokeMethod (ec.Compiler, del_type);
729 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
730 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
731 if (valid == null && !res.BestCandidateIsDynamic)
734 type = method.ReturnType;
735 eclass = ExprClass.Value;
739 public override void Emit (EmitContext ec)
742 // Invocation on delegates call the virtual Invoke member
743 // so we are always `instance' calls
745 Invocation.EmitCall (ec, InstanceExpr, method, arguments, loc);
748 public override void EmitStatement (EmitContext ec)
752 // Pop the return value if there is one
754 if (type != TypeManager.void_type)
755 ec.Emit (OpCodes.Pop);
758 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
760 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);