private DynamicMetaObject IndexWithNegativeChecks(DynamicMetaObject target, DynamicMetaObject index, DynamicMetaObject value, PropertyInfo lengthProperty, Func <Expression, Expression, Expression, Expression> generateIndexOperation)
        {
            DynamicMetaObject[] dynamicMetaObjectArray = new DynamicMetaObject[1];
            dynamicMetaObjectArray[0] = index;
            BindingRestrictions bindingRestriction = target.CombineRestrictions(dynamicMetaObjectArray).Merge(value.Restrictions);

            bindingRestriction = bindingRestriction.Merge(BinderUtils.GetOptionalVersionAndLanguageCheckForType(this, target.LimitType, this._version));
            ParameterExpression parameterExpression  = Expression.Parameter(target.LimitType, "target");
            ParameterExpression parameterExpression1 = Expression.Parameter(typeof(int), "len");
            Expression          expression           = value.Expression;
            ParameterExpression parameterExpression2 = Expression.Parameter(expression.Type, "value");
            ParameterExpression parameterExpression3 = Expression.Parameter(typeof(int), "index");

            ParameterExpression[] parameterExpressionArray = new ParameterExpression[4];
            parameterExpressionArray[0] = parameterExpression;
            parameterExpressionArray[1] = parameterExpression2;
            parameterExpressionArray[2] = parameterExpression1;
            parameterExpressionArray[3] = parameterExpression3;
            Expression[] expressionArray = new Expression[7];
            expressionArray[0] = Expression.Assign(parameterExpression, target.Expression.Cast(target.LimitType));
            expressionArray[1] = Expression.Assign(parameterExpression2, expression);
            expressionArray[2] = Expression.Assign(parameterExpression1, Expression.Property(parameterExpression, lengthProperty));
            expressionArray[3] = Expression.Assign(parameterExpression3, index.Expression);
            expressionArray[4] = Expression.IfThen(Expression.LessThan(parameterExpression3, ExpressionCache.Constant(0)), Expression.Assign(parameterExpression3, Expression.Add(parameterExpression3, parameterExpression1)));
            expressionArray[5] = generateIndexOperation(parameterExpression, parameterExpression3, parameterExpression2);
            expressionArray[6] = parameterExpression2.Cast(typeof(object));
            return(new DynamicMetaObject(Expression.Block(parameterExpressionArray, expressionArray), bindingRestriction));
        }
Exemple #2
0
        private static Func <T, int> CreateGetHashCode(Type underlyingType)
        {
            ParameterExpression value = nameof(value).Parameter <T>();

            return(value.Cast(underlyingType)
                   .Call(nameof(object.GetHashCode))
                   .Lambda <Func <T, int> >(value)
                   .Compile());
        }
Exemple #3
0
        private static Comparison <T> CreateCompare(Type underlyingType)
        {
            ParameterExpression value1 = nameof(value1).Parameter <T>();
            ParameterExpression value2 = nameof(value2).Parameter <T>();

            return(value1.Cast(underlyingType)
                   .Call(nameof(IComparable <T> .CompareTo), value2.Cast(underlyingType))
                   .Lambda <Comparison <T> >(value1, value2)
                   .Compile());
        }
