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.PrepareEmit ();
312 EndInvokeBuilder.PrepareEmit ();
316 public override void Emit ()
320 if (declarative_security != null) {
321 foreach (var de in declarative_security) {
323 TypeBuilder.__AddDeclarativeSecurity (de);
325 TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
330 if (ReturnType.Type != null) {
331 if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
332 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
333 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
334 } else if (ReturnType.Type.HasDynamicElement) {
335 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
336 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
339 ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
342 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
343 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
345 parameters.CheckConstraints (this);
346 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
347 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
349 if (BeginInvokeBuilder != null) {
350 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
351 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
353 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
354 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
358 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
360 base_type = Compiler.BuiltinTypes.MulticastDelegate;
365 protected override TypeAttributes TypeAttr {
367 return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
371 public override string[] ValidAttributeTargets {
373 return attribute_targets;
378 protected override bool VerifyClsCompliance ()
380 if (!base.VerifyClsCompliance ()) {
384 parameters.VerifyClsCompliance (this);
386 if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
387 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
388 GetSignatureForError ());
394 public static MethodSpec GetConstructor (TypeSpec delType)
396 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
397 return (MethodSpec) ctor;
401 // Returns the "Invoke" from a delegate type
403 public static MethodSpec GetInvokeMethod (TypeSpec delType)
405 var invoke = MemberCache.FindMember (delType,
406 MemberFilter.Method (InvokeMethodName, 0, null, null),
407 BindingRestriction.DeclaredOnly);
409 return (MethodSpec) invoke;
412 public static AParametersCollection GetParameters (TypeSpec delType)
414 var invoke_mb = GetInvokeMethod (delType);
415 return invoke_mb.Parameters;
419 // 15.2 Delegate compatibility
421 public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
424 // For each value parameter (a parameter with no ref or out modifier), an
425 // identity conversion or implicit reference conversion exists from the
426 // parameter type in D to the corresponding parameter type in M
431 if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
434 if (a.IsGenericParameter && b.IsGenericParameter)
437 return Convert.ImplicitReferenceConversionExists (a, b);
440 public static string FullDelegateDesc (MethodSpec invoke_method)
442 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
445 public Expression InstanceExpression {
447 return instance_expr;
450 instance_expr = value;
456 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
458 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
460 bool conditional_access_receiver;
461 protected MethodSpec constructor_method;
462 protected MethodGroupExpr method_group;
464 public bool AllowSpecialMethodsInvocation { get; set; }
466 public override bool ContainsEmitWithAwait ()
468 var instance = method_group.InstanceExpression;
469 return instance != null && instance.ContainsEmitWithAwait ();
472 public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
474 Arguments delegate_arguments = new Arguments (pd.Count);
475 for (int i = 0; i < pd.Count; ++i) {
476 Argument.AType atype_modifier;
477 switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
478 case Parameter.Modifier.REF:
479 atype_modifier = Argument.AType.Ref;
481 case Parameter.Modifier.OUT:
482 atype_modifier = Argument.AType.Out;
489 var ptype = types[i];
490 if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
491 ptype = rc.BuiltinTypes.Object;
493 delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
496 return delegate_arguments;
499 public override Expression CreateExpressionTree (ResolveContext ec)
501 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
503 Arguments args = new Arguments (3);
504 args.Add (new Argument (new TypeOf (type, loc)));
506 if (method_group.InstanceExpression == null)
507 args.Add (new Argument (new NullLiteral (loc)));
509 args.Add (new Argument (method_group.InstanceExpression));
511 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
512 Expression e = new Invocation (ma, args).Resolve (ec);
516 e = Convert.ExplicitConversion (ec, e, type, loc);
520 return e.CreateExpressionTree (ec);
523 protected override Expression DoResolve (ResolveContext ec)
525 constructor_method = Delegate.GetConstructor (type);
527 var invoke_method = Delegate.GetInvokeMethod (type);
529 if (!ec.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) {
530 if (method_group.HasConditionalAccess ()) {
531 conditional_access_receiver = true;
532 ec.Set (ResolveContext.Options.ConditionalAccessReceiver);
536 Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
537 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
539 if (conditional_access_receiver)
540 ec.With (ResolveContext.Options.ConditionalAccessReceiver, false);
542 if (method_group == null)
545 var delegate_method = method_group.BestCandidate;
547 if (delegate_method.DeclaringType.IsNullableType) {
548 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
549 delegate_method.GetSignatureForError ());
553 if (!AllowSpecialMethodsInvocation)
554 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
556 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
558 method_group.InstanceExpression = emg.ExtensionExpression;
559 TypeSpec e_type = emg.ExtensionExpression.Type;
560 if (TypeSpec.IsValueType (e_type)) {
561 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
562 delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
566 TypeSpec rt = method_group.BestCandidateReturnType;
567 if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
568 rt = ec.BuiltinTypes.Object;
570 if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
571 Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
572 Error_ConversionFailed (ec, delegate_method, ret_expr);
575 if (method_group.IsConditionallyExcluded) {
576 ec.Report.SymbolRelatedToPreviousError (delegate_method);
577 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
578 if (m != null && m.IsPartialDefinition) {
579 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
580 delegate_method.GetSignatureForError ());
582 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
583 TypeManager.CSharpSignature (delegate_method));
587 var expr = method_group.InstanceExpression;
588 if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
589 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
591 eclass = ExprClass.Value;
595 public override void Emit (EmitContext ec)
597 if (conditional_access_receiver)
598 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
600 if (method_group.InstanceExpression == null) {
603 var ie = new InstanceEmitter (method_group.InstanceExpression, false);
604 ie.Emit (ec, method_group.ConditionalAccess);
607 var delegate_method = method_group.BestCandidate;
609 // Any delegate must be sealed
610 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
611 ec.Emit (OpCodes.Dup);
612 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
614 ec.Emit (OpCodes.Ldftn, delegate_method);
617 ec.Emit (OpCodes.Newobj, constructor_method);
619 if (conditional_access_receiver)
620 ec.CloseConditionalAccess (null);
623 public override void FlowAnalysis (FlowAnalysisContext fc)
625 base.FlowAnalysis (fc);
626 method_group.FlowAnalysis (fc);
628 if (conditional_access_receiver)
629 fc.ConditionalAccessEnd ();
632 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
634 var invoke_method = Delegate.GetInvokeMethod (type);
635 string member_name = method_group.InstanceExpression != null ?
636 Delegate.FullDelegateDesc (method) :
637 TypeManager.GetFullNameSignature (method);
639 ec.Report.SymbolRelatedToPreviousError (type);
640 ec.Report.SymbolRelatedToPreviousError (method);
641 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
642 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",
643 method.ReturnType.GetSignatureForError (), member_name,
644 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
648 if (return_type == null) {
649 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
650 member_name, Delegate.FullDelegateDesc (invoke_method));
654 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
655 return_type.GetSignatureForError (), member_name,
656 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
659 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
661 // if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
664 var invoke = Delegate.GetInvokeMethod (target_type);
666 Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
667 mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
668 return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
671 #region IErrorHandler Members
673 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
678 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
680 Error_ConversionFailed (rc, best as MethodSpec, null);
684 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
686 Error_ConversionFailed (rc, best as MethodSpec, null);
690 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
699 // Created from the conversion code
701 public class ImplicitDelegateCreation : DelegateCreation
705 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
708 this.method_group = mg;
713 // Returns true when type is MVAR or has MVAR reference
715 public static bool ContainsMethodTypeParameter (TypeSpec type)
717 var tps = type as TypeParameterSpec;
719 return tps.IsMethodOwned;
721 var ec = type as ElementTypeSpec;
723 return ContainsMethodTypeParameter (ec.Element);
725 foreach (var t in type.TypeArguments) {
726 if (ContainsMethodTypeParameter (t)) {
732 return ContainsMethodTypeParameter (type.DeclaringType);
739 if (ContainsMethodTypeParameter (type))
742 var best = method_group.BestCandidate;
743 if (ContainsMethodTypeParameter (best.DeclaringType))
746 if (best.TypeArguments != null) {
747 foreach (var ta in best.TypeArguments) {
748 if (ContainsMethodTypeParameter (ta))
756 protected override Expression DoResolve (ResolveContext ec)
758 var expr = base.DoResolve (ec);
760 return ErrorExpression.Instance;
762 if (ec.IsInProbingMode)
766 // Cache any static delegate creation
768 if (method_group.InstanceExpression != null)
772 // Cannot easily cache types with MVAR
778 // Create type level cache for a delegate instance
780 var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
781 int id = parent.MethodGroupsCounter++;
783 mg_cache = new Field (parent, new TypeExpression (type, loc),
784 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
785 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
787 parent.AddField (mg_cache);
792 public override void Emit (EmitContext ec)
794 Label l_initialized = ec.DefineLabel ();
796 if (mg_cache != null) {
797 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
798 ec.Emit (OpCodes.Brtrue_S, l_initialized);
803 if (mg_cache != null) {
804 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
805 ec.MarkLabel (l_initialized);
806 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
812 // A delegate-creation-expression, invoked from the `New' class
814 public class NewDelegate : DelegateCreation
816 public Arguments Arguments;
819 // This constructor is invoked from the `New' expression
821 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
824 this.Arguments = Arguments;
828 protected override Expression DoResolve (ResolveContext ec)
830 if (Arguments == null || Arguments.Count != 1) {
831 ec.Report.Error (149, loc, "Method name expected");
835 Argument a = Arguments [0];
836 if (!a.ResolveMethodGroup (ec))
839 Expression e = a.Expr;
841 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
842 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
843 e = ame.Compatible (ec, type);
847 return e.Resolve (ec);
850 method_group = e as MethodGroupExpr;
851 if (method_group == null) {
852 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
853 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
854 } else if (!e.Type.IsDelegate) {
855 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
860 // An argument is not a method but another delegate
862 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
863 method_group.InstanceExpression = e;
866 return base.DoResolve (ec);
871 // Invocation converted to delegate Invoke call
873 class DelegateInvocation : ExpressionStatement
875 readonly Expression InstanceExpr;
876 readonly bool conditionalAccessReceiver;
880 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
882 this.InstanceExpr = instance_expr;
883 this.arguments = args;
884 this.conditionalAccessReceiver = conditionalAccessReceiver;
888 public override bool ContainsEmitWithAwait ()
890 return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
893 public override Expression CreateExpressionTree (ResolveContext ec)
895 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
896 InstanceExpr.CreateExpressionTree (ec));
898 return CreateExpressionFactoryCall (ec, "Invoke", args);
901 public override void FlowAnalysis (FlowAnalysisContext fc)
903 InstanceExpr.FlowAnalysis (fc);
904 if (arguments != null)
905 arguments.FlowAnalysis (fc);
908 protected override Expression DoResolve (ResolveContext ec)
910 TypeSpec del_type = InstanceExpr.Type;
911 if (del_type == null)
915 // Do only core overload resolution the rest of the checks has been
916 // done on primary expression
918 method = Delegate.GetInvokeMethod (del_type);
919 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
920 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
921 if (valid == null && !res.BestCandidateIsDynamic)
924 type = method.ReturnType;
925 if (conditionalAccessReceiver)
926 type = LiftMemberType (ec, type);
928 eclass = ExprClass.Value;
932 public override void Emit (EmitContext ec)
934 if (conditionalAccessReceiver) {
935 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
939 // Invocation on delegates call the virtual Invoke member
940 // so we are always `instance' calls
942 var call = new CallEmitter ();
943 call.InstanceExpression = InstanceExpr;
944 call.Emit (ec, method, arguments, loc);
946 if (conditionalAccessReceiver)
947 ec.CloseConditionalAccess (type.IsNullableType && type != method.ReturnType ? type : null);
950 public override void EmitStatement (EmitContext ec)
952 if (conditionalAccessReceiver) {
953 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
958 var call = new CallEmitter ();
959 call.InstanceExpression = InstanceExpr;
960 call.EmitStatement (ec, method, arguments, loc);
962 if (conditionalAccessReceiver)
963 ec.CloseConditionalAccess (null);
966 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
968 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);