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)
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
22 // Delegate container implementation
24 public class Delegate : TypeContainer, IParametersMember
26 FullNamedExpression ReturnType;
27 readonly ParametersCompiled parameters;
29 Constructor Constructor;
31 Method BeginInvokeBuilder;
32 Method EndInvokeBuilder;
34 static readonly string[] attribute_targets = new string [] { "type", "return" };
36 public static readonly string InvokeMethodName = "Invoke";
38 Expression instance_expr;
39 ReturnParameter return_attributes;
41 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
43 const Modifiers AllowedModifiers =
51 public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
52 Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
54 : base (ns, parent, name, attrs, MemberKind.Delegate)
57 this.ReturnType = type;
58 ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
59 IsTopLevel ? Modifiers.INTERNAL :
60 Modifiers.PRIVATE, name.Location, Report);
61 parameters = param_list;
62 spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
66 public TypeSpec MemberType {
68 return ReturnType.Type;
72 public AParametersCollection Parameters {
79 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
81 if (a.Target == AttributeTargets.ReturnValue) {
82 if (return_attributes == null)
83 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
85 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
89 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
92 public override AttributeTargets AttributeTargets {
94 return AttributeTargets.Delegate;
98 protected override bool DoDefineMembers ()
100 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
102 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
103 new Parameter (new TypeExpression (TypeManager.intptr_type, Location), "method", Parameter.Modifier.NONE, null, Location)
106 TypeManager.object_type,
107 TypeManager.intptr_type
111 Constructor = new Constructor (this, Constructor.ConstructorName,
112 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
113 Constructor.Define ();
116 // Here the various methods like Invoke, BeginInvoke etc are defined
118 // First, call the `out of band' special method for
119 // defining recursively any types we need:
123 if (!p.Resolve (this))
130 // Check accessibility
131 foreach (var partype in p.Types) {
132 if (!IsAccessibleAs (partype)) {
133 Report.SymbolRelatedToPreviousError (partype);
134 Report.Error (59, Location,
135 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
136 TypeManager.CSharpName (partype), GetSignatureForError ());
140 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
141 if (ReturnType == null)
144 var ret_type = ReturnType.Type;
147 // We don't have to check any others because they are all
148 // guaranteed to be accessible - they are standard types.
150 if (!IsAccessibleAs (ret_type)) {
151 Report.SymbolRelatedToPreviousError (ret_type);
152 Report.Error (58, Location,
153 "Inconsistent accessibility: return type `" +
154 TypeManager.CSharpName (ret_type) + "' is less " +
155 "accessible than delegate `" + GetSignatureForError () + "'");
159 CheckProtectedModifier ();
161 if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
162 Method.Error1599 (Location, ret_type, Report);
166 TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
168 InvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName (InvokeMethodName), p, null);
169 InvokeBuilder.Define ();
172 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
174 if (!IsCompilerGenerated) {
175 DefineAsyncMethods (Parameters.CallingConvention);
181 void DefineAsyncMethods (CallingConventions cc)
183 var iasync_result = Module.PredefinedTypes.IAsyncResult;
184 var async_callback = Module.PredefinedTypes.AsyncCallback;
187 // It's ok when async types don't exist, the delegate will have Invoke method only
189 if (!iasync_result.Define () || !async_callback.Define ())
195 ParametersCompiled async_parameters;
196 if (Parameters.Count == 0) {
197 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
199 var compiled = new Parameter[Parameters.Count];
200 for (int i = 0; i < compiled.Length; ++i) {
201 var p = parameters[i];
202 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
204 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
205 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
208 async_parameters = new ParametersCompiled (compiled);
211 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
213 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
214 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location)
217 async_callback.TypeSpec,
218 TypeManager.object_type
222 BeginInvokeBuilder = new Method (this, null,
223 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
224 new MemberName ("BeginInvoke"), async_parameters, null);
225 BeginInvokeBuilder.Define ();
228 // EndInvoke is a bit more interesting, all the parameters labeled as
229 // out or ref have to be duplicated here.
233 // Define parameters, and count out/ref parameters
235 ParametersCompiled end_parameters;
238 foreach (Parameter p in Parameters.FixedParameters) {
239 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
243 if (out_params > 0) {
244 Parameter[] end_params = new Parameter[out_params];
247 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
248 Parameter p = parameters [i];
249 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
252 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
254 p.ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
255 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
258 end_parameters = new ParametersCompiled (end_params);
260 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
263 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
265 new TypeExpression (iasync_result.TypeSpec, Location),
266 "result", Parameter.Modifier.NONE, null, Location),
267 iasync_result.TypeSpec);
270 // Create method, define parameters, register parameters with type system
272 EndInvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
273 EndInvokeBuilder.Define ();
276 public override void DefineConstants ()
278 if (!Parameters.IsEmpty) {
279 parameters.ResolveDefaultValues (this);
283 public override void EmitType ()
285 if (ReturnType.Type != null) {
286 if (ReturnType.Type == InternalType.Dynamic) {
287 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
288 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
289 } else if (ReturnType.Type.HasDynamicElement) {
290 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
291 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
295 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
297 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
298 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
300 if (BeginInvokeBuilder != null) {
301 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
302 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
304 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
305 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
308 if (OptAttributes != null) {
309 OptAttributes.Emit ();
315 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
317 base_type = TypeManager.multicast_delegate_type;
322 protected override TypeAttributes TypeAttr {
324 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
325 TypeAttributes.Class | TypeAttributes.Sealed |
330 public override string[] ValidAttributeTargets {
332 return attribute_targets;
337 protected override bool VerifyClsCompliance ()
339 if (!base.VerifyClsCompliance ()) {
343 parameters.VerifyClsCompliance (this);
345 if (!ReturnType.Type.IsCLSCompliant ()) {
346 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
347 GetSignatureForError ());
353 public static MethodSpec GetConstructor (CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
355 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
356 return (MethodSpec) ctor;
360 // Returns the "Invoke" from a delegate type
362 public static MethodSpec GetInvokeMethod (CompilerContext ctx, TypeSpec delType)
364 var invoke = MemberCache.FindMember (delType,
365 MemberFilter.Method (InvokeMethodName, 0, null, null),
366 BindingRestriction.DeclaredOnly);
368 return (MethodSpec) invoke;
371 public static AParametersCollection GetParameters (CompilerContext ctx, TypeSpec delType)
373 var invoke_mb = GetInvokeMethod (ctx, delType);
374 return invoke_mb.Parameters;
378 // 15.2 Delegate compatibility
380 public static bool IsTypeCovariant (Expression a, TypeSpec b)
383 // For each value parameter (a parameter with no ref or out modifier), an
384 // identity conversion or implicit reference conversion exists from the
385 // parameter type in D to the corresponding parameter type in M
390 if (RootContext.Version == LanguageVersion.ISO_1)
393 return Convert.ImplicitReferenceConversionExists (a, b);
396 public static string FullDelegateDesc (MethodSpec invoke_method)
398 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
401 public Expression InstanceExpression {
403 return instance_expr;
406 instance_expr = value;
412 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
414 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
416 protected MethodSpec constructor_method;
417 protected MethodGroupExpr method_group;
419 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, TypeSpec[] types, Location loc)
421 Arguments delegate_arguments = new Arguments (pd.Count);
422 for (int i = 0; i < pd.Count; ++i) {
423 Argument.AType atype_modifier;
424 switch (pd.FixedParameters [i].ModFlags) {
425 case Parameter.Modifier.REF:
426 atype_modifier = Argument.AType.Ref;
428 case Parameter.Modifier.OUT:
429 atype_modifier = Argument.AType.Out;
436 delegate_arguments.Add (new Argument (new TypeExpression (types [i], loc), atype_modifier));
439 return delegate_arguments;
442 public override Expression CreateExpressionTree (ResolveContext ec)
444 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
446 Arguments args = new Arguments (3);
447 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
448 args.Add (new Argument (new NullLiteral (loc)));
449 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
450 Expression e = new Invocation (ma, args).Resolve (ec);
454 e = Convert.ExplicitConversion (ec, e, type, loc);
458 return e.CreateExpressionTree (ec);
461 protected override Expression DoResolve (ResolveContext ec)
463 constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
465 var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
467 Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, invoke_method.Parameters.Types, loc);
468 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
469 if (method_group == null)
472 var delegate_method = method_group.BestCandidate;
474 if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
475 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
476 delegate_method.GetSignatureForError ());
480 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
482 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
484 method_group.InstanceExpression = emg.ExtensionExpression;
485 TypeSpec e_type = emg.ExtensionExpression.Type;
486 if (TypeManager.IsValueType (e_type)) {
487 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
488 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
492 TypeSpec rt = delegate_method.ReturnType;
493 Expression ret_expr = new TypeExpression (rt, loc);
494 if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
495 Error_ConversionFailed (ec, delegate_method, ret_expr);
498 if (delegate_method.IsConditionallyExcluded (loc)) {
499 ec.Report.SymbolRelatedToPreviousError (delegate_method);
500 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
501 if (m != null && m.IsPartialDefinition) {
502 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
503 delegate_method.GetSignatureForError ());
505 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
506 TypeManager.CSharpSignature (delegate_method));
510 var expr = method_group.InstanceExpression;
511 if (expr != null && (expr.Type.IsGenericParameter || !TypeManager.IsReferenceType (expr.Type)))
512 method_group.InstanceExpression = new BoxedCast (expr, TypeManager.object_type);
514 eclass = ExprClass.Value;
518 public override void Emit (EmitContext ec)
520 if (method_group.InstanceExpression == null)
521 ec.Emit (OpCodes.Ldnull);
523 method_group.InstanceExpression.Emit (ec);
525 var delegate_method = method_group.BestCandidate;
527 // Any delegate must be sealed
528 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
529 ec.Emit (OpCodes.Dup);
530 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
532 ec.Emit (OpCodes.Ldftn, delegate_method);
535 ec.Emit (OpCodes.Newobj, constructor_method);
538 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
540 var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
541 string member_name = method_group.InstanceExpression != null ?
542 Delegate.FullDelegateDesc (method) :
543 TypeManager.GetFullNameSignature (method);
545 ec.Report.SymbolRelatedToPreviousError (type);
546 ec.Report.SymbolRelatedToPreviousError (method);
547 if (RootContext.Version == LanguageVersion.ISO_1) {
548 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",
549 TypeManager.CSharpName (method.ReturnType), member_name,
550 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
554 if (return_type == null) {
555 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
556 member_name, Delegate.FullDelegateDesc (invoke_method));
560 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
561 return_type.GetSignatureForError (), member_name,
562 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
565 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
567 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
570 var invoke = Delegate.GetInvokeMethod (ec.Compiler, target_type);
572 Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, invoke.Parameters.Types, mg.Location);
573 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
576 #region IErrorHandler Members
578 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
583 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
585 Error_ConversionFailed (rc, best as MethodSpec, null);
589 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
591 Error_ConversionFailed (rc, best as MethodSpec, null);
595 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
604 // Created from the conversion code
606 public class ImplicitDelegateCreation : DelegateCreation
608 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
611 this.method_group = mg;
615 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
616 TypeSpec target_type, Location loc)
618 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
619 return d.DoResolve (ec);
624 // A delegate-creation-expression, invoked from the `New' class
626 public class NewDelegate : DelegateCreation
628 public Arguments Arguments;
631 // This constructor is invoked from the `New' expression
633 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
636 this.Arguments = Arguments;
640 protected override Expression DoResolve (ResolveContext ec)
642 if (Arguments == null || Arguments.Count != 1) {
643 ec.Report.Error (149, loc, "Method name expected");
647 Argument a = Arguments [0];
648 if (!a.ResolveMethodGroup (ec))
651 Expression e = a.Expr;
653 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
654 if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
655 e = ame.Compatible (ec, type);
659 return e.Resolve (ec);
662 method_group = e as MethodGroupExpr;
663 if (method_group == null) {
664 if (e.Type == InternalType.Dynamic) {
665 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
666 } else if (!e.Type.IsDelegate) {
667 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
672 // An argument is not a method but another delegate
674 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (ec.Compiler, e.Type), e.Type, loc);
675 method_group.InstanceExpression = e;
678 return base.DoResolve (ec);
683 // Invocation converted to delegate Invoke call
685 class DelegateInvocation : ExpressionStatement
687 readonly Expression InstanceExpr;
691 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
693 this.InstanceExpr = instance_expr;
694 this.arguments = args;
698 public override Expression CreateExpressionTree (ResolveContext ec)
700 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
701 InstanceExpr.CreateExpressionTree (ec));
703 return CreateExpressionFactoryCall (ec, "Invoke", args);
706 protected override Expression DoResolve (ResolveContext ec)
708 TypeSpec del_type = InstanceExpr.Type;
709 if (del_type == null)
713 // Do only core overload resolution the rest of the checks has been
714 // done on primary expression
716 method = Delegate.GetInvokeMethod (ec.Compiler, del_type);
717 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
718 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
719 if (valid == null && !res.BestCandidateIsDynamic)
722 type = method.ReturnType;
723 eclass = ExprClass.Value;
727 public override void Emit (EmitContext ec)
730 // Invocation on delegates call the virtual Invoke member
731 // so we are always `instance' calls
733 Invocation.EmitCall (ec, InstanceExpr, method, arguments, loc);
736 public override void EmitStatement (EmitContext ec)
740 // Pop the return value if there is one
742 if (type != TypeManager.void_type)
743 ec.Emit (OpCodes.Pop);
746 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
748 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);