|
| 1 | +using System; |
| 2 | +using System.Dynamic; |
| 3 | +using System.Reflection; |
| 4 | + |
| 5 | +using BindFlags = ImpliedReflection.Bind; |
| 6 | + |
| 7 | +using static System.Linq.Expressions.Expression; |
| 8 | +using System.Runtime.CompilerServices; |
| 9 | +using System.Management.Automation; |
| 10 | +using System.Linq.Expressions; |
| 11 | + |
| 12 | +namespace ImpliedReflection |
| 13 | +{ |
| 14 | + internal class ReplicateInstanceBinder : InvokeMemberBinder |
| 15 | + { |
| 16 | + public readonly static ReplicateInstanceBinder Instance = new ReplicateInstanceBinder(); |
| 17 | + |
| 18 | + private ReplicateInstanceBinder() |
| 19 | + : base(nameof(PSMemberInfoExtensions.ReplicateInstance), ignoreCase: false, new CallInfo(1, "instance")) |
| 20 | + { |
| 21 | + } |
| 22 | + |
| 23 | + public override DynamicMetaObject FallbackInvoke( |
| 24 | + DynamicMetaObject target, |
| 25 | + DynamicMetaObject[] args, |
| 26 | + DynamicMetaObject errorSuggestion) |
| 27 | + { |
| 28 | + throw new System.NotImplementedException(); |
| 29 | + } |
| 30 | + |
| 31 | + public override DynamicMetaObject FallbackInvokeMember( |
| 32 | + DynamicMetaObject target, |
| 33 | + DynamicMetaObject[] args, |
| 34 | + DynamicMetaObject errorSuggestion) |
| 35 | + { |
| 36 | + Type type = target.RuntimeType; |
| 37 | + MethodInfo method = type.GetMethod( |
| 38 | + VersionSpecificMemberNames.PrivateMemberNames.PSMemberInfo_ReplicateInstance, |
| 39 | + BindFlags.Any.Instance, |
| 40 | + null, |
| 41 | + new[] { typeof(object) }, |
| 42 | + null); |
| 43 | + |
| 44 | + if (method == null) |
| 45 | + { |
| 46 | + return new DynamicMetaObject( |
| 47 | + Block( |
| 48 | + Throw(New(Cache.RuntimeException_ctor, Constant(ImpliedReflectionStrings.InvalidMemberInfo))), |
| 49 | + Default(typeof(object))), |
| 50 | + BindingRestrictions.GetTypeRestriction(target.Expression, type)); |
| 51 | + } |
| 52 | + |
| 53 | + Expression instance = Convert(target.Expression, type); |
| 54 | + Expression callExpr = Call(instance, method, args[0].Expression); |
| 55 | + |
| 56 | + if (typeof(PSProperty).IsAssignableFrom(type)) |
| 57 | + { |
| 58 | + // PSProperty doesn't override ReplicateInstance, so the call doesn't actually change |
| 59 | + // it's private baseObject field. |
| 60 | + FieldInfo baseObject = typeof(PSProperty).GetField( |
| 61 | + nameof(baseObject), |
| 62 | + BindFlags.NonPublic.Instance); |
| 63 | + |
| 64 | + return new DynamicMetaObject( |
| 65 | + Block(callExpr, Assign(Field(instance, baseObject), args[0].Expression), Default(typeof(object))), |
| 66 | + BindingRestrictions.GetTypeRestriction(target.Expression, type)); |
| 67 | + } |
| 68 | + |
| 69 | + return new DynamicMetaObject( |
| 70 | + Block(callExpr, Default(typeof(object))), |
| 71 | + BindingRestrictions.GetTypeRestriction(target.Expression, type)); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments