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 SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
23 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
24 using System.Reflection;
25 using System.Reflection.Emit;
28 namespace Mono.CSharp {
31 // Delegate container implementation
33 public class Delegate : TypeDefinition, IParametersMember
35 FullNamedExpression ReturnType;
36 readonly ParametersCompiled parameters;
38 Constructor Constructor;
40 Method BeginInvokeBuilder;
41 Method EndInvokeBuilder;
43 static readonly string[] attribute_targets = new string [] { "type", "return" };
45 public static readonly string InvokeMethodName = "Invoke";
47 Expression instance_expr;
48 ReturnParameter return_attributes;
50 SecurityType declarative_security;
52 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
54 const Modifiers AllowedModifiers =
62 public Delegate (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
64 : base (parent, name, attrs, MemberKind.Delegate)
67 this.ReturnType = type;
68 ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
69 IsTopLevel ? Modifiers.INTERNAL :
70 Modifiers.PRIVATE, name.Location, Report);
71 parameters = param_list;
72 spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
76 public TypeSpec MemberType {
78 return ReturnType.Type;
82 public AParametersCollection Parameters {
88 public FullNamedExpression TypExpression {
96 public override void Accept (StructuralVisitor visitor)
101 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
103 if (a.Target == AttributeTargets.ReturnValue) {
104 if (return_attributes == null)
105 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
107 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
111 if (a.IsValidSecurityAttribute ()) {
112 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
116 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
119 public override AttributeTargets AttributeTargets {
121 return AttributeTargets.Delegate;
125 protected override bool DoDefineMembers ()
127 var builtin_types = Compiler.BuiltinTypes;
129 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
131 new Parameter (new TypeExpression (builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
132 new Parameter (new TypeExpression (builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
135 builtin_types.Object,
140 Constructor = new Constructor (this, Constructor.ConstructorName,
141 Modifiers.PUBLIC, null, ctor_parameters, Location);
142 Constructor.Define ();
145 // Here the various methods like Invoke, BeginInvoke etc are defined
147 // First, call the `out of band' special method for
148 // defining recursively any types we need:
152 if (!p.Resolve (this))
159 // Check accessibility
160 foreach (var partype in p.Types) {
161 if (!IsAccessibleAs (partype)) {
162 Report.SymbolRelatedToPreviousError (partype);
163 Report.Error (59, Location,
164 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
165 partype.GetSignatureForError (), GetSignatureForError ());
169 var ret_type = ReturnType.ResolveAsType (this);
170 if (ret_type == null)
174 // We don't have to check any others because they are all
175 // guaranteed to be accessible - they are standard types.
177 if (!IsAccessibleAs (ret_type)) {
178 Report.SymbolRelatedToPreviousError (ret_type);
179 Report.Error (58, Location,
180 "Inconsistent accessibility: return type `" +
181 ret_type.GetSignatureForError () + "' is less " +
182 "accessible than delegate `" + GetSignatureForError () + "'");
186 CheckProtectedModifier ();
188 if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) {
189 Method.Error1599 (Location, ret_type, Report);
193 VarianceDecl.CheckTypeVariance (ret_type, Variance.Covariant, this);
195 var resolved_rt = new TypeExpression (ret_type, Location);
196 InvokeBuilder = new Method (this, resolved_rt, MethodModifiers, new MemberName (InvokeMethodName), p, null);
197 InvokeBuilder.Define ();
200 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
202 if (!IsCompilerGenerated) {
203 DefineAsyncMethods (resolved_rt);
209 void DefineAsyncMethods (TypeExpression returnType)
211 var iasync_result = Module.PredefinedTypes.IAsyncResult;
212 var async_callback = Module.PredefinedTypes.AsyncCallback;
215 // It's ok when async types don't exist, the delegate will have Invoke method only
217 if (!iasync_result.Define () || !async_callback.Define ())
223 ParametersCompiled async_parameters;
224 if (Parameters.Count == 0) {
225 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
227 var compiled = new Parameter[Parameters.Count];
228 for (int i = 0; i < compiled.Length; ++i) {
229 var p = parameters[i];
230 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
232 p.ModFlags & Parameter.Modifier.RefOutMask,
233 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
236 async_parameters = new ParametersCompiled (compiled);
239 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
241 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
242 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, Location), "object", Parameter.Modifier.NONE, null, Location)
245 async_callback.TypeSpec,
246 Compiler.BuiltinTypes.Object
250 BeginInvokeBuilder = new Method (this,
251 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
252 new MemberName ("BeginInvoke"), async_parameters, null);
253 BeginInvokeBuilder.Define ();
256 // EndInvoke is a bit more interesting, all the parameters labeled as
257 // out or ref have to be duplicated here.
261 // Define parameters, and count out/ref parameters
263 ParametersCompiled end_parameters;
266 foreach (Parameter p in Parameters.FixedParameters) {
267 if ((p.ModFlags & Parameter.Modifier.RefOutMask) != 0)
271 if (out_params > 0) {
272 Parameter[] end_params = new Parameter[out_params];
275 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
276 Parameter p = parameters [i];
277 if ((p.ModFlags & Parameter.Modifier.RefOutMask) == 0)
280 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
282 p.ModFlags & Parameter.Modifier.RefOutMask,
283 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
286 end_parameters = new ParametersCompiled (end_params);
288 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
291 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
293 new TypeExpression (iasync_result.TypeSpec, Location),
294 "result", Parameter.Modifier.NONE, null, Location),
295 iasync_result.TypeSpec);
298 // Create method, define parameters, register parameters with type system
300 EndInvokeBuilder = new Method (this, returnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
301 EndInvokeBuilder.Define ();
304 public override void PrepareEmit ()
306 if ((caching_flags & Flags.CloseTypeCreated) != 0)
309 InvokeBuilder.PrepareEmit ();
310 if (BeginInvokeBuilder != null) {
311 BeginInvokeBuilder.TypeExpression = null;
312 EndInvokeBuilder.TypeExpression = null;
313 BeginInvokeBuilder.PrepareEmit ();
314 EndInvokeBuilder.PrepareEmit ();
318 public override void Emit ()
322 if (declarative_security != null) {
323 foreach (var de in declarative_security) {
325 TypeBuilder.__AddDeclarativeSecurity (de);
327 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
332 if (ReturnType.Type != null) {
333 if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
334 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
335 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
336 } else if (ReturnType.Type.HasDynamicElement) {
337 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
338 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
341 ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
344 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
345 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
347 parameters.CheckConstraints (this);
348 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
349 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
351 if (BeginInvokeBuilder != null) {
352 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
353 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
355 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
356 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
360 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
362 base_type = Compiler.BuiltinTypes.MulticastDelegate;
367 protected override TypeAttributes TypeAttr {
369 return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
373 public override string[] ValidAttributeTargets {
375 return attribute_targets;
380 protected override bool VerifyClsCompliance ()
382 if (!base.VerifyClsCompliance ()) {
386 parameters.VerifyClsCompliance (this);
388 if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
389 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
390 GetSignatureForError ());
396 public static MethodSpec GetConstructor (TypeSpec delType)
398 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
399 return (MethodSpec) ctor;
403 // Returns the "Invoke" from a delegate type
405 public static MethodSpec GetInvokeMethod (TypeSpec delType)
407 var invoke = MemberCache.FindMember (delType,
408 MemberFilter.Method (InvokeMethodName, 0, null, null),
409 BindingRestriction.DeclaredOnly);
411 return (MethodSpec) invoke;
414 public static AParametersCollection GetParameters (TypeSpec delType)
416 var invoke_mb = GetInvokeMethod (delType);
417 return invoke_mb.Parameters;
421 // 15.2 Delegate compatibility
423 public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
426 // For each value parameter (a parameter with no ref or out modifier), an
427 // identity conversion or implicit reference conversion exists from the
428 // parameter type in D to the corresponding parameter type in M
433 if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
436 if (a.IsGenericParameter && b.IsGenericParameter)
439 return Convert.ImplicitReferenceConversionExists (a, b);
442 public static string FullDelegateDesc (MethodSpec invoke_method)
444 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
447 public Expression InstanceExpression {
449 return instance_expr;
452 instance_expr = value;
458 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
460 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
462 protected MethodSpec constructor_method;
463 protected MethodGroupExpr method_group;
465 public bool AllowSpecialMethodsInvocation { get; set; }
467 public override bool ContainsEmitWithAwait ()
469 var instance = method_group.InstanceExpression;
470 return instance != null && instance.ContainsEmitWithAwait ();
473 public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
475 Arguments delegate_arguments = new Arguments (pd.Count);
476 for (int i = 0; i < pd.Count; ++i) {
477 Argument.AType atype_modifier;
478 switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
479 case Parameter.Modifier.REF:
480 atype_modifier = Argument.AType.Ref;
482 case Parameter.Modifier.OUT:
483 atype_modifier = Argument.AType.Out;
490 var ptype = types[i];
491 if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
492 ptype = rc.BuiltinTypes.Object;
494 delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
497 return delegate_arguments;
500 public override Expression CreateExpressionTree (ResolveContext ec)
502 Arguments args = new Arguments (2);
503 args.Add (new Argument (new TypeOf (type, loc)));
505 if (method_group.InstanceExpression == null)
506 args.Add (new Argument (new NullLiteral (loc)));
508 args.Add (new Argument (method_group.InstanceExpression));
511 var create_v45 = ec.Module.PredefinedMembers.MethodInfoCreateDelegate.Get ();
512 if (create_v45 != null) {
514 // .NET 4.5 has better API but it produces different instance than Delegate::CreateDelegate
515 // and because csc uses this enhancement we have to as well to be fully compatible
517 var mg = MethodGroupExpr.CreatePredefined (create_v45, create_v45.DeclaringType, loc);
518 mg.InstanceExpression = method_group.CreateExpressionTree (ec);
521 ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
522 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
525 Expression e = new Invocation (ma, args).Resolve (ec);
529 e = Convert.ExplicitConversion (ec, e, type, loc);
533 return e.CreateExpressionTree (ec);
536 void ResolveConditionalAccessReceiver (ResolveContext rc)
538 // LAMESPEC: Not sure why this is explicitly disallowed with very odd error message
539 if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && method_group.HasConditionalAccess ()) {
540 Error_OperatorCannotBeApplied (rc, loc, "?", method_group.Type);
544 protected override Expression DoResolve (ResolveContext ec)
546 constructor_method = Delegate.GetConstructor (type);
548 var invoke_method = Delegate.GetInvokeMethod (type);
550 ResolveConditionalAccessReceiver (ec);
552 Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
553 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
555 if (method_group == null)
558 var delegate_method = method_group.BestCandidate;
560 if (delegate_method.DeclaringType.IsNullableType) {
561 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
562 delegate_method.GetSignatureForError ());
566 if (!AllowSpecialMethodsInvocation)
567 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
569 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
571 method_group.InstanceExpression = emg.ExtensionExpression;
572 TypeSpec e_type = emg.ExtensionExpression.Type;
573 if (TypeSpec.IsValueType (e_type)) {
574 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
575 delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
579 TypeSpec rt = method_group.BestCandidateReturnType;
580 if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
581 rt = ec.BuiltinTypes.Object;
583 if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
584 Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
585 Error_ConversionFailed (ec, delegate_method, ret_expr);
588 if (method_group.IsConditionallyExcluded) {
589 ec.Report.SymbolRelatedToPreviousError (delegate_method);
590 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
591 if (m != null && m.IsPartialDefinition) {
592 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
593 delegate_method.GetSignatureForError ());
595 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
596 TypeManager.CSharpSignature (delegate_method));
600 var expr = method_group.InstanceExpression;
601 if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
602 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
604 eclass = ExprClass.Value;
608 public override void Emit (EmitContext ec)
610 if (method_group.InstanceExpression == null) {
613 var ie = new InstanceEmitter (method_group.InstanceExpression, false);
614 ie.Emit (ec, method_group.ConditionalAccess);
617 var delegate_method = method_group.BestCandidate;
619 // Any delegate must be sealed
620 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
621 ec.Emit (OpCodes.Dup);
622 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
624 ec.Emit (OpCodes.Ldftn, delegate_method);
627 ec.Emit (OpCodes.Newobj, constructor_method);
630 public override void FlowAnalysis (FlowAnalysisContext fc)
632 base.FlowAnalysis (fc);
633 method_group.FlowAnalysis (fc);
636 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
638 var invoke_method = Delegate.GetInvokeMethod (type);
639 string member_name = method_group.InstanceExpression != null ?
640 Delegate.FullDelegateDesc (method) :
641 TypeManager.GetFullNameSignature (method);
643 ec.Report.SymbolRelatedToPreviousError (type);
644 ec.Report.SymbolRelatedToPreviousError (method);
645 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
646 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",
647 method.ReturnType.GetSignatureForError (), member_name,
648 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
652 if (return_type == null) {
653 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
654 member_name, Delegate.FullDelegateDesc (invoke_method));
658 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
659 return_type.GetSignatureForError (), member_name,
660 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
663 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
665 // if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
668 var invoke = Delegate.GetInvokeMethod (target_type);
670 Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
671 mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
672 return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
675 #region IErrorHandler Members
677 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
682 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
684 Error_ConversionFailed (rc, best as MethodSpec, null);
688 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
690 Error_ConversionFailed (rc, best as MethodSpec, null);
694 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
703 // Created from the conversion code
705 public class ImplicitDelegateCreation : DelegateCreation
709 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
712 this.method_group = mg;
717 // Returns true when type is MVAR or has MVAR reference
719 public static bool ContainsMethodTypeParameter (TypeSpec type)
721 var tps = type as TypeParameterSpec;
723 return tps.IsMethodOwned;
725 var ec = type as ElementTypeSpec;
727 return ContainsMethodTypeParameter (ec.Element);
729 foreach (var t in type.TypeArguments) {
730 if (ContainsMethodTypeParameter (t)) {
736 return ContainsMethodTypeParameter (type.DeclaringType);
743 if (ContainsMethodTypeParameter (type))
746 var best = method_group.BestCandidate;
747 if (ContainsMethodTypeParameter (best.DeclaringType))
750 if (best.TypeArguments != null) {
751 foreach (var ta in best.TypeArguments) {
752 if (ContainsMethodTypeParameter (ta))
760 protected override Expression DoResolve (ResolveContext ec)
762 var expr = base.DoResolve (ec);
764 return ErrorExpression.Instance;
766 if (ec.IsInProbingMode)
770 // Cache any static delegate creation
772 if (method_group.InstanceExpression != null)
776 // Cannot easily cache types with MVAR
782 // Create type level cache for a delegate instance
784 var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
785 int id = parent.MethodGroupsCounter++;
787 mg_cache = new Field (parent, new TypeExpression (type, loc),
788 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
789 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
791 parent.AddField (mg_cache);
796 public override void Emit (EmitContext ec)
798 Label l_initialized = ec.DefineLabel ();
800 if (mg_cache != null) {
801 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
802 ec.Emit (OpCodes.Brtrue_S, l_initialized);
807 if (mg_cache != null) {
808 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
809 ec.MarkLabel (l_initialized);
810 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
816 // A delegate-creation-expression, invoked from the `New' class
818 public class NewDelegate : DelegateCreation
820 public Arguments Arguments;
823 // This constructor is invoked from the `New' expression
825 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
828 this.Arguments = Arguments;
832 protected override Expression DoResolve (ResolveContext ec)
834 if (Arguments == null || Arguments.Count != 1) {
835 ec.Report.Error (149, loc, "Method name expected");
839 Argument a = Arguments [0];
840 if (!a.ResolveMethodGroup (ec))
843 Expression e = a.Expr;
845 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
846 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
847 e = ame.Compatible (ec, type);
851 return e.Resolve (ec);
854 method_group = e as MethodGroupExpr;
855 if (method_group == null) {
856 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
857 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
858 } else if (!e.Type.IsDelegate) {
859 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
864 // An argument is not a method but another delegate
866 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
867 method_group.InstanceExpression = e;
870 return base.DoResolve (ec);
875 // Invocation converted to delegate Invoke call
877 class DelegateInvocation : ExpressionStatement
879 readonly Expression InstanceExpr;
880 readonly bool conditionalAccessReceiver;
884 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
886 this.InstanceExpr = instance_expr;
887 this.arguments = args;
888 this.conditionalAccessReceiver = conditionalAccessReceiver;
892 public override bool ContainsEmitWithAwait ()
894 return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
897 public override Expression CreateExpressionTree (ResolveContext ec)
899 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
900 InstanceExpr.CreateExpressionTree (ec));
902 return CreateExpressionFactoryCall (ec, "Invoke", args);
905 public override void FlowAnalysis (FlowAnalysisContext fc)
907 InstanceExpr.FlowAnalysis (fc);
908 if (arguments != null)
909 arguments.FlowAnalysis (fc);
912 protected override Expression DoResolve (ResolveContext ec)
914 TypeSpec del_type = InstanceExpr.Type;
915 if (del_type == null)
919 // Do only core overload resolution the rest of the checks has been
920 // done on primary expression
922 method = Delegate.GetInvokeMethod (del_type);
923 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
924 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
925 if (valid == null && !res.BestCandidateIsDynamic)
928 type = method.ReturnType;
929 if (conditionalAccessReceiver)
930 type = LiftMemberType (ec, type);
932 eclass = ExprClass.Value;
936 public override void Emit (EmitContext ec)
938 if (conditionalAccessReceiver) {
939 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
943 // Invocation on delegates call the virtual Invoke member
944 // so we are always `instance' calls
946 var call = new CallEmitter ();
947 call.InstanceExpression = InstanceExpr;
948 call.Emit (ec, method, arguments, loc);
950 if (conditionalAccessReceiver)
951 ec.CloseConditionalAccess (type.IsNullableType && type != method.ReturnType ? type : null);
954 public override void EmitStatement (EmitContext ec)
956 if (conditionalAccessReceiver) {
957 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
962 var call = new CallEmitter ();
963 call.InstanceExpression = InstanceExpr;
964 call.EmitStatement (ec, method, arguments, loc);
966 if (conditionalAccessReceiver)
967 ec.CloseConditionalAccess (null);
970 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
972 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);