Exemple #4
0
        private static Func <T, T, bool> CreateEquals(Type underlyingType)
        {
            ParameterExpression value1 = nameof(value1).Parameter <T>();
            ParameterExpression value2 = nameof(value2).Parameter <T>();

            return(value1.Cast(underlyingType)
                   .Operation(EqualityOp.EqualTo, value2.Cast(underlyingType))
                   .Lambda <Func <T, T, bool> >(value1, value2)
                   .Compile());
        }
        public static Func <TArg1, T> CreateFactoryMethod <TArg1, T>()
        {
            var constructor = GetBestConstructor(typeof(T), new[] { typeof(TArg1) });

            if (constructor == null)
            {
                return(null);
            }

            var parameters = new ParameterExpression[] {
                Expression.Parameter(typeof(TArg1), "arg1")
            };

            return(Expression
                   .Lambda <Func <TArg1, T> >(
                       Expression.New(constructor.Constructor, parameters.Cast <Expression>()), parameters
                       )
                   .Compile());
        }
        public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion)
        {
            PSMemberInfo        info;
            BindingRestrictions restrictions2;
            bool flag3;
            Type type4;

            if (!target.HasValue || !value.HasValue)
            {
                return(base.Defer(target, new DynamicMetaObject[] { value }));
            }
            object obj2 = PSObject.Base(target.Value);

            if (obj2 == null)
            {
                return(target.ThrowRuntimeError(new DynamicMetaObject[] { value }, BindingRestrictions.Empty, "PropertyNotFound", ParserStrings.PropertyNotFound, new Expression[] { Expression.Constant(base.Name) }).WriteToDebugLog(this));
            }
            if (value.Value == AutomationNull.Value)
            {
                value = new DynamicMetaObject(ExpressionCache.NullConstant, value.PSGetTypeRestriction(), null);
            }
            if (this._getMemberBinder.HasInstanceMember && PSGetMemberBinder.TryGetInstanceMember(target.Value, base.Name, out info))
            {
                ParameterExpression   expression   = Expression.Variable(typeof(PSMemberInfo));
                ParameterExpression   expression2  = Expression.Variable(typeof(object));
                ConditionalExpression expression3  = Expression.Condition(Expression.Call(CachedReflectionInfo.PSGetMemberBinder_TryGetInstanceMember, target.Expression.Cast(typeof(object)), Expression.Constant(base.Name), expression), Expression.Assign(Expression.Property(expression, "Value"), value.Expression.Cast(typeof(object))), base.GetUpdateExpression(typeof(object)));
                BindingRestrictions   restrictions = BinderUtils.GetVersionCheck(this._getMemberBinder, this._getMemberBinder._version).Merge(value.PSGetTypeRestriction());
                return(new DynamicMetaObject(Expression.Block(new ParameterExpression[] { expression, expression2 }, new Expression[] { expression3 }), restrictions).WriteToDebugLog(this));
            }
            if (obj2 is IDictionary)
            {
                Type genericTypeArg = null;
                bool flag           = PSGetMemberBinder.IsGenericDictionary(obj2, ref genericTypeArg);
                if (!flag || (genericTypeArg != null))
                {
                    bool                flag2;
                    Type                type       = flag ? typeof(IDictionary <,>).MakeGenericType(new Type[] { typeof(string), genericTypeArg }) : typeof(IDictionary);
                    MethodInfo          method     = type.GetMethod("set_Item");
                    ParameterExpression left       = Expression.Variable(genericTypeArg ?? typeof(object));
                    Type                resultType = left.Type;
                    LanguagePrimitives.ConversionData conversion = LanguagePrimitives.FigureConversion(value.Value, resultType, out flag2);
                    if (conversion.Rank != ConversionRank.None)
                    {
                        Expression right = PSConvertBinder.InvokeConverter(conversion, value.Expression, resultType, flag2, ExpressionCache.InvariantCulture);
                        return(new DynamicMetaObject(Expression.Block(new ParameterExpression[] { left }, new Expression[] { Expression.Assign(left, right), Expression.Call(PSGetMemberBinder.GetTargetExpr(target).Cast(type), method, Expression.Constant(base.Name), right), right.Cast(typeof(object)) }), target.CombineRestrictions(new DynamicMetaObject[] { value })).WriteToDebugLog(this));
                    }
                }
            }
            info          = this._getMemberBinder.GetPSMemberInfo(target, out restrictions2, out flag3, out type4, null, null);
            restrictions2 = restrictions2.Merge(value.PSGetTypeRestriction());
            if (ExecutionContext.HasEverUsedConstrainedLanguage)
            {
                restrictions2 = restrictions2.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage());
                DynamicMetaObject obj3 = PSGetMemberBinder.EnsureAllowedInLanguageMode(LocalPipeline.GetExecutionContextFromTLS().LanguageMode, target, obj2, base.Name, this._static, new DynamicMetaObject[] { value }, restrictions2, "PropertySetterNotSupportedInConstrainedLanguage", ParserStrings.PropertySetConstrainedLanguage);
                if (obj3 != null)
                {
                    return(obj3.WriteToDebugLog(this));
                }
            }
            if (flag3)
            {
                if (info == null)
                {
                    return((errorSuggestion ?? new DynamicMetaObject(Compiler.ThrowRuntimeError("PropertyAssignmentException", ParserStrings.PropertyNotFound, this.ReturnType, new Expression[] { Expression.Constant(base.Name) }), restrictions2)).WriteToDebugLog(this));
                }
                PSPropertyInfo info3 = info as PSPropertyInfo;
                if (info3 != null)
                {
                    if (!info3.IsSettable)
                    {
                        Expression innerException = Expression.New(CachedReflectionInfo.SetValueException_ctor, new Expression[] { Expression.Constant("PropertyAssignmentException"), Expression.Constant(null, typeof(Exception)), Expression.Constant(ParserStrings.PropertyIsReadOnly), Expression.NewArrayInit(typeof(object), new Expression[] { Expression.Constant(base.Name) }) });
                        return(new DynamicMetaObject(Compiler.ThrowRuntimeErrorWithInnerException("PropertyAssignmentException", Expression.Constant(ParserStrings.PropertyIsReadOnly), innerException, this.ReturnType, new Expression[] { Expression.Constant(base.Name) }), restrictions2).WriteToDebugLog(this));
                    }
                    PSProperty property = info3 as PSProperty;
                    if (property != null)
                    {
                        DotNetAdapter.PropertyCacheEntry adapterData = property.adapterData as DotNetAdapter.PropertyCacheEntry;
                        if (adapterData != null)
                        {
                            Expression expression10;
                            Type       propertyType;
                            if (adapterData.member.DeclaringType.IsGenericTypeDefinition)
                            {
                                Expression expression9 = Expression.New(CachedReflectionInfo.SetValueException_ctor, new Expression[] { Expression.Constant("PropertyAssignmentException"), Expression.Constant(null, typeof(Exception)), Expression.Constant(ExtendedTypeSystem.CannotInvokeStaticMethodOnUninstantiatedGenericType), Expression.NewArrayInit(typeof(object), new Expression[] { Expression.Constant(adapterData.member.DeclaringType.FullName) }) });
                                return(new DynamicMetaObject(Compiler.ThrowRuntimeErrorWithInnerException("PropertyAssignmentException", Expression.Constant(ExtendedTypeSystem.CannotInvokeStaticMethodOnUninstantiatedGenericType), expression9, this.ReturnType, new Expression[] { Expression.Constant(adapterData.member.DeclaringType.FullName) }), restrictions2).WriteToDebugLog(this));
                            }
                            PropertyInfo member = adapterData.member as PropertyInfo;
                            if (member != null)
                            {
                                propertyType = member.PropertyType;
                                Expression expression11 = this._static ? null : PSGetMemberBinder.GetTargetExpr(target);
                                expression10 = Expression.Property(expression11, member);
                            }
                            else
                            {
                                FieldInfo field = (FieldInfo)adapterData.member;
                                propertyType = field.FieldType;
                                Expression expression12 = this._static ? null : PSGetMemberBinder.GetTargetExpr(target);
                                expression10 = Expression.Field(expression12, field);
                            }
                            Type underlyingType = Nullable.GetUnderlyingType(propertyType);
                            Type type7          = underlyingType ?? propertyType;
                            ParameterExpression expression13 = Expression.Variable(type7);
                            Expression          expression14 = (underlyingType != null) ? ((value.Value == null) ? ((Expression)Expression.Constant(null, propertyType)) : ((Expression)Expression.New(propertyType.GetConstructor(new Type[] { underlyingType }), new Expression[] { expression13 }))) : ((Expression)expression13);
                            Expression          expression15 = (type7.Equals(typeof(object)) && value.LimitType.Equals(typeof(PSObject))) ? Expression.Call(CachedReflectionInfo.PSObject_Base, value.Expression.Cast(typeof(PSObject))) : value.CastOrConvert(type7);
                            Expression          expr         = Expression.Block(new ParameterExpression[] { expression13 }, new Expression[] { Expression.Assign(expression13, expression15), Expression.Assign(expression10, expression14), expression13.Cast(typeof(object)) });
                            ParameterExpression variable     = Expression.Variable(typeof(Exception));
                            return(new DynamicMetaObject(Expression.TryCatch(expr.Cast(typeof(object)), new CatchBlock[] { Expression.Catch(variable, Expression.Block(Expression.Call(CachedReflectionInfo.ExceptionHandlingOps_ConvertToMethodInvocationException, variable, Expression.Constant(typeof(SetValueInvocationException)), Expression.Constant(base.Name), ExpressionCache.Constant(0), Expression.Constant(null, typeof(MemberInfo))), Expression.Rethrow(typeof(object)))) }), restrictions2).WriteToDebugLog(this));
                        }
                    }
                    PSCodeProperty property2 = info3 as PSCodeProperty;
                    if (property2 != null)
                    {
                        ParameterExpression expression17 = Expression.Variable(typeof(object));
                        return(new DynamicMetaObject(Expression.Block(new ParameterExpression[] { expression17 }, new Expression[] { Expression.Assign(expression17, value.CastOrConvert(expression17.Type)), PSInvokeMemberBinder.InvokeMethod(property2.SetterCodeReference, null, new DynamicMetaObject[] { target, value }, false), expression17 }), restrictions2).WriteToDebugLog(this));
                    }
                    PSScriptProperty property3 = info3 as PSScriptProperty;
                    if (property3 != null)
                    {
                        return(new DynamicMetaObject(Expression.Call(Expression.Constant(property3), CachedReflectionInfo.PSScriptProperty_InvokeSetter, PSGetMemberBinder.GetTargetExpr(target), value.Expression.Cast(typeof(object))), restrictions2).WriteToDebugLog(this));
                    }
                }
                if (errorSuggestion != null)
                {
                    return(errorSuggestion.WriteToDebugLog(this));
                }
            }
            return(new DynamicMetaObject(Expression.Call(CachedReflectionInfo.PSSetMemberBinder_SetAdaptedValue, PSGetMemberBinder.GetTargetExpr(target).Cast(typeof(object)), Expression.Constant(base.Name), value.Expression.Cast(typeof(object))), restrictions2).WriteToDebugLog(this));
        }
        private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject value, DynamicMetaObject errorSuggestion, string methodName)
        {
            DynamicMetaObject dynamicMetaObject;
            Func <Expression, Expression, Expression, Expression> func = null;
            MethodInfo methodInfo = PSInvokeMemberBinder.FindBestMethod(target, indexes.Append <DynamicMetaObject>(value), string.Concat("set_", methodName), false, this._constraints);

            if (methodInfo != null)
            {
                ParameterInfo[] parameters = methodInfo.GetParameters();
                if ((int)parameters.Length == (int)indexes.Length + 1)
                {
                    Expression[] expressionArray = new Expression[(int)parameters.Length];
                    int          num             = 0;
                    while (num < (int)parameters.Length)
                    {
                        Type         parameterType    = parameters[num].ParameterType;
                        Expression[] expressionArray1 = expressionArray;
                        int          num1             = num;
                        if (num == (int)parameters.Length - 1)
                        {
                            dynamicMetaObject = value;
                        }
                        else
                        {
                            dynamicMetaObject = indexes[num];
                        }
                        expressionArray1[num1] = PSGetIndexBinder.ConvertIndex(dynamicMetaObject, parameterType);
                        if (expressionArray[num] != null)
                        {
                            num++;
                        }
                        else
                        {
                            DynamicMetaObject dynamicMetaObject1 = errorSuggestion;
                            DynamicMetaObject dynamicMetaObject2 = dynamicMetaObject1;
                            if (dynamicMetaObject1 == null)
                            {
                                dynamicMetaObject2 = PSConvertBinder.ThrowNoConversion(target, parameterType, this, this._version, indexes.Append <DynamicMetaObject>(value).ToArray <DynamicMetaObject>());
                            }
                            return(dynamicMetaObject2);
                        }
                    }
                    if ((int)parameters.Length == 2 && parameters[0].ParameterType.Equals(typeof(int)) && target.Value as IDictionary == null)
                    {
                        PropertyInfo property     = target.LimitType.GetProperty("Length");
                        PropertyInfo propertyInfo = property;
                        if (property == null)
                        {
                            propertyInfo = target.LimitType.GetProperty("Count");
                        }
                        PropertyInfo propertyInfo1 = propertyInfo;
                        if (propertyInfo1 != null)
                        {
                            PSSetIndexBinder  pSSetIndexBinder   = this;
                            DynamicMetaObject dynamicMetaObject3 = new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction());
                            DynamicMetaObject dynamicMetaObject4 = new DynamicMetaObject(expressionArray[0], indexes[0].PSGetTypeRestriction());
                            DynamicMetaObject dynamicMetaObject5 = new DynamicMetaObject(expressionArray[1], value.PSGetTypeRestriction());
                            PropertyInfo      propertyInfo2      = propertyInfo1;
                            if (func == null)
                            {
                                func = (Expression t, Expression i, Expression v) => Expression.Call(t, methodInfo, i, v);
                            }
                            return(pSSetIndexBinder.IndexWithNegativeChecks(dynamicMetaObject3, dynamicMetaObject4, dynamicMetaObject5, propertyInfo2, func));
                        }
                    }
                    BindingRestrictions bindingRestriction = target.CombineRestrictions(indexes).Merge(value.PSGetTypeRestriction());
                    bindingRestriction = bindingRestriction.Merge(BinderUtils.GetVersionCheck(this, this._version));
                    bindingRestriction = bindingRestriction.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage());
                    Expression          expression          = expressionArray[(int)expressionArray.Length - 1];
                    ParameterExpression parameterExpression = Expression.Parameter(expression.Type, "value");
                    expressionArray[(int)expressionArray.Length - 1] = parameterExpression;
                    ParameterExpression[] parameterExpressionArray = new ParameterExpression[1];
                    parameterExpressionArray[0] = parameterExpression;
                    Expression[] expressionArray2 = new Expression[3];
                    expressionArray2[0] = Expression.Assign(parameterExpression, expression);
                    expressionArray2[1] = Expression.Call(target.Expression.Cast(target.LimitType), methodInfo, expressionArray);
                    expressionArray2[2] = parameterExpression.Cast(typeof(object));
                    return(new DynamicMetaObject(Expression.Block(parameterExpressionArray, expressionArray2), bindingRestriction));
                }
                else
                {
                    DynamicMetaObject dynamicMetaObject6 = errorSuggestion;
                    DynamicMetaObject dynamicMetaObject7 = dynamicMetaObject6;
                    if (dynamicMetaObject6 == null)
                    {
                        dynamicMetaObject7 = this.CannotIndexTarget(target, indexes, value);
                    }
                    return(dynamicMetaObject7);
                }
            }
            else
            {
                DynamicMetaObject dynamicMetaObject8 = errorSuggestion;
                DynamicMetaObject dynamicMetaObject9 = dynamicMetaObject8;
                if (dynamicMetaObject8 == null)
                {
                    dynamicMetaObject9 = this.CannotIndexTarget(target, indexes, value);
                }
                return(dynamicMetaObject9);
            }
        }
Exemple #8
0
        internal static Expression InvokeMethod(MethodInfo mi, DynamicMetaObject target, DynamicMetaObject[] args, bool expandParameters)
        {
            Expression expression;
            List <ParameterExpression> parameterExpressions = new List <ParameterExpression>();
            List <Expression>          expressions          = new List <Expression>();
            var temps     = new List <ParameterExpression>();
            var initTemps = new List <Expression>();
            List <Expression> expressions1 = new List <Expression>();

            ParameterInfo[] parameters      = mi.GetParameters();
            Expression[]    expressionArray = new Expression[(int)parameters.Length];
            for (int i = 0; i < (int)parameters.Length; i++)
            {
                string name      = parameters[i].Name;
                var    paramName = parameters[i].Name;
                if (string.IsNullOrWhiteSpace(parameters[i].Name))
                {
                    paramName = i.ToString(CultureInfo.InvariantCulture);
                }
                if ((int)parameters[i].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length == 0)
                {
                    if (i < (int)args.Length)
                    {
                        if (!parameters[i].ParameterType.IsByRef)
                        {
                            expressionArray[i] = args[i].CastOrConvertMethodArgument(parameters[i].ParameterType, paramName, mi.Name, temps, initTemps);
                        }
                        else
                        {
                            if (args[i].Value as PSReference != null)
                            {
                                ParameterExpression parameterExpression = Expression.Variable(parameters[i].ParameterType.GetElementType());
                                temps.Add(parameterExpression);
                                MemberExpression memberExpression = Expression.Property(args[i].Expression.Cast(typeof(PSReference)), CachedReflectionInfo.PSReference_Value);
                                initTemps.Add(Expression.Assign(parameterExpression, memberExpression.Convert(parameterExpression.Type)));
                                expressions1.Add(Expression.Assign(memberExpression, parameterExpression.Cast(typeof(object))));
                                expressionArray[i] = parameterExpression;
                            }
                            else
                            {
                                Type[] typeArray = new Type[4];
                                typeArray[0] = typeof(string);
                                typeArray[1] = typeof(Exception);
                                typeArray[2] = typeof(string);
                                typeArray[3] = typeof(object[]);
                                object[] nonRefArgumentToRefParameter = new object[4];
                                nonRefArgumentToRefParameter[0] = "NonRefArgumentToRefParameterMsg";
                                nonRefArgumentToRefParameter[2] = ExtendedTypeSystem.NonRefArgumentToRefParameter;
                                object[] fullName = new object[3];
                                fullName[0] = i + 1;
                                fullName[1] = typeof(PSReference).FullName;
                                fullName[2] = "[ref]";
                                nonRefArgumentToRefParameter[3] = fullName;
                                return(Compiler.CreateThrow(typeof(object), typeof(MethodException), typeArray, nonRefArgumentToRefParameter));
                            }
                        }
                    }
                    else
                    {
                        object defaultValue = parameters[i].DefaultValue;
                        if (defaultValue != null)
                        {
                            expressionArray[i] = Expression.Constant(defaultValue);
                        }
                        else
                        {
                            expressionArray[i] = Expression.Constant(null, parameters[i].ParameterType);
                        }
                    }
                }
                else
                {
                    Func <DynamicMetaObject, Expression> func = null;
                    Type elementType = parameters[i].ParameterType.GetElementType();
                    if (!expandParameters)
                    {
                        Expression expression1 = args[i].CastOrConvertMethodArgument(parameters[i].ParameterType, paramName, mi.Name, temps, initTemps);
                        expressionArray[i] = expression1;
                    }
                    else
                    {
                        Expression[] expressionArray1 = expressionArray;
                        int          num  = i;
                        Type         type = elementType;
                        IEnumerable <DynamicMetaObject> dynamicMetaObjects = args.Skip <DynamicMetaObject>(i);
                        if (func == null)
                        {
                            func = (DynamicMetaObject a) => a.CastOrConvertMethodArgument(elementType, name, mi.Name, parameterExpressions, expressions);
                        }
                        expressionArray1[num] = Expression.NewArrayInit(type, dynamicMetaObjects.Select <DynamicMetaObject, Expression>(func));
                    }
                }
            }
            if (mi.IsStatic)
            {
                expression = Expression.Call(mi, expressionArray);
            }
            else
            {
                expression = Expression.Call(PSGetMemberBinder.GetTargetExpr(target).Cast(mi.DeclaringType), mi, expressionArray);
            }
            Expression expression2 = expression;

            if (temps.Any <ParameterExpression>())
            {
                if (!mi.ReturnType.Equals(typeof(void)) && expressions1.Any <Expression>())
                {
                    ParameterExpression parameterExpression1 = Expression.Variable(mi.ReturnType);
                    temps.Add(parameterExpression1);
                    expression2 = Expression.Assign(parameterExpression1, expression2);
                    expressions1.Add(parameterExpression1);
                }
                expression2 = Expression.Block(mi.ReturnType, temps, initTemps.Append <Expression>(expression2).Concat <Expression>(expressions1));
            }
            return(expression2);
        }
