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 IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using System.Reflection;
23 using System.Reflection.Emit;
26 namespace Mono.CSharp {
29 // Delegate container implementation
31 public class Delegate : TypeDefinition, IParametersMember
33 FullNamedExpression ReturnType;
34 readonly ParametersCompiled parameters;
36 Constructor Constructor;
38 Method BeginInvokeBuilder;
39 Method EndInvokeBuilder;
41 static readonly string[] attribute_targets = new string [] { "type", "return" };
43 public static readonly string InvokeMethodName = "Invoke";
45 Expression instance_expr;
46 ReturnParameter return_attributes;
48 const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
50 const Modifiers AllowedModifiers =
58 public Delegate (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
60 : base (parent, name, attrs, MemberKind.Delegate)
63 this.ReturnType = type;
64 ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
65 IsTopLevel ? Modifiers.INTERNAL :
66 Modifiers.PRIVATE, name.Location, Report);
67 parameters = param_list;
68 spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
72 public TypeSpec MemberType {
74 return ReturnType.Type;
78 public AParametersCollection Parameters {
84 public FullNamedExpression TypExpression {
92 public override void Accept (StructuralVisitor visitor)
97 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
99 if (a.Target == AttributeTargets.ReturnValue) {
100 if (return_attributes == null)
101 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
103 return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
107 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
110 public override AttributeTargets AttributeTargets {
112 return AttributeTargets.Delegate;
116 protected override bool DoDefineMembers ()
118 var builtin_types = Compiler.BuiltinTypes;
120 var ctor_parameters = ParametersCompiled.CreateFullyResolved (
122 new Parameter (new TypeExpression (builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
123 new Parameter (new TypeExpression (builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
126 builtin_types.Object,
131 Constructor = new Constructor (this, Constructor.ConstructorName,
132 Modifiers.PUBLIC, null, ctor_parameters, Location);
133 Constructor.Define ();
136 // Here the various methods like Invoke, BeginInvoke etc are defined
138 // First, call the `out of band' special method for
139 // defining recursively any types we need:
143 if (!p.Resolve (this))
150 // Check accessibility
151 foreach (var partype in p.Types) {
152 if (!IsAccessibleAs (partype)) {
153 Report.SymbolRelatedToPreviousError (partype);
154 Report.Error (59, Location,
155 "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
156 partype.GetSignatureForError (), GetSignatureForError ());
160 var ret_type = ReturnType.ResolveAsType (this);
161 if (ret_type == null)
165 // We don't have to check any others because they are all
166 // guaranteed to be accessible - they are standard types.
168 if (!IsAccessibleAs (ret_type)) {
169 Report.SymbolRelatedToPreviousError (ret_type);
170 Report.Error (58, Location,
171 "Inconsistent accessibility: return type `" +
172 ret_type.GetSignatureForError () + "' is less " +
173 "accessible than delegate `" + GetSignatureForError () + "'");
177 CheckProtectedModifier ();
179 if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) {
180 Method.Error1599 (Location, ret_type, Report);
184 VarianceDecl.CheckTypeVariance (ret_type, Variance.Covariant, this);
186 var resolved_rt = new TypeExpression (ret_type, Location);
187 InvokeBuilder = new Method (this, resolved_rt, MethodModifiers, new MemberName (InvokeMethodName), p, null);
188 InvokeBuilder.Define ();
191 // Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
193 if (!IsCompilerGenerated) {
194 DefineAsyncMethods (resolved_rt);
200 void DefineAsyncMethods (TypeExpression returnType)
202 var iasync_result = Module.PredefinedTypes.IAsyncResult;
203 var async_callback = Module.PredefinedTypes.AsyncCallback;
206 // It's ok when async types don't exist, the delegate will have Invoke method only
208 if (!iasync_result.Define () || !async_callback.Define ())
214 ParametersCompiled async_parameters;
215 if (Parameters.Count == 0) {
216 async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
218 var compiled = new Parameter[Parameters.Count];
219 for (int i = 0; i < compiled.Length; ++i) {
220 var p = parameters[i];
221 compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
223 p.ModFlags & Parameter.Modifier.RefOutMask,
224 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
227 async_parameters = new ParametersCompiled (compiled);
230 async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
232 new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
233 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, Location), "object", Parameter.Modifier.NONE, null, Location)
236 async_callback.TypeSpec,
237 Compiler.BuiltinTypes.Object
241 BeginInvokeBuilder = new Method (this,
242 new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
243 new MemberName ("BeginInvoke"), async_parameters, null);
244 BeginInvokeBuilder.Define ();
247 // EndInvoke is a bit more interesting, all the parameters labeled as
248 // out or ref have to be duplicated here.
252 // Define parameters, and count out/ref parameters
254 ParametersCompiled end_parameters;
257 foreach (Parameter p in Parameters.FixedParameters) {
258 if ((p.ModFlags & Parameter.Modifier.RefOutMask) != 0)
262 if (out_params > 0) {
263 Parameter[] end_params = new Parameter[out_params];
266 for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
267 Parameter p = parameters [i];
268 if ((p.ModFlags & Parameter.Modifier.RefOutMask) == 0)
271 end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
273 p.ModFlags & Parameter.Modifier.RefOutMask,
274 p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
277 end_parameters = new ParametersCompiled (end_params);
279 end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
282 end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
284 new TypeExpression (iasync_result.TypeSpec, Location),
285 "result", Parameter.Modifier.NONE, null, Location),
286 iasync_result.TypeSpec);
289 // Create method, define parameters, register parameters with type system
291 EndInvokeBuilder = new Method (this, returnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
292 EndInvokeBuilder.Define ();
295 public override void PrepareEmit ()
297 if (!Parameters.IsEmpty) {
298 parameters.ResolveDefaultValues (this);
301 InvokeBuilder.PrepareEmit ();
302 if (BeginInvokeBuilder != null) {
303 BeginInvokeBuilder.PrepareEmit ();
304 EndInvokeBuilder.PrepareEmit ();
308 public override void Emit ()
312 if (ReturnType.Type != null) {
313 if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
314 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
315 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
316 } else if (ReturnType.Type.HasDynamicElement) {
317 return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
318 Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
321 ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
324 Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
325 Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
327 parameters.CheckConstraints (this);
328 parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
329 InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
331 if (BeginInvokeBuilder != null) {
332 BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
333 EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
335 BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
336 EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
340 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
342 base_type = Compiler.BuiltinTypes.MulticastDelegate;
347 protected override TypeAttributes TypeAttr {
349 return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
353 public override string[] ValidAttributeTargets {
355 return attribute_targets;
360 protected override bool VerifyClsCompliance ()
362 if (!base.VerifyClsCompliance ()) {
366 parameters.VerifyClsCompliance (this);
368 if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
369 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
370 GetSignatureForError ());
376 public static MethodSpec GetConstructor (TypeSpec delType)
378 var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
379 return (MethodSpec) ctor;
383 // Returns the "Invoke" from a delegate type
385 public static MethodSpec GetInvokeMethod (TypeSpec delType)
387 var invoke = MemberCache.FindMember (delType,
388 MemberFilter.Method (InvokeMethodName, 0, null, null),
389 BindingRestriction.DeclaredOnly);
391 return (MethodSpec) invoke;
394 public static AParametersCollection GetParameters (TypeSpec delType)
396 var invoke_mb = GetInvokeMethod (delType);
397 return invoke_mb.Parameters;
401 // 15.2 Delegate compatibility
403 public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
406 // For each value parameter (a parameter with no ref or out modifier), an
407 // identity conversion or implicit reference conversion exists from the
408 // parameter type in D to the corresponding parameter type in M
413 if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
416 if (a.IsGenericParameter && b.IsGenericParameter)
419 return Convert.ImplicitReferenceConversionExists (a, b);
422 public static string FullDelegateDesc (MethodSpec invoke_method)
424 return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
427 public Expression InstanceExpression {
429 return instance_expr;
432 instance_expr = value;
438 // Base class for `NewDelegate' and `ImplicitDelegateCreation'
440 public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
442 protected MethodSpec constructor_method;
443 protected MethodGroupExpr method_group;
445 public bool AllowSpecialMethodsInvocation { get; set; }
447 public override bool ContainsEmitWithAwait ()
449 var instance = method_group.InstanceExpression;
450 return instance != null && instance.ContainsEmitWithAwait ();
453 public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
455 Arguments delegate_arguments = new Arguments (pd.Count);
456 for (int i = 0; i < pd.Count; ++i) {
457 Argument.AType atype_modifier;
458 switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
459 case Parameter.Modifier.REF:
460 atype_modifier = Argument.AType.Ref;
462 case Parameter.Modifier.OUT:
463 atype_modifier = Argument.AType.Out;
470 var ptype = types[i];
471 if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
472 ptype = rc.BuiltinTypes.Object;
474 delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
477 return delegate_arguments;
480 public override Expression CreateExpressionTree (ResolveContext ec)
482 MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
484 Arguments args = new Arguments (3);
485 args.Add (new Argument (new TypeOf (type, loc)));
487 if (method_group.InstanceExpression == null)
488 args.Add (new Argument (new NullLiteral (loc)));
490 args.Add (new Argument (method_group.InstanceExpression));
492 args.Add (new Argument (method_group.CreateExpressionTree (ec)));
493 Expression e = new Invocation (ma, args).Resolve (ec);
497 e = Convert.ExplicitConversion (ec, e, type, loc);
501 return e.CreateExpressionTree (ec);
504 protected override Expression DoResolve (ResolveContext ec)
506 constructor_method = Delegate.GetConstructor (type);
508 var invoke_method = Delegate.GetInvokeMethod (type);
510 Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
511 method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
512 if (method_group == null)
515 var delegate_method = method_group.BestCandidate;
517 if (delegate_method.DeclaringType.IsNullableType) {
518 ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
519 delegate_method.GetSignatureForError ());
523 if (!AllowSpecialMethodsInvocation)
524 Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
526 ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
528 method_group.InstanceExpression = emg.ExtensionExpression;
529 TypeSpec e_type = emg.ExtensionExpression.Type;
530 if (TypeSpec.IsValueType (e_type)) {
531 ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
532 delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
536 TypeSpec rt = method_group.BestCandidateReturnType;
537 if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
538 rt = ec.BuiltinTypes.Object;
540 if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
541 Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
542 Error_ConversionFailed (ec, delegate_method, ret_expr);
545 if (method_group.IsConditionallyExcluded) {
546 ec.Report.SymbolRelatedToPreviousError (delegate_method);
547 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
548 if (m != null && m.IsPartialDefinition) {
549 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
550 delegate_method.GetSignatureForError ());
552 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
553 TypeManager.CSharpSignature (delegate_method));
557 var expr = method_group.InstanceExpression;
558 if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
559 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
561 eclass = ExprClass.Value;
565 public override void Emit (EmitContext ec)
568 if (method_group.InstanceExpression == null) {
569 ie = new InstanceEmitter ();
572 ie = new InstanceEmitter (method_group.InstanceExpression, false);
573 ie.NullShortCircuit = method_group.NullShortCircuit;
577 var delegate_method = method_group.BestCandidate;
579 // Any delegate must be sealed
580 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
581 ec.Emit (OpCodes.Dup);
582 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
584 ec.Emit (OpCodes.Ldftn, delegate_method);
587 ec.Emit (OpCodes.Newobj, constructor_method);
589 if (method_group.NullShortCircuit) {
590 ie.EmitResultLift (ec, type, false);
594 public override void FlowAnalysis (FlowAnalysisContext fc) {
595 base.FlowAnalysis (fc);
596 method_group.FlowAnalysis (fc);
599 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
601 var invoke_method = Delegate.GetInvokeMethod (type);
602 string member_name = method_group.InstanceExpression != null ?
603 Delegate.FullDelegateDesc (method) :
604 TypeManager.GetFullNameSignature (method);
606 ec.Report.SymbolRelatedToPreviousError (type);
607 ec.Report.SymbolRelatedToPreviousError (method);
608 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
609 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",
610 method.ReturnType.GetSignatureForError (), member_name,
611 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
615 if (return_type == null) {
616 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
617 member_name, Delegate.FullDelegateDesc (invoke_method));
621 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
622 return_type.GetSignatureForError (), member_name,
623 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
626 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
628 // if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
631 var invoke = Delegate.GetInvokeMethod (target_type);
633 Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
634 return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
637 #region IErrorHandler Members
639 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
644 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
646 Error_ConversionFailed (rc, best as MethodSpec, null);
650 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
652 Error_ConversionFailed (rc, best as MethodSpec, null);
656 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
665 // Created from the conversion code
667 public class ImplicitDelegateCreation : DelegateCreation
671 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
674 this.method_group = mg;
679 // Returns true when type is MVAR or has MVAR reference
681 public static bool ContainsMethodTypeParameter (TypeSpec type)
683 var tps = type as TypeParameterSpec;
685 return tps.IsMethodOwned;
687 var ec = type as ElementTypeSpec;
689 return ContainsMethodTypeParameter (ec.Element);
691 foreach (var t in type.TypeArguments) {
692 if (ContainsMethodTypeParameter (t)) {
698 return ContainsMethodTypeParameter (type.DeclaringType);
705 if (ContainsMethodTypeParameter (type))
708 var best = method_group.BestCandidate;
709 if (ContainsMethodTypeParameter (best.DeclaringType))
712 if (best.TypeArguments != null) {
713 foreach (var ta in best.TypeArguments) {
714 if (ContainsMethodTypeParameter (ta))
722 protected override Expression DoResolve (ResolveContext ec)
724 var expr = base.DoResolve (ec);
726 return ErrorExpression.Instance;
728 if (ec.IsInProbingMode)
732 // Cache any static delegate creation
734 if (method_group.InstanceExpression != null)
738 // Cannot easily cache types with MVAR
744 // Create type level cache for a delegate instance
746 var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
747 int id = parent.MethodGroupsCounter++;
749 mg_cache = new Field (parent, new TypeExpression (type, loc),
750 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
751 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
753 parent.AddField (mg_cache);
758 public override void Emit (EmitContext ec)
760 Label l_initialized = ec.DefineLabel ();
762 if (mg_cache != null) {
763 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
764 ec.Emit (OpCodes.Brtrue_S, l_initialized);
769 if (mg_cache != null) {
770 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
771 ec.MarkLabel (l_initialized);
772 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
778 // A delegate-creation-expression, invoked from the `New' class
780 public class NewDelegate : DelegateCreation
782 public Arguments Arguments;
785 // This constructor is invoked from the `New' expression
787 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
790 this.Arguments = Arguments;
794 protected override Expression DoResolve (ResolveContext ec)
796 if (Arguments == null || Arguments.Count != 1) {
797 ec.Report.Error (149, loc, "Method name expected");
801 Argument a = Arguments [0];
802 if (!a.ResolveMethodGroup (ec))
805 Expression e = a.Expr;
807 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
808 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
809 e = ame.Compatible (ec, type);
813 return e.Resolve (ec);
816 method_group = e as MethodGroupExpr;
817 if (method_group == null) {
818 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
819 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
820 } else if (!e.Type.IsDelegate) {
821 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
826 // An argument is not a method but another delegate
828 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
829 method_group.InstanceExpression = e;
832 return base.DoResolve (ec);
837 // Invocation converted to delegate Invoke call
839 class DelegateInvocation : ExpressionStatement
841 readonly Expression InstanceExpr;
845 public DelegateInvocation (Expression instance_expr, Arguments args, Location loc)
847 this.InstanceExpr = instance_expr;
848 this.arguments = args;
852 public override bool ContainsEmitWithAwait ()
854 return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
857 public override Expression CreateExpressionTree (ResolveContext ec)
859 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
860 InstanceExpr.CreateExpressionTree (ec));
862 return CreateExpressionFactoryCall (ec, "Invoke", args);
865 public override void FlowAnalysis (FlowAnalysisContext fc)
867 InstanceExpr.FlowAnalysis (fc);
868 if (arguments != null)
869 arguments.FlowAnalysis (fc);
872 protected override Expression DoResolve (ResolveContext ec)
874 TypeSpec del_type = InstanceExpr.Type;
875 if (del_type == null)
879 // Do only core overload resolution the rest of the checks has been
880 // done on primary expression
882 method = Delegate.GetInvokeMethod (del_type);
883 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
884 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
885 if (valid == null && !res.BestCandidateIsDynamic)
888 type = method.ReturnType;
889 eclass = ExprClass.Value;
893 public override void Emit (EmitContext ec)
896 // Invocation on delegates call the virtual Invoke member
897 // so we are always `instance' calls
899 var call = new CallEmitter ();
900 call.InstanceExpression = InstanceExpr;
901 call.Emit (ec, method, arguments, loc);
904 public override void EmitStatement (EmitContext ec)
906 var call = new CallEmitter ();
907 call.InstanceExpression = InstanceExpr;
908 call.EmitStatement (ec, method, arguments, loc);
911 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
913 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);