Property() public static method

Creates an IndexExpression representing the access to an indexed property.
public static Property ( Expression instance, PropertyInfo indexer ) : IndexExpression
instance Expression The object to which the property belongs. If the property is static/shared, it must be null.
indexer PropertyInfo The that represents the property to index.
return IndexExpression
Ejemplo n.º 1
0
        private static Expression <Func <T, bool> > PrimaryKeyEquals(PropertyInfo property, int value)
        {
            var param = Expression.Parameter(typeof(T));
            var body  = Expression.Equal(Expression.Property(param, property), Expression.Constant(value));

            return(Expression.Lambda <Func <T, bool> >(body, param));
        }
Ejemplo n.º 2
0
        public void TestWhereComparison()
        {
            // Partial LINQ expression (x => x.Number1)
            var parameter = LinqExpression.Parameter(typeof(NumbersModel), "x");
            var n1        = LinqExpression.Property(parameter, "Number1");

            var l3    = new Func <int, bool>(n => n < 3);
            var le3   = new Func <int, bool>(n => n <= 3);
            var g6    = new Func <int, bool>(n => n > 6);
            var ge6   = new Func <int, bool>(n => n >= 6);
            var e7    = new Func <int, bool>(n => n == 7);
            var ne7   = new Func <int, bool>(n => n != 7);
            var cases = new[] {
                Tuple.Create((LinqExpression)LinqExpression.LessThan(n1, LinqExpression.Constant(3)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)l3, parameter),
                Tuple.Create((LinqExpression)LinqExpression.LessThanOrEqual(n1, LinqExpression.Constant(3)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)le3, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThan(n1, LinqExpression.Constant(6)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)g6, parameter),
                Tuple.Create((LinqExpression)LinqExpression.GreaterThanOrEqual(n1, LinqExpression.Constant(6)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)ge6, parameter),
                Tuple.Create((LinqExpression)LinqExpression.Equal(n1, LinqExpression.Constant(7)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)e7, parameter),
                Tuple.Create((LinqExpression)LinqExpression.NotEqual(n1, LinqExpression.Constant(7)),
                             (Func <NumbersModel, object, bool>)TestWhereCompareValidator, (object)ne7, parameter)
            };

            LoadModelNumbers(10);
            Db.Count.Should().Be(10);
            RunTestWithNumbers(new[] { 2, 3, 4, 5, 1, 9 }, cases);
        }
        private void BuildWithSubquery()
        {
            var criteria       = (CriteriaImpl)MainQuery.UnderlyingCriteria;
            var session        = (SessionImpl)criteria.Session;
            var metaData       = session.SessionFactory.GetClassMetadata(typeof(TRoot));
            var idName         = metaData.IdentifierPropertyName; //TODO: multiple props
            var pe             = Expression.Parameter(typeof(TRoot));
            var idExprBody     = Expression.Property(pe, typeof(TRoot).GetProperty(idName));
            var expr           = Expression.Lambda(idExprBody, pe);
            var mainCloned     = MainQuery.Clone();
            var projectionList = new List <IProjection>();

            projectionList.Add(ExpressionProcessor.FindMemberProjection(expr.Body).AsProjection());
            mainCloned.UnderlyingCriteria.SetProjection(projectionList.ToArray());
            var tree = new QueryRelationTree();

            foreach (var pathExpr in Includes)
            {
                tree.AddNode(pathExpr);
            }
            foreach (var pair in tree.DeepFirstSearch())
            {
                var query = session.QueryOver <TRoot>();
                //Add a SubQuery
                query.And(Subqueries.PropertyIn(idName, ((QueryOver <TRoot, TRoot>)mainCloned).DetachedCriteria));
                CopyCriteriaValues(criteria, query);
                FillSubQuery(pair.Value, query, criteria);
                query.Future();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates two-way binding between a property in the target processor view model class and
        /// its represented property in the settings manager.
        /// </summary>
        /// <typeparam name="TParameter">The type of the property parameter.</typeparam>
        /// <typeparam name="TTargetClass">The type of the target class.</typeparam>
        /// <param name="targetClassName">The name of the target class.</param>
        /// <param name="targetPropertyName">The name of the property.</param>
        /// <param name="settingsManager">The calling instance of the SettingsManager class.</param>
        public static void BindSettingsProperty <TParameter, TTargetClass>(
            string targetClassName,
            string targetPropertyName,
            SettingsManager settingsManager)
        {
            var propertyInfo        = typeof(ViewModels.MainViewModel).GetProperty(targetClassName);
            var targetClassInstance = (TTargetClass)propertyInfo.GetGetMethod().Invoke(settingsManager.MainViewModelRef, null);

            ParameterExpression targetParameter   = LExpression.Parameter(typeof(SettingsManager), "x");
            MemberExpression    mainVMRefExp      = LExpression.Property(targetParameter, "MainViewModelRef");
            MemberExpression    viewModelExp      = LExpression.Property(mainVMRefExp, targetClassName);
            MemberExpression    targetPropertyExp = LExpression.Property(viewModelExp, targetPropertyName);
            Expression <Func <SettingsManager, TParameter> > targetExp = LExpression.Lambda <Func <SettingsManager, TParameter> >(targetPropertyExp, new ParameterExpression[] { targetParameter });

            Action <SettingsManager, TParameter> targetSetterAction = CreateSetterByName <SettingsManager, TParameter>(targetPropertyName);

            settingsManager.DisposeCollection.Add(
                settingsManager.WhenAnyValue(targetExp)
                .Where(_ => !settingsManager.IsLoading)
                .Subscribe(delegate(TParameter x)
            {
                targetSetterAction(settingsManager, x);
            }));

            MemberExpression settingsPropertyExp = LExpression.Property(targetParameter, targetPropertyName);
            Expression <Func <SettingsManager, TParameter> > settingsExp = LExpression.Lambda <Func <SettingsManager, TParameter> >(settingsPropertyExp, new ParameterExpression[] { targetParameter });
            Action <TTargetClass, TParameter> settingsSetterAction       = CreateSetterByName <TTargetClass, TParameter>(targetPropertyName);

            settingsManager.DisposeCollection.Add(
                settingsManager.WhenAnyValue(settingsExp)
                .Subscribe(delegate(TParameter x)
            {
                settingsSetterAction(targetClassInstance, x);
            }));
        }
Ejemplo n.º 5
0
        public static Expression Count(Expression arg)
        {
            CheckIsEnumerable(arg);
            var count = arg.Type.GetProperty("Count");

            return(new Expression(LinqExpression.Property(arg, count)));
        }
Ejemplo n.º 6
0
        public static Expression Call(ProcedureCall call)
        {
            if (ReferenceEquals(call, null))
            {
                throw new ArgumentNullException(nameof(call));
            }
            var services  = Services.Instance;
            var procedure = services.GetProcedureSignature(call);

            if (!procedure.HasReturnType)
            {
                throw new InvalidOperationException(
                          "Cannot use a procedure that does not return a value.");
            }
            var arguments = services.GetArguments(procedure, call.Arguments);

            var servicesExpr      = LinqExpression.Constant(services);
            var executeCallMethod = typeof(Services).GetMethod(
                "ExecuteCall", new[] { typeof(Scanner.ProcedureSignature), typeof(object[]) });
            var procedureExpr = LinqExpression.Constant(procedure);
            var argumentsExpr = LinqExpression.Constant(arguments);

            var result = LinqExpression.Call(
                servicesExpr, executeCallMethod,
                new[] { procedureExpr, argumentsExpr });
            var value = LinqExpression.Convert(
                LinqExpression.Property(result, "Value"), procedure.ReturnType);

            return(new Expression(value));
        }
Ejemplo n.º 7
0
        private LambdaExpression toDictLambda(Type from, Type to)
        {
            var valueType = recordCreator.GetValueType(to);
            var recType   = typeof(IRecord <>).MakeGenericType(valueType);
            var set       = recType.GetTypeInfo().GetDeclaredMethod(nameof(IRecord <object> .SetValue));

            var input      = Ex.Parameter(from, "input");
            var tmp        = Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(valueType), "tmp");
            var res        = Ex.Parameter(typeof(IDictionary <,>).MakeGenericType(typeof(string), valueType), "res");
            var rec        = Ex.Parameter(recType, "rec");
            var getters    = GetReadablePropertiesForType(from);
            var converters = getters.Select(g => Ref.GetLambda(g.PropertyType, valueType));

            var end   = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to));
            var block = Ex.Block(new[] { tmp, res, rec },
                                 Ex.Assign(res, Ex.New(GetParameterlessConstructor(to))),
                                 Ex.Assign(rec, recordCreator.Creator(to).ApplyTo(res)),
                                 Ex.IfThen(Ex.MakeBinary(ExpressionType.Equal, rec, Ex.Default(rec.Type)), Ex.Goto(end, NoResult(to))),
                                 Ex.Block(getters.Zip(converters, (g, c) => new { g, c })
                                          .Select(x =>
                                                  Ex.Block(
                                                      Ex.Assign(tmp, x.c.ApplyTo(Ex.Property(input, x.g))),
                                                      Ex.IfThenElse(Ex.Property(tmp, nameof(IConversionResult.IsSuccessful)),
                                                                    Ex.Call(rec, set, Ex.Constant(x.g.Name), Ex.Property(tmp, nameof(IConversionResult.Result))),
                                                                    Ex.Goto(end, NoResult(to)))))),
                                 Ex.Label(end, Result(to, Ex.Convert(res, to))));

            return(Ex.Lambda(block, input));
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Create a lambda to receive a property value
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        private Delegate CreateValueGetter(PropertyInfo property)
        {
            ParameterExpression parameter = Expression.Parameter(GetType(), "i");
            UnaryExpression     cast      = Expression.TypeAs(Expression.Property(parameter, property), typeof(object));

            return(Expression.Lambda(cast, parameter).Compile());
        }
