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 Error_ConversionFailed (ec, delegate_method, delegate_method.ReturnType);
593 if (method_group.IsConditionallyExcluded) {
594 ec.Report.SymbolRelatedToPreviousError (delegate_method);
595 MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
596 if (m != null && m.IsPartialDefinition) {
597 ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
598 delegate_method.GetSignatureForError ());
600 ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
601 TypeManager.CSharpSignature (delegate_method));
605 var expr = method_group.InstanceExpression;
606 if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
607 method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
609 eclass = ExprClass.Value;
613 public override void Emit (EmitContext ec)
615 if (method_group.InstanceExpression == null) {
618 var ie = new InstanceEmitter (method_group.InstanceExpression, false);
619 ie.Emit (ec, method_group.ConditionalAccess);
622 var delegate_method = method_group.BestCandidate;
624 // Any delegate must be sealed
625 if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
626 ec.Emit (OpCodes.Dup);
627 ec.Emit (OpCodes.Ldvirtftn, delegate_method);
629 ec.Emit (OpCodes.Ldftn, delegate_method);
632 ec.Emit (OpCodes.Newobj, constructor_method);
635 public override void FlowAnalysis (FlowAnalysisContext fc)
637 base.FlowAnalysis (fc);
638 method_group.FlowAnalysis (fc);
641 void Error_ConversionFailed (ResolveContext ec, MethodSpec method, TypeSpec return_type)
643 var invoke_method = Delegate.GetInvokeMethod (type);
644 string member_name = method_group.InstanceExpression != null ?
645 Delegate.FullDelegateDesc (method) :
646 TypeManager.GetFullNameSignature (method);
648 ec.Report.SymbolRelatedToPreviousError (type);
649 ec.Report.SymbolRelatedToPreviousError (method);
650 if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
651 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",
652 method.ReturnType.GetSignatureForError (), member_name,
653 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
657 if (return_type == null) {
658 ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
659 member_name, Delegate.FullDelegateDesc (invoke_method));
663 if (invoke_method.ReturnType.Kind == MemberKind.ByRef) {
664 ec.Report.Error (8189, loc, "By reference return delegate does not match `{0}' return type",
665 Delegate.FullDelegateDesc (invoke_method));
669 ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
670 return_type.GetSignatureForError (), member_name,
671 invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
674 public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
676 // if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
679 var invoke = Delegate.GetInvokeMethod (target_type);
681 Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
682 mg = mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
683 return mg != null && Delegate.IsTypeCovariant (ec, mg.BestCandidateReturnType, invoke.ReturnType);
686 #region IErrorHandler Members
688 bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
693 bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
695 Error_ConversionFailed (rc, best as MethodSpec, null);
699 bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
701 Error_ConversionFailed (rc, best as MethodSpec, null);
705 bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
714 // Created from the conversion code
716 public class ImplicitDelegateCreation : DelegateCreation
720 public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
723 this.method_group = mg;
728 // Returns true when type is MVAR or has MVAR reference
730 public static bool ContainsMethodTypeParameter (TypeSpec type)
732 var tps = type as TypeParameterSpec;
734 return tps.IsMethodOwned;
736 var ec = type as ElementTypeSpec;
738 return ContainsMethodTypeParameter (ec.Element);
740 foreach (var t in type.TypeArguments) {
741 if (ContainsMethodTypeParameter (t)) {
747 return ContainsMethodTypeParameter (type.DeclaringType);
754 if (ContainsMethodTypeParameter (type))
757 var best = method_group.BestCandidate;
758 if (ContainsMethodTypeParameter (best.DeclaringType))
761 if (best.TypeArguments != null) {
762 foreach (var ta in best.TypeArguments) {
763 if (ContainsMethodTypeParameter (ta))
771 protected override Expression DoResolve (ResolveContext ec)
773 var expr = base.DoResolve (ec);
775 return ErrorExpression.Instance;
777 if (ec.IsInProbingMode)
781 // Cache any static delegate creation
783 if (method_group.InstanceExpression != null)
787 // Cannot easily cache types with MVAR
793 // Create type level cache for a delegate instance
795 var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
796 int id = parent.MethodGroupsCounter++;
798 mg_cache = new Field (parent, new TypeExpression (type, loc),
799 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
800 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
802 parent.AddField (mg_cache);
807 public override void Emit (EmitContext ec)
809 Label l_initialized = ec.DefineLabel ();
811 if (mg_cache != null) {
812 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
813 ec.Emit (OpCodes.Brtrue_S, l_initialized);
818 if (mg_cache != null) {
819 ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
820 ec.MarkLabel (l_initialized);
821 ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
827 // A delegate-creation-expression, invoked from the `New' class
829 public class NewDelegate : DelegateCreation
831 public Arguments Arguments;
834 // This constructor is invoked from the `New' expression
836 public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
839 this.Arguments = Arguments;
843 protected override Expression DoResolve (ResolveContext ec)
845 if (Arguments == null || Arguments.Count != 1) {
846 ec.Report.Error (149, loc, "Method name expected");
850 Argument a = Arguments [0];
851 if (!a.ResolveMethodGroup (ec))
854 Expression e = a.Expr;
856 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
857 if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
858 e = ame.Compatible (ec, type);
862 return e.Resolve (ec);
865 method_group = e as MethodGroupExpr;
866 if (method_group == null) {
867 if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
868 e = Convert.ImplicitConversionRequired (ec, e, type, loc);
869 } else if (!e.Type.IsDelegate) {
870 e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
875 // An argument is not a method but another delegate
877 method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
878 method_group.InstanceExpression = e;
881 return base.DoResolve (ec);
886 // Invocation converted to delegate Invoke call
888 class DelegateInvocation : ExpressionStatement
890 readonly Expression InstanceExpr;
891 readonly bool conditionalAccessReceiver;
895 public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
897 this.InstanceExpr = instance_expr;
898 this.arguments = args;
899 this.conditionalAccessReceiver = conditionalAccessReceiver;
903 public override bool ContainsEmitWithAwait ()
905 return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
908 public override Expression CreateExpressionTree (ResolveContext ec)
910 Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
911 InstanceExpr.CreateExpressionTree (ec));
913 return CreateExpressionFactoryCall (ec, "Invoke", args);
916 public override void FlowAnalysis (FlowAnalysisContext fc)
918 InstanceExpr.FlowAnalysis (fc);
919 if (arguments != null)
920 arguments.FlowAnalysis (fc);
923 protected override Expression DoResolve (ResolveContext ec)
925 TypeSpec del_type = InstanceExpr.Type;
926 if (del_type == null)
930 // Do only core overload resolution the rest of the checks has been
931 // done on primary expression
933 method = Delegate.GetInvokeMethod (del_type);
934 var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
935 var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
936 if (valid == null && !res.BestCandidateIsDynamic)
939 type = method.ReturnType;
940 if (conditionalAccessReceiver)
941 type = LiftMemberType (ec, type);
943 eclass = ExprClass.Value;
947 public override void Emit (EmitContext ec)
949 if (conditionalAccessReceiver) {
950 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
954 // Invocation on delegates call the virtual Invoke member
955 // so we are always `instance' calls
957 var call = new CallEmitter ();
958 call.InstanceExpression = InstanceExpr;
959 call.Emit (ec, method, arguments, loc);
961 if (conditionalAccessReceiver)
962 ec.CloseConditionalAccess (type.IsNullableType && type != method.ReturnType ? type : null);
965 public override void EmitStatement (EmitContext ec)
967 if (conditionalAccessReceiver) {
968 ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
973 var call = new CallEmitter ();
974 call.InstanceExpression = InstanceExpr;
975 call.EmitStatement (ec, method, arguments, loc);
977 if (conditionalAccessReceiver)
978 ec.CloseConditionalAccess (null);
981 public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
983 return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);