Exemple #9
0
            static Converter()
            {
                ParameterExpression value = nameof(value).Parameter <FROM>();

                To = value.Cast <TO>().Lambda <Convert>(value).Compile();
            }
        private static Expression GetExprForValueType(Type type, Expression convertedExpr, Expression originalExpr, ref BindingRestrictions restrictions)
        {
            Expression expression;
            bool       flag = true;

            if (MutableValueTypesWithInstanceMembers.ContainsKey(type))
            {
                expression = Expression.Call(CachedReflectionInfo.PSVariableAssignmentBinder_CopyInstanceMembersOfValueType.MakeGenericMethod(new Type[] { type }), convertedExpr, originalExpr);
                flag       = false;
            }
            else if (IsValueTypeMutable(type))
            {
                ParameterExpression left = Expression.Variable(type);
                expression = Expression.Block(new ParameterExpression[] { left }, new Expression[] { Expression.Assign(left, convertedExpr), left.Cast(typeof(object)) });
            }
            else
            {
                expression = originalExpr;
            }
            if (flag)
            {
                restrictions = restrictions.Merge(GetVersionCheck(_mutableValueWithInstanceMemberVersion));
            }
            return(expression);
        }
        private DynamicMetaObject GetIndexDictionary(DynamicMetaObject target, DynamicMetaObject[] indexes, Type idictionary)
        {
            bool flag;

            if (indexes.Length > 1)
            {
                return(null);
            }
            MethodInfo method = idictionary.GetMethod("TryGetValue");

            ParameterInfo[] parameters    = method.GetParameters();
            Type            parameterType = parameters[0].ParameterType;

            LanguagePrimitives.ConversionData conversion = LanguagePrimitives.FigureConversion(indexes[0].Value, parameterType, out flag);
            if (conversion.Rank == ConversionRank.None)
            {
                return(null);
            }
            if (indexes[0].LimitType.IsArray && !parameterType.IsArray)
            {
                return(null);
            }
            BindingRestrictions restrictions = target.CombineRestrictions(indexes).Merge(BinderUtils.GetOptionalVersionAndLanguageCheckForType(this, parameterType, this._version));
            Expression          expression   = PSConvertBinder.InvokeConverter(conversion, indexes[0].Expression, parameterType, flag, ExpressionCache.InvariantCulture);
            ParameterExpression expression2  = Expression.Parameter(parameters[1].ParameterType.GetElementType(), "outParam");

            return(new DynamicMetaObject(Expression.Block(new ParameterExpression[] { expression2 }, new Expression[] { Expression.Condition(Expression.Call(target.Expression.Cast(idictionary), method, expression, expression2), expression2.Cast(typeof(object)), this.GetNullResult()) }), restrictions));
        }