Ejemplo n.º 9
0
        public static IQueryable <TEntity> EagerFetchAll <TEntity>(this IQueryable <TEntity> query)
        {
            // hack the session reference out of the provider - or is
            // there a better way to do this?
            //IStatelessSession session = (IStatelessSession)query.Provider.GetType().GetProperty("Session").GetValue(query.Provider);

            //ISession session = (ISession)query.Provider.GetType()
            //                             .GetProperty("Session", System.Reflection.BindingFlags.Instance
            //                                                   | System.Reflection.BindingFlags.NonPublic)
            //                             .GetValue(query.Provider);

            var            entityType     = typeof(TEntity);
            var            sessionFactory = Ioc.Create <ISessionFactory>();
            IClassMetadata metaData       = sessionFactory.GetClassMetadata(entityType);

            for (int i = 0; i < metaData.PropertyNames.Length; i++)
            {
                global::NHibernate.Type.IType propType = metaData.PropertyTypes[i];

                // get eagerly mapped associations to other entities
                if (propType.IsAssociationType && !metaData.PropertyLaziness[i])
                {
                    ParameterExpression par = Expression.Parameter(entityType, "p");

                    Expression propExp = Expression.Property(par, metaData.PropertyNames[i]);



                    Type             relatedType = null;
                    LambdaExpression lambdaExp;
                    string           methodName;
                    if (propType.ReturnedClass.IsGenericCollection())
                    {
                        relatedType = propType.ReturnedClass.GetGenericArguments()[0];
                        var funcType = typeof(Func <,>).MakeGenericType(entityType, typeof(IEnumerable <>).MakeGenericType(relatedType));
                        lambdaExp  = Expression.Lambda(funcType, propExp, par);
                        methodName = "FetchMany";
                    }
                    else
                    {
                        relatedType = propType.ReturnedClass;
                        lambdaExp   = Expression.Lambda(propExp, par);
                        methodName  = "Fetch";
                    }

                    var        fetchManyMethodImpl = typeof(EagerFetchingExtensionMethods).GetMethod(methodName).MakeGenericMethod(entityType, relatedType);
                    Expression callExpr            = Expression.Call(null,
                                                                     fetchManyMethodImpl,
                                                                     // first parameter is the query, second is property access expression
                                                                     query.Expression, lambdaExp
                                                                     );

                    LambdaExpression expr             = Expression.Lambda(callExpr, par);
                    Type             fetchGenericType = typeof(NhFetchRequest <,>).MakeGenericType(entityType, propType.ReturnedClass);
                    query = (IQueryable <TEntity>)Activator.CreateInstance(fetchGenericType, query.Provider, callExpr);
                }
            }

            return(query);
        }
