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;
18 using System.Collections.Generic;
20 namespace Mono.CSharp {
23 // Delegate container implementation
25 public class Delegate : TypeContainer, IParametersMember
27 FullNamedExpression ReturnType;
28 readonly ParametersCompiled parameters;
30 Constructor Constructor;
32 Method BeginInvokeBuilder;
33 Method EndInvokeBuilder;
35 static readonly string[] attribute_targets = new string [] { "type", "return" };
37 public static readonly string InvokeMethodName = "Invoke";
39 Expression instance_expr;
40 ReturnParameter return_attributes;
42 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
44 const Modifiers AllowedModifiers =
52 public Delegate (NamespaceEntry ns, DeclSpace parent, FullNamedExpression type,
53 Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
55 : base (ns, parent, name, attrs, MemberKind.Delegate)
58 this.ReturnType = type;
59 ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
60 IsTopLevel ? Modifiers.INTERNAL :
61 Modifiers.PRIVATE, name.Location, Report);
62 parameters = param_list;
63 spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
67 public TypeSpec MemberType {
69 return ReturnType.Type;
73 public AParametersCollection Parameters {
80 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
82 if (a.Target == AttributeTargets.ReturnValue) {
83 if (return_attributes == null)
84 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
86 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
90 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
93 public override AttributeTargets AttributeTargets {
95 return AttributeTargets.Delegate;
99 protected override bool DoDefineMembers ()
101 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
103 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
104 new Parameter (new TypeExpression (TypeManager.intptr_type, Location), "method", Parameter.Modifier.NONE, null, Location)
107 TypeManager.object_type,
108 TypeManager.intptr_type
112 Constructor = new Constructor (this, System.Reflection.ConstructorInfo.ConstructorName,
113 Modifiers.PUBLIC, null, ctor_parameters, null, Location);
114 Constructor.Define ();
117 // Here the various methods like Invoke, BeginInvoke etc are defined
119 // First, call the `out of band' special method for
120 // defining recursively any types we need:
124 if (!p.Resolve (this))
131 // Check accessibility
132 foreach (var partype in p.Types) {
133 if (!IsAccessibleAs (partype)) {
134 Report.SymbolRelatedToPreviousError (partype);
135 Report.Error (59, Location,
136 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
137 TypeManager.CSharpName (partype), GetSignatureForError ());
141 ReturnType = ReturnType.ResolveAsTypeTerminal (this, false);
142 if (ReturnType == null)
145 var ret_type = ReturnType.Type;
148 // We don't have to check any others because they are all
149 // guaranteed to be accessible - they are standard types.
151 if (!IsAccessibleAs (ret_type)) {
152 Report.SymbolRelatedToPreviousError (ret_type);
153 Report.Error (58, Location,
154 "Inconsistent accessibility: return type `" +
155 TypeManager.CSharpName (ret_type) + "' is less " +
156 "accessible than delegate `" + GetSignatureForError () + "'");
160 CheckProtectedModifier ();
162 if (RootContext.StdLib && TypeManager.IsSpecialType (ret_type)) {
163 Method.Error1599 (Location, ret_type, Report);
167 TypeManager.CheckTypeVariance (ret_type, Variance.Covariant, this);
169 InvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName (InvokeMethodName), p, null);
170 InvokeBuilder.Define ();
173 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
175 if (TypeManager.iasyncresult_type != null && TypeManager.asynccallback_type != null && !IsCompilerGenerated) {
176 DefineAsyncMethods (Parameters.CallingConvention);
182 void DefineAsyncMethods (CallingConventions cc)
187 ParametersCompiled async_parameters;
188 if (Parameters.Count == 0) {
189 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
191 var compiled = new Parameter[Parameters.Count];
192 for (int i = 0; i < compiled.Length; ++i)
193 compiled[i] = new Parameter (new TypeExpression (Parameters.Types[i], Location),
194 Parameters.FixedParameters[i].Name,
195 Parameters.FixedParameters[i].ModFlags & (Parameter.Modifier.REF | Parameter.Modifier.OUT),
198 async_parameters = new ParametersCompiled (compiled);
201 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
203 new Parameter (new TypeExpression (TypeManager.asynccallback_type, Location), "callback", Parameter.Modifier.NONE, null, Location),
204 new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location)
207 TypeManager.asynccallback_type,
208 TypeManager.object_type
212 BeginInvokeBuilder = new Method (this, null,
213 new TypeExpression (TypeManager.iasyncresult_type, Location), MethodModifiers,
214 new MemberName ("BeginInvoke"), async_parameters, null);
215 BeginInvokeBuilder.Define ();
218 // EndInvoke is a bit more interesting, all the parameters labeled as
219 // out or ref have to be duplicated here.
223 // Define parameters, and count out/ref parameters
225 ParametersCompiled end_parameters;
228 foreach (Parameter p in Parameters.FixedParameters) {
229 if ((p.ModFlags & Parameter.Modifier.ISBYREF) != 0)
233 if (out_params > 0) {
234 var end_param_types = new TypeSpec [out_params];
235 Parameter[] end_params = new Parameter[out_params];
238 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
239 Parameter p = parameters [i];
240 if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
243 end_param_types[param] = Parameters.Types[i];
244 end_params[param] = p;
247 end_parameters = ParametersCompiled.CreateFullyResolved (end_params, end_param_types);
249 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
252 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
254 new TypeExpression (TypeManager.iasyncresult_type, Location),
255 "result", Parameter.Modifier.NONE, null, Location),
256 TypeManager.iasyncresult_type);
259 // Create method, define parameters, register parameters with type system
261 EndInvokeBuilder = new Method (this, null, ReturnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
262 EndInvokeBuilder.Define ();
265 public override void DefineConstants ()
267 if (!Parameters.IsEmpty) {
268 parameters.ResolveDefaultValues (this);
272 public override void EmitType ()
274 if (ReturnType.Type == InternalType.Dynamic) {
275 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
276 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
278 var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType.Type);
279 if (trans_flags != null) {
280 var pa = Compiler.PredefinedAttributes.DynamicTransform;
281 if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
282 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
283 return_attributes.Builder.SetCustomAttribute (
284 new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
289 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
291 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
292 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
294 if (BeginInvokeBuilder != null) {
295 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
297 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
298 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
301 if (OptAttributes != null) {
302 OptAttributes.Emit ();
308 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
310 base_type = TypeManager.multicast_delegate_type;
315 protected override TypeAttributes TypeAttr {
317 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
318 TypeAttributes.Class | TypeAttributes.Sealed |
323 public override string[] ValidAttributeTargets {
325 return attribute_targets;
330 protected override bool VerifyClsCompliance ()
332 if (!base.VerifyClsCompliance ()) {
336 parameters.VerifyClsCompliance (this);
338 if (!ReturnType.Type.IsCLSCompliant ()) {
339 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
340 GetSignatureForError ());
346 public static MethodSpec GetConstructor (CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
348 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
349 return (MethodSpec) ctor;
353 // Returns the "Invoke" from a delegate type
355 public static MethodSpec GetInvokeMethod (CompilerContext ctx, TypeSpec delType)
357 var invoke = MemberCache.FindMember (delType,
358 MemberFilter.Method (InvokeMethodName, 0, null, null),
359 BindingRestriction.DeclaredOnly);
361 return (MethodSpec) invoke;
364 public static AParametersCollection GetParameters (CompilerContext ctx, TypeSpec delType)
366 var invoke_mb = GetInvokeMethod (ctx, delType);
367 return invoke_mb.Parameters;
371 // 15.2 Delegate compatibility
373 public static bool IsTypeCovariant (Expression a, TypeSpec b)
376 // For each value parameter (a parameter with no ref or out modifier), an
377 // identity conversion or implicit reference conversion exists from the
378 // parameter type in D to the corresponding parameter type in M
383 if (RootContext.Version == LanguageVersion.ISO_1)
386 return Convert.ImplicitReferenceConversionExists (a, b);
389 public static string FullDelegateDesc (MethodSpec invoke_method)
391 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
394 public Expression InstanceExpression {
396 return instance_expr;
399 instance_expr = value;
405 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
407 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
409 protected MethodSpec constructor_method;
410 protected MethodGroupExpr method_group;
412 public static Arguments CreateDelegateMethodArguments (AParametersCollection pd, TypeSpec[] types, Location loc)
414 Arguments delegate_arguments = new Arguments (pd.Count);
415 for (int i = 0; i < pd.Count; ++i) {
416 Argument.AType atype_modifier;
417 switch (pd.FixedParameters [i].ModFlags) {
418 case Parameter.Modifier.REF:
419 atype_modifier = Argument.AType.Ref;
421 case Parameter.Modifier.OUT:
422 atype_modifier = Argument.AType.Out;
429 delegate_arguments.Add (new Argument (new TypeExpression (types [i], loc), atype_modifier));
432 return delegate_arguments;
435 public override Expression CreateExpressionTree (ResolveContext ec)
437 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
439 Arguments args = new Arguments (3);
440 args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
441 args.Add (new Argument (new NullLiteral (loc)));
442 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
443 Expression e = new Invocation (ma, args).Resolve (ec);
447 e = Convert.ExplicitConversion (ec, e, type, loc);
451 return e.CreateExpressionTree (ec);
454 protected override Expression DoResolve (ResolveContext ec)
456 constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
458 var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
460 Arguments arguments = CreateDelegateMethodArguments (invoke_method.Parameters, invoke_method.Parameters.Types, loc);
461 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
462 if (method_group == null)
465 var delegate_method = method_group.BestCandidate;
467 if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
468 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
469 delegate_method.GetSignatureForError ());
473 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
475 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
477 method_group.InstanceExpression = emg.ExtensionExpression;
478 TypeSpec e_type = emg.ExtensionExpression.Type;
479 if (TypeManager.IsValueType (e_type)) {
480 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
481 delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
485 TypeSpec rt = delegate_method.ReturnType;
486 Expression ret_expr = new TypeExpression (rt, loc);
487 if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
488 Error_ConversionFailed (ec, delegate_method, ret_expr);
491 if (delegate_method.IsConditionallyExcluded (loc)) {
492 ec.Report.SymbolRelatedToPreviousError (delegate_method);
493 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
494 if (m != null && m.IsPartialDefinition) {
495 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
496 delegate_method.GetSignatureForError ());
498 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
499 TypeManager.CSharpSignature (delegate_method));
503 var expr = method_group.InstanceExpression;
504 if (expr != null && (expr.Type.IsGenericParameter || !TypeManager.IsReferenceType (expr.Type)))
505 method_group.InstanceExpression = new BoxedCast (expr, TypeManager.object_type);
507 eclass = ExprClass.Value;
511 public override void Emit (EmitContext ec)
513 if (method_group.InstanceExpression == null)
514 ec.Emit (OpCodes.Ldnull);
516 method_group.InstanceExpression.Emit (ec);
518 var delegate_method = method_group.BestCandidate;
520 // Any delegate must be sealed
521 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
522 ec.Emit (OpCodes.Dup);
523 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
525 ec.Emit (OpCodes.Ldftn, delegate_method);
528 ec.Emit (OpCodes.Newobj, constructor_method);
531 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
533 var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
534 string member_name = method_group.InstanceExpression != null ?
535 Delegate.FullDelegateDesc (method) :
536 TypeManager.GetFullNameSignature (method);
538 ec.Report.SymbolRelatedToPreviousError (type);
539 ec.Report.SymbolRelatedToPreviousError (method);
540 if (RootContext.Version == LanguageVersion.ISO_1) {
541 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",
542 TypeManager.CSharpName (method.ReturnType), member_name,
543 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
547 if (return_type == null) {
548 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
549 member_name, Delegate.FullDelegateDesc (invoke_method));
553 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
554 return_type.GetSignatureForError (), member_name,
555 TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
558 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
560 if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
563 var invoke = Delegate.GetInvokeMethod (ec.Compiler, target_type);
565 Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, invoke.Parameters.Types, mg.Location);
566 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
569 #region IErrorHandler Members
571 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
576 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
578 Error_ConversionFailed (rc, best as MethodSpec, null);
582 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
584 Error_ConversionFailed (rc, best as MethodSpec, null);
588 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
597 // Created from the conversion code
599 public class ImplicitDelegateCreation : DelegateCreation
601 ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
604 this.method_group = mg;
608 static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
609 TypeSpec target_type, Location loc)
611 ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
612 return d.DoResolve (ec);
617 // A delegate-creation-expression, invoked from the `New' class
619 public class NewDelegate : DelegateCreation
621 public Arguments Arguments;
624 // This constructor is invoked from the `New' expression
626 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
629 this.Arguments = Arguments;
633 protected override Expression DoResolve (ResolveContext ec)
635 if (Arguments == null || Arguments.Count != 1) {
636 ec.Report.Error (149, loc, "Method name expected");
640 Argument a = Arguments [0];
641 if (!a.ResolveMethodGroup (ec))
644 Expression e = a.Expr;
646 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
647 if (ame != null && RootContext.Version != LanguageVersion.ISO_1) {
648 e = ame.Compatible (ec, type);
652 return e.Resolve (ec);
655 method_group = e as MethodGroupExpr;
656 if (method_group == null) {
657 if (e.Type == InternalType.Dynamic) {
658 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
659 } else if (!e.Type.IsDelegate) {
660 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
665 // An argument is not a method but another delegate
667 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (ec.Compiler, e.Type), e.Type, loc);
668 method_group.InstanceExpression = e;
671 return base.DoResolve (ec);
676 // Invocation converted to delegate Invoke call
678 class DelegateInvocation : ExpressionStatement
680 readonly Expression InstanceExpr;
684 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
686 this.InstanceExpr = instance_expr;
687 this.arguments = args;
691 public override Expression CreateExpressionTree (ResolveContext ec)
693 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
694 InstanceExpr.CreateExpressionTree (ec));
696 return CreateExpressionFactoryCall (ec, "Invoke", args);
699 protected override Expression DoResolve (ResolveContext ec)
701 if (InstanceExpr is EventExpr) {
702 ((EventExpr) InstanceExpr).Error_CannotAssign (ec);
706 TypeSpec del_type = InstanceExpr.Type;
707 if (del_type == null)
711 // Do only core overload resolution the rest of the checks has been
712 // done on primary expression
714 method = Delegate.GetInvokeMethod (ec.Compiler, del_type);
715 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
716 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
717 if (valid == null && !res.BestCandidateIsDynamic)
720 type = method.ReturnType;
721 eclass = ExprClass.Value;
725 public override void Emit (EmitContext ec)
728 // Invocation on delegates call the virtual Invoke member
729 // so we are always `instance' calls
731 Invocation.EmitCall (ec, InstanceExpr, method, arguments, loc);
734 public override void EmitStatement (EmitContext ec)
738 // Pop the return value if there is one
740 if (type != TypeManager.void_type)
741 ec.Emit (OpCodes.Pop);
744 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
746 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);