Exemple #12
0
        internal static Expression CastOrConvertMethodArgument(this DynamicMetaObject target, Type parameterType, string parameterName, string methodName, List <ParameterExpression> temps, List <Expression> initTemps)
        {
            bool flag;

            if (target.Value == AutomationNull.Value)
            {
                return(Expression.Constant(null, parameterType));
            }
            Type limitType = target.LimitType;

            if (parameterType.Equals(typeof(object)) && limitType.Equals(typeof(PSObject)))
            {
                return(Expression.Call(CachedReflectionInfo.PSObject_Base, target.Expression.Cast(typeof(PSObject))));
            }
            if (parameterType.IsAssignableFrom(limitType))
            {
                return(target.Expression.Cast(parameterType));
            }
            ParameterExpression variable    = Expression.Variable(typeof(Exception));
            ParameterExpression expression2 = Expression.Variable(target.Expression.Type);
            Expression          expression3 = PSConvertBinder.InvokeConverter(LanguagePrimitives.FigureConversion(target.Value, parameterType, out flag), expression2, parameterType, flag, ExpressionCache.InvariantCulture);
            BlockExpression     right       = Expression.Block(new ParameterExpression[] { expression2 }, new Expression[] { Expression.TryCatch(Expression.Block(Expression.Assign(expression2, target.Expression), expression3), new CatchBlock[] { Expression.Catch(variable, Expression.Block(Expression.Call(CachedReflectionInfo.ExceptionHandlingOps_ConvertToArgumentConversionException, variable, Expression.Constant(parameterName), expression2.Cast(typeof(object)), Expression.Constant(methodName), Expression.Constant(parameterType)), Expression.Default(expression3.Type))) }) });
            ParameterExpression item        = Expression.Variable(right.Type);

            temps.Add(item);
            initTemps.Add(Expression.Assign(item, right));
            return(item);
        }