Ejemplo n.º 10
0
        // Pseudocode:
        //string input =>
        //{
        //    R result = 0;
        //    for (int i = input.Length - 1; i >= 0; i--)
        //    {
        //        result <<= 6;
        //        var m = _invMap[input[i]];
        //        if (m == 0xff)
        //            return default(ConversionResult<R>);
        //        result += m;
        //    }
        //    return new ConversionResult<R>(result);
        //}
        private LambdaExpression fromLambda(Type to)
        {
            var stringthis = typeof(string).GetTypeInfo().DeclaredProperties.First(p => p.GetIndexParameters().Length == 1 && p.GetIndexParameters()[0].ParameterType == typeof(int));
            var input      = Ex.Parameter(typeof(string), "input");
            var result     = Ex.Parameter(to, "result");
            var i          = Ex.Parameter(typeof(int), "i");
            var m          = Ex.Parameter(typeof(byte), "m");
            var loopstart  = Ex.Label("loopstart");
            var end        = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end");
            var loop       = Ex.Block(
                Ex.Label(loopstart),
                Ex.IfThen(Ex.MakeBinary(ExpressionType.LessThan, i, Ex.Constant(0)),
                          Ex.Goto(end, Result(to, result))),
                Ex.LeftShiftAssign(result, Ex.Constant(6)),
                Ex.Assign(m, Ex.ArrayIndex(Ex.Constant(_invMap), Ex.Convert(Ex.MakeIndex(input, stringthis, new[] { i }), typeof(int)))),
                Ex.IfThen(Ex.MakeBinary(ExpressionType.Equal, m, Ex.Constant((byte)0xff)),
                          Ex.Goto(end, NoResult(to))),
                Ex.AddAssign(result, Ex.Convert(m, result.Type)),
                Ex.PostDecrementAssign(i),
                Ex.Goto(loopstart));
            var block = Ex.Block(new[] { result, i, m },
                                 Ex.Assign(result, Ex.Convert(Ex.Constant(0), to)),
                                 Ex.Assign(i, Ex.MakeBinary(ExpressionType.Subtract, Ex.Property(input, nameof(string.Length)), Ex.Constant(1))),
                                 loop,
                                 Ex.Label(end, NoResult(to)));

            return(Ex.Lambda(block, input));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Filters a sequence of values based on a fulltext search predicate
        /// </summary>
        /// <typeparam name="T">Any type</typeparam>
        /// <param name="source">The source - some IQueryable object.</param>
        /// <param name="text">The text - meaning of the search</param>
        /// <param name="options">The options for full-text search</param>
        /// <returns></returns>
        public static IQueryable <T> FullTextSearchQuery <T>(this IQueryable <T> source, string text, FullTextSearchOptions options = null)
        {
            var pe            = Exp.Parameter(typeof(T), "d");
            var predicateBody = CreateSubExpression(pe, typeof(T), text, options, isQueriable: true);

            if (predicateBody != null)
            {
                var whereExp = Exp.Lambda <Func <T, bool> >(predicateBody, new ParameterExpression[] { pe });
                source = source.Where(whereExp);
            }

            //Order by Expression
            if (options == null)
            {
                return(source);
            }

            var orderByProperty = options.OrderBy;

            if (string.IsNullOrEmpty(orderByProperty))
            {
                orderByProperty = typeof(T).GetProperties().First().Name;
            }

            var property   = Exp.Property(pe, orderByProperty);
            var lambda     = Exp.Lambda(property, pe);
            var method     = options.IsDescendingOrder ? "OrderByDescending" : "OrderBy";
            var orderByExp = Exp.Call(typeof(Queryable), method, new[] { typeof(T), property.Type }, source.Expression, lambda);

            source = source.Provider.CreateQuery <T>(orderByExp) as IOrderedQueryable <T>;
            return(source);
        }
        private LambdaExpression fromEnumerableLambda(Type from)
        {
            var input = Ex.Parameter(from, "input");
            var eType = from.GetTypeInfo().ImplementedInterfaces
                        .Where(i => i.GenericTypeArguments.Length == 1 && i.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                        .Select(i => i.GenericTypeArguments[0]).SingleOrDefault()
                        ?? from.GetTypeInfo().GenericTypeArguments[0];
            var res    = Ex.Parameter(typeof(string), "res");
            var result = Ex.Block(new[] { res },
                                  Ex.Assign(res, Ex.Call((from mi in typeof(string).GetTypeInfo().GetDeclaredMethods(nameof(string.Join))
                                                          where mi.GetGenericArguments().Length == 1
                                                          let par = mi.GetParameters()
                                                                    where par.Length == 2 &&
                                                                    par[0].ParameterType == typeof(string) &&
                                                                    par[1].ParameterType == typeof(IEnumerable <>).MakeGenericType(mi.GetGenericArguments()[0])
                                                                    select mi).Single().MakeGenericMethod(eType),
                                                         Ex.Constant(Separators[0].ToString()), input)),
                                  Ex.Condition(Ex.MakeBinary(Et.Equal, Ex.Property(res, nameof(string.Length)), Ex.Constant(0)),
                                               NoResult(typeof(string)),
                                               Result(typeof(string), res)));

            var block = Ex.Condition(Ex.MakeBinary(Et.Equal, input, Ex.Default(from)),
                                     NoResult(typeof(string)),
                                     result);
            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
Ejemplo n.º 13
0
        internal static IQueryable <T> ApplyMethod <T>(this IQueryable <T> source, string property, string methodName)
        {
            string[]            props = property.Split('.');
            Type                type  = typeof(T);
            ParameterExpression arg   = Expression.Parameter(type, "x");
            Expression          expr  = arg;

            foreach (string prop in props)
            {
                // use reflection (not ComponentModel) to mirror LINQ
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }

            Type             delegateType = typeof(Func <,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda       = Expression.Lambda(delegateType, expr, arg);

            object result = typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName &&
                method.IsGenericMethodDefinition &&
                method.GetGenericArguments().Length == 2 &&
                method.GetParameters().Length == 2)
                            .MakeGenericMethod(typeof(T), type)
                            .Invoke(null, new object[] { source, lambda });

            return((IOrderedQueryable <T>)result);
        }
Ejemplo n.º 14
0
        internal bool AddSplattedArgumentTest(object value, Expression /*!*/ expression, out int listLength, out ParameterExpression /*!*/ listVariable)
        {
            if (value == null)
            {
                AddRestriction(Ast.Equal(expression, Ast.Constant(null)));
            }
            else
            {
                // test exact type:
                AddTypeRestriction(value.GetType(), expression);

                List <object> list = value as List <object>;
                if (list != null)
                {
                    Type type = typeof(List <object>);
                    listLength   = list.Count;
                    listVariable = GetTemporary(type, "#list");
                    AddCondition(Ast.Equal(
                                     Ast.Property(Ast.Assign(listVariable, Ast.Convert(expression, type)), type.GetProperty("Count")),
                                     Ast.Constant(list.Count))
                                 );
                    return(true);
                }
            }

            listLength   = -1;
            listVariable = null;
            return(false);
        }
        public LambdaExpression CreateLambda(Type from, Type to)
        {
            var toParameters = to.GetTypeInfo().GenericTypeArguments;
            var tupa         = toParameters.Length;
            var input        = Ex.Parameter(from, "input");
            var converters   = toParameters.Select(p => Ref.GetLambda(typeof(string), p)).ToArray();
            var res          = toParameters.Select(p => Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(p))).ToArray();
            var end          = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end");
            var indexer      = typeof(string[]).GetTypeInfo().GetDeclaredProperty("Item");

            var split      = Ex.Parameter(typeof(string[]), "split");
            var conversion = Ex.Block(converters.Select((c, i) =>
                                                        Ex.Block(
                                                            Ex.Assign(res[i],
                                                                      c.ApplyTo(Ex.MakeIndex(split, indexer, new[] { Ex.MakeBinary(Et.Add, Ex.Constant(i), Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))) }))),
                                                            Ex.IfThen(Ex.Not(Ex.Property(res[i], nameof(IConversionResult.IsSuccessful))),
                                                                      Ex.Goto(end, NoResult(to))))));
            var block = Ex.Block(new[] { split },
                                 Ex.Assign(split, Ex.Call(input, nameof(string.Split), Type.EmptyTypes, _separator)),
                                 Ex.Condition(Ex.MakeBinary(Et.LessThan, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa)),
                                              NoResult(to),
                                              Ex.Block(res,
                                                       Ex.IfThen(Ex.MakeBinary(Et.GreaterThan, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa)),
                                                                 Ex.Assign(Ex.ArrayAccess(split, Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))),
                                                                           Ex.Call(typeof(string), nameof(string.Join), Type.EmptyTypes, _separatorString,
                                                                                   Ex.Call(typeof(Enumerable), nameof(Enumerable.Take), new[] { typeof(string) }, split,
                                                                                           Ex.MakeBinary(Et.Add, Ex.Constant(1), Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))))))),
                                                       conversion,
                                                       Ex.Label(end, Result(to, Ex.Call(Creator(to), res.Select(r => Ex.Property(r, nameof(IConversionResult.Result)))))))));
            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
Ejemplo n.º 16
0
        private static Func <int[], int[]> GenerateCopyExpression()
        {
            var ctor = typeof(int[]).GetConstructor(new[] { typeof(int) });
            var get  = typeof(int[]).GetMethod("Get", new[] { typeof(int) });
            var set  = typeof(int[]).GetMethod("Set", new[] { typeof(int), typeof(int) });

            var p1     = Exp.Parameter(typeof(int[]));
            var v1     = Exp.Variable(typeof(int[]));
            var v2     = Exp.Variable(typeof(int));
            var @break = Exp.Label();

            var block = Exp.Block(
                new[] { v1, v2 },
                Exp.Assign(v1, Exp.New(ctor, Exp.Property(p1, "Length"))),
                Exp.Assign(v2, Exp.Constant(0)),
                Exp.Loop(
                    Exp.IfThenElse(
                        Exp.LessThan(v2, Exp.Property(p1, "Length")),
                        Exp.Block(
                            Exp.Call(v1, set, v2, Exp.Call(p1, get, v2)),
                            Exp.AddAssign(v2, Exp.Constant(1))
                            ),
                        Exp.Break(@break)
                        ),
                    @break),
                v1
                );

            return(Exp.Lambda <Func <int[], int[]> >(block, new ParameterExpression[] { p1 }).Compile());
        }
Ejemplo n.º 17
0
        static GlyphRunFormatter()
        {
            var refType = typeof(CharacterBufferReference);

            _textFormattingMode = typeof(GlyphRun).GetField("_textFormattingMode", BindingFlags.NonPublic | BindingFlags.Instance);

            {
                var property = refType.GetProperty("CharacterBuffer", BindingFlags.NonPublic | BindingFlags.Instance);
                var param0   = Expr.Parameter(refType);
                var expr     = Expr.Convert(Expr.Property(param0, property), typeof(IList <char>));
                var lambda   = Expr.Lambda <Func <CharacterBufferReference, IList <char> > >(expr, param0);
                getCharBuf = lambda.Compile();
            }

            {
                var property = refType.GetProperty("OffsetToFirstChar", BindingFlags.NonPublic | BindingFlags.Instance);
                var param0   = Expr.Parameter(refType);
                var expr     = Expr.Property(param0, property);
                var lambda   = Expr.Lambda <Func <CharacterBufferReference, int> >(expr, param0);
                getCharOffset = lambda.Compile();
            }

            {
                var ctor   = typeof(TextBounds).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
                var param0 = Expr.Parameter(typeof(Rect));
                var expr   = Expr.New(ctor, param0, Expr.Constant(FlowDirection.LeftToRight), Expr.Constant(null, typeof(IList <TextRunBounds>)));
                var lambda = Expr.Lambda <Func <Rect, TextBounds> >(expr, param0);
                makeBounds = lambda.Compile();
            }
        }
Ejemplo n.º 18
0
 static Expression GetArgument(Expression Expression, int n)
 {
     if (Expression.Type == typeof(LuaArguments))
         return Expression.Property(Expression, "Item", Expression.Constant(n));
     else
         return Expression.ArrayAccess(Expression, Expression.Constant(n));
 }
Ejemplo n.º 19
0
        private IQueryOver <Document, TIndex> BindQueryOverByPath <TIndex>(string name)
        {
            IQueryOver <Document> queryOver;

            if (_joins.TryGetValue(name, out queryOver))
            {
                return((IQueryOver <Document, TIndex>)queryOver);
            }

            // public IList<{TIndex}> {TIndex} {get;set;}
            var dynamicMethod     = new DynamicMethod(typeof(TIndex).Name, typeof(IEnumerable <TIndex>), null, typeof(Document));
            var syntheticMethod   = new SyntheticMethodInfo(dynamicMethod, typeof(Document));
            var syntheticProperty = new SyntheticPropertyInfo(syntheticMethod);

            // doc => doc.{TIndex}
            var parameter           = Expression.Parameter(typeof(Document), "doc");
            var syntheticExpression = (Expression <Func <Document, IEnumerable <TIndex> > >)Expression.Lambda(
                typeof(Func <Document, IEnumerable <TIndex> >),
                Expression.Property(parameter, syntheticProperty),
                parameter);

            TIndex alias = default(TIndex);

            var join = BindDocument().JoinQueryOver(syntheticExpression, () => alias);

            _joins.Add(name, join);

            return(join);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Implements Class#new feature.
        /// </summary>
        public void BuildObjectConstruction(MetaObjectBuilder /*!*/ metaBuilder, CallArguments /*!*/ args, string /*!*/ methodName)
        {
            Debug.Assert(!IsSingletonClass, "Cannot instantiate singletons");

            Type type = GetUnderlyingSystemType();

            RubyMemberInfo initializer           = ResolveMethod(Symbols.Initialize, true).InvalidateSitesOnOverride();
            RubyMethodInfo overriddenInitializer = initializer as RubyMethodInfo;

            // check the version of this class to ensure the initializer won't be changed without rebuilding the site:
            metaBuilder.AddCondition(
                Ast.Equal(Ast.Property(Ast.Constant(this), RubyModule.VersionProperty), Ast.Constant(this.Version))
                );

            // Initializer is overridden => initializer is invoked on an uninitialized instance.
            // Is user class (defined in Ruby code) => construct it as if it had initializer that calls super immediately
            // (we need to "inherit" factories/constructors from the base class (e.g. class S < String; self; end.new('foo')).
            if (overriddenInitializer != null || (_isRubyClass && _structInfo == null))
            {
                metaBuilder.Result = MakeAllocatorCall(args, () => Ast.Constant(Name));

                if (overriddenInitializer != null || (_isRubyClass && initializer != null && !initializer.IsEmpty))
                {
                    BuildOverriddenInitializerCall(metaBuilder, args, initializer);
                }
            }
            else if (type.IsSubclassOf(typeof(Delegate)))
            {
                metaBuilder.Result = MakeDelegateConstructorCall(type, args);
            }
            else
            {
                MethodBase[] constructionOverloads;

                bool includeSelf;
                if (_structInfo != null)
                {
                    constructionOverloads = new MethodBase[] { Methods.CreateStructInstance };
                    includeSelf           = true;
                }
                else if (_factories != null)
                {
                    constructionOverloads = (MethodBase[])ReflectionUtils.GetMethodInfos(_factories);
                    includeSelf           = true;
                }
                else
                {
                    constructionOverloads = type.GetConstructors();
                    if (constructionOverloads.Length == 0)
                    {
                        throw RubyExceptions.CreateTypeError(String.Format("allocator undefined for {0}", Name));
                    }
                    includeSelf = false;
                }

                RubyMethodGroupInfo.BuildCallNoFlow(metaBuilder, args, methodName, constructionOverloads, includeSelf, false);
                RubyMethodGroupInfo.ApplyBlockFlowHandlingInternal(metaBuilder, args);
            }
        }
Ejemplo n.º 21
0
        private static Expression <Func <T, object> > ToLambda <T>(string propertyName)
        {
            var parameter    = Expression.Parameter(typeof(T));
            var property     = Expression.Property(parameter, propertyName);
            var propAsObject = Expression.Convert(property, typeof(object));

            return(Expression.Lambda <Func <T, object> >(propAsObject, parameter));
        }
Ejemplo n.º 22
0
        public void MemberAccess_property_expression()
        {
            var expression =
                LinqExpression.Property(
                    LinqExpression.Parameter(typeof(SampleClass)),
                    nameof(SampleClass.InstanceProperty));

            ShouldRoundrip(expression);
        }
 private static Ex conditional(Type from, Ex input, Ex result)
 {
     return(Ex.Condition(
                Ex.MakeBinary(Et.OrElse,
                              Ex.MakeBinary(Et.Equal, input, Ex.Default(from)),
                              Ex.MakeBinary(Et.Equal, Ex.Property(input, nameof(Array.Length)), Ex.Constant(0))),
                NoResult(typeof(string)),
                Result(typeof(string), result)));
 }
Ejemplo n.º 24
0
        public void MemberAccess_property_type()
        {
            var expression =
                LinqExpression.Property(
                    null,
                    typeof(SampleClass),
                    nameof(SampleClass.StaticProperty));

            ShouldRoundrip(expression);
        }
Ejemplo n.º 25
0
        public void MemberAccess_property_expression_arguments()
        {
            var expression =
                LinqExpression.Property(
                    LinqExpression.Parameter(typeof(SampleClass)),
                    "Indexer",
                    LinqExpression.Parameter(typeof(int)));

            ShouldRoundrip(expression);
        }
Ejemplo n.º 26
0
        /// <summary>Generate a specific property getter for a specific type</summary>
        /// <typeparam name="T">The type which contains the member</typeparam>
        /// <typeparam name="TResult">The static member's actual type</typeparam>
        /// <param name="memberName">The member's name as defined in <typeparamref name="T"/></param>
        /// <returns>A compiled lambda which can access (get) the static member</returns>
        /// <remarks>Generates a method similar to this:
        /// <code>
        /// TResult GetMethod()
        /// {
        ///     return T.memberName;
        /// }
        /// </code>
        /// </remarks>
        public static Func <TResult> GenerateStaticPropertyGetter <T, TResult>(string memberName)
        {
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(memberName));
            Contract.Ensures(Contract.Result <Func <TResult> >() != null);

            var member = Expr.Property(null, typeof(T), memberName);                    // basically 'T.memberName'
            var lambda = Expr.Lambda <Func <TResult> >(member);

            return(lambda.Compile());
        }
