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 CreateReturnBuilder ();
105 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
109 if (a.IsValidSecurityAttribute ()) {
110 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
114 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
117 public override AttributeTargets AttributeTargets {
119 return AttributeTargets.Delegate;
123 ReturnParameter CreateReturnBuilder ()
125 return return_attributes ?? (return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location));
128 protected override bool DoDefineMembers ()
130 var builtin_types = Compiler.BuiltinTypes;
132 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
134 new Parameter (new TypeExpression (builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
135 new Parameter (new TypeExpression (builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
138 builtin_types.Object,
143 Constructor = new Constructor (this, Constructor.ConstructorName,
144 Modifiers.PUBLIC, null, ctor_parameters, Location);
145 Constructor.Define ();
148 // Here the various methods like Invoke, BeginInvoke etc are defined
150 // First, call the `out of band' special method for
151 // defining recursively any types we need:
155 if (!p.Resolve (this))
162 // Check accessibility
163 foreach (var partype in p.Types) {
164 if (!IsAccessibleAs (partype)) {
165 Report.SymbolRelatedToPreviousError (partype);
166 Report.Error (59, Location,
167 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
168 partype.GetSignatureForError (), GetSignatureForError ());
172 var ret_type = ReturnType.ResolveAsType (this);
173 if (ret_type == null)
177 // We don't have to check any others because they are all
178 // guaranteed to be accessible - they are standard types.
180 if (!IsAccessibleAs (ret_type)) {
181 Report.SymbolRelatedToPreviousError (ret_type);
182 Report.Error (58, Location,
183 "Inconsistent accessibility: return type `" +
184 ret_type.GetSignatureForError () + "' is less " +
185 "accessible than delegate `" + GetSignatureForError () + "'");
189 CheckProtectedModifier ();
191 if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) {
192 Method.Error1599 (Location, ret_type, Report);
196 VarianceDecl.CheckTypeVariance (ret_type, Variance.Covariant, this);
198 var resolved_rt = new TypeExpression (ret_type, Location);
199 InvokeBuilder = new Method (this, resolved_rt, MethodModifiers, new MemberName (InvokeMethodName), p, null);
200 InvokeBuilder.Define ();
203 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
205 if (!IsCompilerGenerated) {
206 DefineAsyncMethods (resolved_rt);
212 void DefineAsyncMethods (TypeExpression returnType)
214 var iasync_result = Module.PredefinedTypes.IAsyncResult;
215 var async_callback = Module.PredefinedTypes.AsyncCallback;
218 // It's ok when async types don't exist, the delegate will have Invoke method only
220 if (!iasync_result.Define () || !async_callback.Define ())
226 ParametersCompiled async_parameters;
227 if (Parameters.Count == 0) {
228 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
230 var compiled = new Parameter[Parameters.Count];
231 for (int i = 0; i < compiled.Length; ++i) {
232 var p = parameters[i];
233 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
235 p.ModFlags & Parameter.Modifier.RefOutMask,
236 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
239 async_parameters = new ParametersCompiled (compiled);
242 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
244 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
245 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, Location), "object", Parameter.Modifier.NONE, null, Location)
248 async_callback.TypeSpec,
249 Compiler.BuiltinTypes.Object
253 BeginInvokeBuilder = new Method (this,
254 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
255 new MemberName ("BeginInvoke"), async_parameters, null);
256 BeginInvokeBuilder.Define ();
259 // EndInvoke is a bit more interesting, all the parameters labeled as
260 // out or ref have to be duplicated here.
264 // Define parameters, and count out/ref parameters
266 ParametersCompiled end_parameters;
269 foreach (Parameter p in Parameters.FixedParameters) {
270 if ((p.ModFlags & Parameter.Modifier.RefOutMask) != 0)
274 if (out_params > 0) {
275 Parameter[] end_params = new Parameter[out_params];
278 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
279 Parameter p = parameters [i];
280 if ((p.ModFlags & Parameter.Modifier.RefOutMask) == 0)
283 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
285 p.ModFlags & Parameter.Modifier.RefOutMask,
286 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
289 end_parameters = new ParametersCompiled (end_params);
291 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
294 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
296 new TypeExpression (iasync_result.TypeSpec, Location),
297 "result", Parameter.Modifier.NONE, null, Location),
298 iasync_result.TypeSpec);
301 // Create method, define parameters, register parameters with type system
303 EndInvokeBuilder = new Method (this, returnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
304 EndInvokeBuilder.Define ();
307 public override void PrepareEmit ()
309 if ((caching_flags & Flags.CloseTypeCreated) != 0)
312 InvokeBuilder.PrepareEmit ();
313 if (BeginInvokeBuilder != null) {
314 BeginInvokeBuilder.TypeExpression = null;
315 EndInvokeBuilder.TypeExpression = null;
316 BeginInvokeBuilder.PrepareEmit ();
317 EndInvokeBuilder.PrepareEmit ();
321 public override void Emit ()
325 if (declarative_security != null) {
326 foreach (var de in declarative_security) {
328 TypeBuilder.__AddDeclarativeSecurity (de);
330 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
335 var rtype = ReturnType.Type;
337 if (rtype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
338 Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder);
339 } else if (rtype.HasDynamicElement) {
340 Module.PredefinedAttributes.Dynamic.EmitAttribute (CreateReturnBuilder ().Builder, rtype, Location);
343 if (rtype.HasNamedTupleElement) {
344 Module.PredefinedAttributes.TupleElementNames.EmitAttribute (CreateReturnBuilder ().Builder, rtype, Location);
347 ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
350 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
351 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
353 parameters.CheckConstraints (this);
354 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
355 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
357 if (BeginInvokeBuilder != null) {
358 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
359 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
361 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
362 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
366 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
368 base_type = Compiler.BuiltinTypes.MulticastDelegate;
373 protected override TypeAttributes TypeAttr {
375 return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
379 public override string[] ValidAttributeTargets {
381 return attribute_targets;
386 protected override bool VerifyClsCompliance ()
388 if (!base.VerifyClsCompliance ()) {
392 parameters.VerifyClsCompliance (this);
394 if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
395 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
396 GetSignatureForError ());
402 public static MethodSpec GetConstructor (TypeSpec delType)
404 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
405 return (MethodSpec) ctor;
409 // Returns the "Invoke" from a delegate type
411 public static MethodSpec GetInvokeMethod (TypeSpec delType)
413 var invoke = MemberCache.FindMember (delType,
414 MemberFilter.Method (InvokeMethodName, 0, null, null),
415 BindingRestriction.DeclaredOnly);
417 return (MethodSpec) invoke;
420 public static AParametersCollection GetParameters (TypeSpec delType)
422 var invoke_mb = GetInvokeMethod (delType);
423 return invoke_mb.Parameters;
427 // 15.2 Delegate compatibility
429 public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
432 // For each value parameter (a parameter with no ref or out modifier), an
433 // identity conversion or implicit reference conversion exists from the
434 // parameter type in D to the corresponding parameter type in M
439 if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
442 if (a.IsGenericParameter && b.IsGenericParameter)
445 return Convert.ImplicitReferenceConversionExists (a, b);
448 public static string FullDelegateDesc (MethodSpec invoke_method)
450 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
453 public Expression InstanceExpression {
455 return instance_expr;
458 instance_expr = value;
464 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
466 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
468 protected MethodSpec constructor_method;
469 protected MethodGroupExpr method_group;
471 public bool AllowSpecialMethodsInvocation { get; set; }
473 public override bool ContainsEmitWithAwait ()
475 var instance = method_group.InstanceExpression;
476 return instance != null && instance.ContainsEmitWithAwait ();
479 public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
481 Arguments delegate_arguments = new Arguments (pd.Count);
482 for (int i = 0; i < pd.Count; ++i) {
483 Argument.AType atype_modifier;
484 switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
485 case Parameter.Modifier.REF:
486 atype_modifier = Argument.AType.Ref;
488 case Parameter.Modifier.OUT:
489 atype_modifier = Argument.AType.Out;
496 var ptype = types[i];
497 if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
498 ptype = rc.BuiltinTypes.Object;
500 delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
503 return delegate_arguments;
506 public override Expression CreateExpressionTree (ResolveContext ec)
508 Arguments args = new Arguments (2);
509 args.Add (new Argument (new TypeOf (type, loc)));
511 if (method_group.InstanceExpression == null)
512 args.Add (new Argument (new NullLiteral (loc)));
514 args.Add (new Argument (method_group.InstanceExpression));
517 var create_v45 = ec.Module.PredefinedMembers.MethodInfoCreateDelegate.Get ();
518 if (create_v45 != null) {
520 // .NET 4.5 has better API but it produces different instance than Delegate::CreateDelegate
521 // and because csc uses this enhancement we have to as well to be fully compatible
523 var mg = MethodGroupExpr.CreatePredefined (create_v45, create_v45.DeclaringType, loc);
524 mg.InstanceExpression = method_group.CreateExpressionTree (ec);
527 ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
528 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
531 Expression e = new Invocation (ma, args).Resolve (ec);
535 e = Convert.ExplicitConversion (ec, e, type, loc);
539 return e.CreateExpressionTree (ec);
542 void ResolveConditionalAccessReceiver (ResolveContext rc)
544 // LAMESPEC: Not sure why this is explicitly disallowed with very odd error message
545 if (!rc.HasSet (ResolveContext.Options.DontSetConditionalAccessReceiver) && method_group.HasConditionalAccess ()) {
546 Error_OperatorCannotBeApplied (rc, loc, "?", method_group.Type);
550 protected override Expression DoResolve (ResolveContext ec)
552 constructor_method = Delegate.GetConstructor (type);
554 var invoke_method = Delegate.GetInvokeMethod (type);
556 ResolveConditionalAccessReceiver (ec);
558 Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
559 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
561 if (method_group == null)
564 var delegate_method = method_group.BestCandidate;
566 if (delegate_method.DeclaringType.IsNullableType) {
567 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
568 delegate_method.GetSignatureForError ());
572 if (!AllowSpecialMethodsInvocation)
573 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
575 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
577 method_group.InstanceExpression = emg.ExtensionExpression;
578 TypeSpec e_type = emg.ExtensionExpression.Type;
579 if (TypeSpec.IsValueType (e_type)) {
580 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
581 delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
585 TypeSpec rt = method_group.BestCandidateReturnType;
586 if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
587 rt = ec.BuiltinTypes.Object;
589 if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
590 Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
591 Error_ConversionFailed (ec, delegate_method, ret_expr);
594 if (method_group.IsConditionallyExcluded) {
595 ec.Report.SymbolRelatedToPreviousError (delegate_method);
596 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
597 if (m != null && m.IsPartialDefinition) {
598 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
599 delegate_method.GetSignatureForError ());
601 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
602 TypeManager.CSharpSignature (delegate_method));
606 var expr = method_group.InstanceExpression;
607 if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
608 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
610 eclass = ExprClass.Value;
614 public override void Emit (EmitContext ec)
616 if (method_group.InstanceExpression == null) {
619 var ie = new InstanceEmitter (method_group.InstanceExpression, false);
620 ie.Emit (ec, method_group.ConditionalAccess);
623 var delegate_method = method_group.BestCandidate;
625 // Any delegate must be sealed
626 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
627 ec.Emit (OpCodes.Dup);
628 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
630 ec.Emit (OpCodes.Ldftn, delegate_method);
633 ec.Emit (OpCodes.Newobj, constructor_method);
636 public override void FlowAnalysis (FlowAnalysisContext fc)
638 base.FlowAnalysis (fc);
639 method_group.FlowAnalysis (fc);
642 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
644 var invoke_method = Delegate.GetInvokeMethod (type);
645 string member_name = method_group.InstanceExpression != null ?
646 Delegate.FullDelegateDesc (method) :
647 TypeManager.GetFullNameSignature (method);
649 ec.Report.SymbolRelatedToPreviousError (type);
650 ec.Report.SymbolRelatedToPreviousError (method);
651 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
652 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",
653 method.ReturnType.GetSignatureForError (), member_name,
654 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
658 if (return_type == null) {
659 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
660 member_name, Delegate.FullDelegateDesc (invoke_method));
664 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
665 return_type.GetSignatureForError (), member_name,
666 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
669 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
671 // if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
674 var invoke = Delegate.GetInvokeMethod (target_type);
676 Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
677 mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
678 return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
681 #region IErrorHandler Members
683 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
688 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
690 Error_ConversionFailed (rc, best as MethodSpec, null);
694 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
696 Error_ConversionFailed (rc, best as MethodSpec, null);
700 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
709 // Created from the conversion code
711 public class ImplicitDelegateCreation : DelegateCreation
715 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
718 this.method_group = mg;
723 // Returns true when type is MVAR or has MVAR reference
725 public static bool ContainsMethodTypeParameter (TypeSpec type)
727 var tps = type as TypeParameterSpec;
729 return tps.IsMethodOwned;
731 var ec = type as ElementTypeSpec;
733 return ContainsMethodTypeParameter (ec.Element);
735 foreach (var t in type.TypeArguments) {
736 if (ContainsMethodTypeParameter (t)) {
742 return ContainsMethodTypeParameter (type.DeclaringType);
749 if (ContainsMethodTypeParameter (type))
752 var best = method_group.BestCandidate;
753 if (ContainsMethodTypeParameter (best.DeclaringType))
756 if (best.TypeArguments != null) {
757 foreach (var ta in best.TypeArguments) {
758 if (ContainsMethodTypeParameter (ta))
766 protected override Expression DoResolve (ResolveContext ec)
768 var expr = base.DoResolve (ec);
770 return ErrorExpression.Instance;
772 if (ec.IsInProbingMode)
776 // Cache any static delegate creation
778 if (method_group.InstanceExpression != null)
782 // Cannot easily cache types with MVAR
788 // Create type level cache for a delegate instance
790 var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
791 int id = parent.MethodGroupsCounter++;
793 mg_cache = new Field (parent, new TypeExpression (type, loc),
794 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
795 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
797 parent.AddField (mg_cache);
802 public override void Emit (EmitContext ec)
804 Label l_initialized = ec.DefineLabel ();
806 if (mg_cache != null) {
807 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
808 ec.Emit (OpCodes.Brtrue_S, l_initialized);
813 if (mg_cache != null) {
814 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
815 ec.MarkLabel (l_initialized);
816 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
822 // A delegate-creation-expression, invoked from the `New' class
824 public class NewDelegate : DelegateCreation
826 public Arguments Arguments;
829 // This constructor is invoked from the `New' expression
831 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
834 this.Arguments = Arguments;
838 protected override Expression DoResolve (ResolveContext ec)
840 if (Arguments == null || Arguments.Count != 1) {
841 ec.Report.Error (149, loc, "Method name expected");
845 Argument a = Arguments [0];
846 if (!a.ResolveMethodGroup (ec))
849 Expression e = a.Expr;
851 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
852 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
853 e = ame.Compatible (ec, type);
857 return e.Resolve (ec);
860 method_group = e as MethodGroupExpr;
861 if (method_group == null) {
862 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
863 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
864 } else if (!e.Type.IsDelegate) {
865 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
870 // An argument is not a method but another delegate
872 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
873 method_group.InstanceExpression = e;
876 return base.DoResolve (ec);
881 // Invocation converted to delegate Invoke call
883 class DelegateInvocation : ExpressionStatement
885 readonly Expression InstanceExpr;
886 readonly bool conditionalAccessReceiver;
890 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
892 this.InstanceExpr = instance_expr;
893 this.arguments = args;
894 this.conditionalAccessReceiver = conditionalAccessReceiver;
898 public override bool ContainsEmitWithAwait ()
900 return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
903 public override Expression CreateExpressionTree (ResolveContext ec)
905 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
906 InstanceExpr.CreateExpressionTree (ec));
908 return CreateExpressionFactoryCall (ec, "Invoke", args);
911 public override void FlowAnalysis (FlowAnalysisContext fc)
913 InstanceExpr.FlowAnalysis (fc);
914 if (arguments != null)
915 arguments.FlowAnalysis (fc);
918 protected override Expression DoResolve (ResolveContext ec)
920 TypeSpec del_type = InstanceExpr.Type;
921 if (del_type == null)
925 // Do only core overload resolution the rest of the checks has been
926 // done on primary expression
928 method = Delegate.GetInvokeMethod (del_type);
929 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
930 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
931 if (valid == null && !res.BestCandidateIsDynamic)
934 type = method.ReturnType;
935 if (conditionalAccessReceiver)
936 type = LiftMemberType (ec, type);
938 eclass = ExprClass.Value;
942 public override void Emit (EmitContext ec)
944 if (conditionalAccessReceiver) {
945 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
949 // Invocation on delegates call the virtual Invoke member
950 // so we are always `instance' calls
952 var call = new CallEmitter ();
953 call.InstanceExpression = InstanceExpr;
954 call.Emit (ec, method, arguments, loc);
956 if (conditionalAccessReceiver)
957 ec.CloseConditionalAccess (type.IsNullableType && type != method.ReturnType ? type : null);
960 public override void EmitStatement (EmitContext ec)
962 if (conditionalAccessReceiver) {
963 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
968 var call = new CallEmitter ();
969 call.InstanceExpression = InstanceExpr;
970 call.EmitStatement (ec, method, arguments, loc);
972 if (conditionalAccessReceiver)
973 ec.CloseConditionalAccess (null);
976 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
978 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);