Exemple #13
0
        public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
        {
            bool flag;
            Type type = (Type)target.Value;

            MethodInformation[] methodInformationArray = DotNetAdapter.GetMethodInformationArray(type.GetConstructors());
            target = new DynamicMetaObject(target.Expression, BindingRestrictions.GetInstanceRestriction(target.Expression, target.Value), target.Value);
            string            errorId     = null;
            string            errorMsg    = null;
            int               count       = base.CallInfo.ArgumentCount - base.CallInfo.ArgumentNames.Count;
            MethodInformation information = Adapter.FindBestMethod(methodInformationArray, null, (from arg in args.Take <DynamicMetaObject>(count) select arg.Value).ToArray <object>(), ref errorId, ref errorMsg, out flag);

            if (information == null)
            {
                if (errorSuggestion == null)
                {
                }
                return(new DynamicMetaObject(Expression.Throw(Expression.New(CachedReflectionInfo.MethodException_ctor, new Expression[] { Expression.Constant(errorId), Expression.Constant(null, typeof(Exception)), Expression.Constant(errorMsg), Expression.NewArrayInit(typeof(object), new Expression[] { Expression.Constant(".ctor").Cast(typeof(object)), ExpressionCache.Constant(count).Cast(typeof(object)) }) }), this.ReturnType), target.CombineRestrictions(args)));
            }
            ConstructorInfo method = (ConstructorInfo)information.method;

            ParameterInfo[] parameters = method.GetParameters();
            Expression[]    arguments  = new Expression[parameters.Length];
            int             index      = 0;

            while (index < parameters.Length)
            {
                bool flag3;
                Type parameterType = parameters[index].ParameterType;
                if (parameters[index].GetCustomAttributes(typeof(ParamArrayAttribute), true).Any <object>() && flag)
                {
                    Type elementType = parameters[index].ParameterType.GetElementType();
                    List <Expression> initializers = new List <Expression>();
                    int num3 = index;
                    int num4 = index;
                    while (num4 < count)
                    {
                        bool flag2;
                        LanguagePrimitives.ConversionData data = LanguagePrimitives.FigureConversion(args[index].Value, elementType, out flag2);
                        initializers.Add(PSConvertBinder.InvokeConverter(data, args[num4].Expression, elementType, flag2, ExpressionCache.InvariantCulture));
                        num4++;
                        index++;
                    }
                    arguments[num3] = Expression.NewArrayInit(elementType, initializers);
                    break;
                }
                LanguagePrimitives.ConversionData conversion = LanguagePrimitives.FigureConversion(args[index].Value, parameterType, out flag3);
                arguments[index] = PSConvertBinder.InvokeConverter(conversion, args[index].Expression, parameterType, flag3, ExpressionCache.InvariantCulture);
                index++;
            }
            Expression right = Expression.New(method, arguments);

            if (base.CallInfo.ArgumentNames.Any <string>())
            {
                ParameterExpression expr        = Expression.Parameter(right.Type);
                List <Expression>   expressions = new List <Expression>();
                foreach (string str3 in base.CallInfo.ArgumentNames)
                {
                    Expression   expression3;
                    Type         propertyType;
                    bool         flag4;
                    MemberInfo[] infoArray3 = type.GetMember(str3, MemberTypes.Property | MemberTypes.Field, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    if ((infoArray3.Length != 1) || (!(infoArray3[0] is PropertyInfo) && !(infoArray3[0] is FieldInfo)))
                    {
                        return(target.ThrowRuntimeError(args, BindingRestrictions.Empty, "PropertyNotFoundForType", ParserStrings.PropertyNotFoundForType, new Expression[] { Expression.Constant(str3), Expression.Constant(type) }));
                    }
                    MemberInfo info2 = infoArray3[0];
                    if (info2 is PropertyInfo)
                    {
                        PropertyInfo property = (PropertyInfo)info2;
                        if (property.GetSetMethod() == null)
                        {
                            return(target.ThrowRuntimeError(args, BindingRestrictions.Empty, "PropertyIsReadOnly", ParserStrings.PropertyIsReadOnly, new Expression[] { Expression.Constant(str3) }));
                        }
                        propertyType = property.PropertyType;
                        expression3  = Expression.Property(expr.Cast(info2.DeclaringType), property);
                    }
                    else
                    {
                        propertyType = ((FieldInfo)info2).FieldType;
                        expression3  = Expression.Field(expr.Cast(info2.DeclaringType), (FieldInfo)info2);
                    }
                    LanguagePrimitives.ConversionData data3 = LanguagePrimitives.FigureConversion(args[index].Value, propertyType, out flag4);
                    if (data3.Rank == ConversionRank.None)
                    {
                        return(PSConvertBinder.ThrowNoConversion(args[index], propertyType, this, -1, args.Except <DynamicMetaObject>(new DynamicMetaObject[] { args[index] }).Prepend <DynamicMetaObject>(target).ToArray <DynamicMetaObject>()));
                    }
                    expressions.Add(Expression.Assign(expression3, PSConvertBinder.InvokeConverter(data3, args[index].Expression, propertyType, flag4, ExpressionCache.InvariantCulture)));
                    index++;
                }
                ParameterExpression variable    = Expression.Parameter(typeof(Exception));
                BlockExpression     expression5 = Expression.Block(Expression.Assign(expr, right), Expression.TryCatch(Expression.Block(typeof(void), expressions), new CatchBlock[] { Expression.Catch(variable, Expression.Block(Expression.Call(CachedReflectionInfo.CommandProcessorBase_CheckForSevereException, variable), Compiler.ThrowRuntimeErrorWithInnerException("PropertyAssignmentException", Expression.Property(variable, "Message"), variable, typeof(void), new Expression[0]))) }), expr);
                right = Expression.Block(new ParameterExpression[] { expr }, new Expression[] { expression5 });
            }
            return(new DynamicMetaObject(right, target.CombineRestrictions(args)));
        }