Ejemplo n.º 27
0
        public static Expression SelectProperty(Type type, string property)
        {
            var returnType         = GetPropertyType(type, property);
            var funcType           = typeof(Func <,>).MakeGenericType(type, returnType);
            var param              = Expression.Parameter(type, "i");
            var propertyExpression = Expression.Property(param, property);

            var expressionFactory = CreateExpressionFactory(funcType);

            return(expressionFactory.Invoke(null, new object[] { propertyExpression, new[] { param } }) as Expression);
        }
Ejemplo n.º 28
0
            private static (SystemExpression, UnaryExpression) GetBodyExpressions(ParameterExpression parameter, string propertyName, object value)
            {
                var documentType = typeof(TQueryable);

                if (propertyName.Contains("."))
                {
                    var propertyType = documentType;

                    var propertyNames = propertyName.Split('.');

                    SystemExpression bodyLeft = parameter;

                    foreach (var property in propertyNames)
                    {
                        var propertyInfo = propertyType.GetProperty(property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);

                        if (propertyInfo == null)
                        {
                            throw new ArgumentOutOfRangeException(nameof(propertyInfo), propertyName);
                        }

                        propertyType = propertyInfo.PropertyType;

                        bodyLeft = SystemExpression.Property(bodyLeft, property);
                    }

                    var bodyRight =
                        SystemExpression.Convert(
                            SystemExpression.Constant(GetConstantValue(value, bodyLeft.Type)),
                            bodyLeft.Type
                            );

                    return(bodyLeft, bodyRight);
                }
                else
                {
                    var propertyInfo = documentType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);

                    if (propertyInfo == null)
                    {
                        throw new ArgumentOutOfRangeException(nameof(propertyName), propertyName);
                    }

                    var bodyLeft = SystemExpression.MakeMemberAccess(parameter, propertyInfo);

                    var bodyRight =
                        SystemExpression.Convert(
                            SystemExpression.Constant(GetConstantValue(value, propertyInfo.PropertyType)),
                            propertyInfo.PropertyType
                            );

                    return(bodyLeft, bodyRight);
                }
            }
Ejemplo n.º 29
0
 public TExGCX(Expression ex_) : base(ex_)
 {
     fs       = Ex.Field(ex, "fs");
     v2s      = Ex.Field(ex, "v2s");
     v3s      = Ex.Field(ex, "v3s");
     rv2s     = Ex.Field(ex, "rv2s");
     index    = Ex.Field(ex, "index");
     i_float  = Ex.Field(ex, "i").As <float>();
     pi_float = Ex.Field(ex, "pi").As <float>();
     beh_loc  = Ex.Property(ex, "Loc");
     bpi      = Ex.Property(ex, "AsBPI");
 }
Ejemplo n.º 30
0
 private static Ex enumeratorConversion(Type to, Ex enumerator, Type eType, LambdaExpression[] converters, Ex[] res, System.Linq.Expressions.LabelTarget end)
 {
     return(Ex.Block(res.Zip(converters, (r, con) =>
                             Ex.Block(
                                 Ex.IfThenElse(
                                     enumerator.Type.GetTypeInfo().GetDeclaredMethod(nameof(IEnumerator.MoveNext)) == null
                         ? Ex.Call(Ex.Convert(enumerator, typeof(IEnumerator)), nameof(IEnumerator.MoveNext), Type.EmptyTypes)
                         : Ex.Call(enumerator, enumerator.Type.GetTypeInfo().GetDeclaredMethod(nameof(IEnumerator.MoveNext))),
                                     Ex.Assign(r, con.ApplyTo(Ex.Property(enumerator, nameof(IEnumerator.Current)))),
                                     Ex.Goto(end, NoResult(to))),
                                 Ex.IfThen(Ex.Not(Ex.Property(r, nameof(IConversionResult.IsSuccessful))),
                                           Ex.Goto(end, NoResult(to)))))));
 }
Ejemplo n.º 31
0
        static Func <TextSelection, object> GenerateGetTextViewAction()
        {
            ParameterExpression textSelectionArgument = Expression.Parameter(typeof(TextSelection), nameof(textSelectionArgument));
            MemberExpression    body = Expression.Property(textSelectionArgument, "TextView");

            var lambda = Expression.Lambda <Func <TextSelection, object> >(
                body: body,
                parameters: new[] { textSelectionArgument }
                );


            return(lambda.Compile());
        }