/// <summary>Resolve enumerable parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameterEnumerable(ExpressionScope scope, IDictionary <string, Type> parameterTypes)
        {
            var parameters = new List <ParameterExpression>();

            var parameterEnumerable = scope.CreateParameter(typeof(IEnumerable));

            parameters.Add(parameterEnumerable);

            var dictParameter     = scope.CreateVariable(typeof(Dictionary <string, object>));
            var methodConvert     = typeof(EvalCompiler).GetMethod("ResolveToParameterDictionary", BindingFlags.NonPublic | BindingFlags.Static);
            var expressionConvert = Expression.Call(methodConvert, new Expression[] { parameterEnumerable });
            var expressionAssign  = Expression.Assign(dictParameter, expressionConvert);

            scope.Expressions.Add(expressionAssign);

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new Lazy <Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    Expression innerExpression = Expression.Property(dictParameter, DictionaryItemPropertyInfo, Expression.Constant(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                                      Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                                      Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return(innerParameter);
                }));
            }

            return(parameters);
        }
        /// <summary>Resolve single object parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List<ParameterExpression> ResolveParameterSingleObject(ExpressionScope scope, IDictionary<string, Type> parameterTypes)
        {
            var parameters = new List<ParameterExpression>();

            var parameterExpression = scope.CreateParameter(typeof (object));
            parameters.Add(parameterExpression);

            var parameterObjectType = parameterTypes["{0}"];
            var parameterObject = scope.CreateVariable(parameterObjectType, "{0}");
            scope.Expressions.Add(Expression.Assign(parameterObject, Expression.Convert(parameterExpression, parameterObjectType)));

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new Lazy<Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    var property = parameterObjectType.GetProperty(parameter.Key);

                    Expression innerExpression = property != null ?
                        Expression.Property(parameterObject, property) :
                        Expression.Field(parameterObject, parameterObjectType.GetField(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                        Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                        Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return innerParameter;
                }));
            }

            return parameters;
        }
Ejemplo n.º 3
0
        public IEnumerable <EvaluationResult> Evaluate(IEnumerable <string> expressions, JObject source, CultureInfo culture = null)
        {
            var sourcePayload = source ?? new JObject();
            var sourceName    = "inp";
            var sources       = new List <EvaluationSource>()
            {
                new EvaluationSource()
                {
                    Name = sourceName, Cell = "N3", Payload = sourcePayload
                }
            };
            var results = new List <EvaluationResult>();
            var scope   = new ExpressionScope(culture == null ? outputLang : Language.Create(culture), sources);
            var helper  = new JsonExpressionHelper();
            var index   = 1;

            foreach (var expression in expressions)
            {
                var exprName = $"__A{index}";
                var cell     = exprName;
                var tokens   = helper.Parse(sourcePayload, expression);
                var result   = Evaluate(exprName, cell, tokens, scope, null);
                result.Value = helper.TranslateResult(result.Value);
                results.Add(result);
                ++index;
            }
            return(results);
        }
        private static ExpressionNode ParseAgainstModel(string originalExpression, string expression, SuperSimpleTemplateParserScope scope, ExpressionScope expressionScope)
        {
            var subModelIndex = expression.IndexOf('.');
            if (subModelIndex >= 0)
            {
                var subModel = ParseAgainstModel(originalExpression, expression.Substring(0, subModelIndex), scope, expressionScope);
                return SyntaxTreeExpression.SubModel(
                    subModel,
                    ParseAgainstModel(originalExpression, expression.Substring(subModelIndex + 1), new SuperSimpleTemplateParserScope { Block = scope.Block, ModelType = subModel.ResultType }, ExpressionScope.CurrentModelOnStack)
                );
            }

            var propertyInfo = scope.ModelType.GetProperty(expression);
            if (propertyInfo != null) return SyntaxTreeExpression.Property(scope.ModelType, expression, expressionScope);

            var fieldInfo = scope.ModelType.GetField(expression);
            if (fieldInfo != null) return SyntaxTreeExpression.Field(scope.ModelType, expression, expressionScope);

            if (IsLateBoundAcceptingType(scope.ModelType)) return SyntaxTreeExpression.LateBound(expression, true, expressionScope);

            if (expression.StartsWith("Has"))
            {
                var collectionExpression = ParseAgainstModel(originalExpression, expression.Substring(3), scope, expressionScope);
                return SyntaxTreeExpression.HasItems(collectionExpression);
            }

            throw new VeilParserException(String.Format("Unable to parse model expression '{0}'", originalExpression));
        }
        private static ExpressionNode ParseAgainstModel(Type modelType, string expression, ExpressionScope expressionScope)
        {
            var dotIndex = expression.IndexOf('.');
            if (dotIndex >= 0)
            {
                var subModel = HandlebarsExpressionParser.ParseAgainstModel(modelType, expression.Substring(0, dotIndex), expressionScope);
                return SyntaxTreeExpression.SubModel(
                    subModel,
                    HandlebarsExpressionParser.ParseAgainstModel(subModel.ResultType, expression.Substring(dotIndex + 1), ExpressionScope.CurrentModelOnStack)
                );
            }

            if (expression.EndsWith("()"))
            {
                var func = FindMember(modelType, expression.Substring(0, expression.Length - 2), MemberTypes.Method);
                if (func != null) return SyntaxTreeExpression.Function(modelType, func.Name, expressionScope);
            }

            var prop = FindMember(modelType, expression, MemberTypes.Property | MemberTypes.Field);
            if (prop != null)
            {
                switch (prop.MemberType)
                {
                    case MemberTypes.Property: return SyntaxTreeExpression.Property(modelType, prop.Name, expressionScope);
                    case MemberTypes.Field: return SyntaxTreeExpression.Field(modelType, prop.Name, expressionScope);
                }
            }

            if (IsLateBoundAcceptingType(modelType)) return SyntaxTreeExpression.LateBound(expression, false, expressionScope);

            throw new VeilParserException(String.Format("Unable to parse model expression '{0}' againt model '{1}'", expression, modelType.Name));
        }
        /// <summary>Resolve dictionary parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameterDictionary(ExpressionScope scope, IDictionary <string, Type> parameterTypes)
        {
            var parameters = new List <ParameterExpression>();

            var parameterDictionary = scope.CreateParameter(typeof(IDictionary));

            parameters.Add(parameterDictionary);

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new Lazy <Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    Expression innerExpression = Expression.Property(parameterDictionary, DictionaryItemPropertyInfo, Expression.Constant(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                                      Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                                      Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return(innerParameter);
                }));
            }

            return(parameters);
        }
        /// <summary>Resolve enumerable parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List<ParameterExpression> ResolveParameterEnumerable(ExpressionScope scope, IDictionary<string, Type> parameterTypes)
        {
            var parameters = new List<ParameterExpression>();

            var parameterEnumerable = scope.CreateParameter(typeof (IEnumerable));
            parameters.Add(parameterEnumerable);

            var dictParameter = scope.CreateVariable(typeof (Dictionary<string, object>));
            var methodConvert = typeof (EvalCompiler).GetMethod("ResolveToParameterDictionary", BindingFlags.NonPublic | BindingFlags.Static);
            var expressionConvert = Expression.Call(methodConvert, new Expression[] {parameterEnumerable});
            var expressionAssign = Expression.Assign(dictParameter, expressionConvert);
            scope.Expressions.Add(expressionAssign);

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new LazySingleThread<Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    Expression innerExpression = Expression.Property(dictParameter, DictionaryItemPropertyInfo, Expression.Constant(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                        Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                        Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return innerParameter;
                }));
            }

            return parameters;
        }
        /// <summary>Resolve untyped parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List<ParameterExpression> ResolveParameterUntyped(ExpressionScope scope, IDictionary<string, Type> parameterTypes, bool forceFirstParameterProperty = false)
        {
            var parameters = new List<ParameterExpression>();

            foreach (var parameter in parameterTypes)
            {
                var parameterExpression = scope.CreateParameter(typeof (object));
                parameters.Add(parameterExpression);

                scope.CreateLazyVariable(parameter.Key, new Lazy<Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    var innerExpression = parameterExpression.Type != parameter.Value ?
                        Expression.Assign(innerParameter, Expression.Convert(parameterExpression, parameter.Value)) :
                        Expression.Assign(innerParameter, parameterExpression);

                    scope.Expressions.Insert(0, innerExpression);

                    return innerParameter;
                }));
            }

            if (parameterTypes.Count == 1 || (parameterTypes.Count > 0 && forceFirstParameterProperty))
            {
                var keyValue = parameterTypes.First();
                if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object)
                {
                    ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value);
                }
            }

            return parameters;
        }
		private static ExpressionNode ParseAgainstModel(Type modelType, string expression, ExpressionScope expressionScope, IMemberLocator memberLocator, SourceLocation location)
        {
            var dotIndex = expression.IndexOf('.');
            if (dotIndex >= 0)
            {
				var subModel = ParseAgainstModel(modelType, expression.Substring(0, dotIndex), expressionScope, memberLocator, location.SetLength(dotIndex));
                return SyntaxTreeExpression.SubModel(
                    subModel,
                    ParseAgainstModel(subModel.ResultType, expression.Substring(dotIndex + 1), ExpressionScope.CurrentModelOnStack, memberLocator, location.MoveIndex(dotIndex + 1)),
					location
                );
            }

            if (expression.EndsWith("()"))
            {
                var func = memberLocator.FindMethod(modelType, expression.Substring(0, expression.Length - 2));
                if (func != null) return SyntaxTreeExpression.Function(modelType, func.Name, location, expressionScope);
            }

            var prop = memberLocator.FindProperty(modelType, expression);
		    if (prop != null)
		        return SyntaxTreeExpression.Property(modelType, prop.Name, location, expressionScope);

            var field = memberLocator.FindField(modelType, expression);
		    if (field != null)
		        return SyntaxTreeExpression.Field(modelType, field.Name, location, expressionScope);

            if (IsLateBoundAcceptingType(modelType)) 
				return SyntaxTreeExpression.LateBound(expression, location, memberLocator, false, expressionScope);

            throw new VeilParserException(
                $"Unable to parse model expression '{expression}' againt model '{modelType.Name}'", location);
        }
Ejemplo n.º 10
0
        /// <summary>Resolve parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterKind">The parameter kind for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List<ParameterExpression> ResolveParameter(ExpressionScope scope, EvalCompilerParameterKind parameterKind, IDictionary<string, Type> parameterTypes)
        {
            if (parameterTypes == null) return null;

            List<ParameterExpression> parameterExpressions;

            switch (parameterKind)
            {
                case EvalCompilerParameterKind.Dictionary:
                    parameterExpressions = ResolveParameterDictionary(scope, parameterTypes);
                    break;
                case EvalCompilerParameterKind.Enumerable:
                    parameterExpressions = ResolveParameterEnumerable(scope, parameterTypes);
                    break;
                case EvalCompilerParameterKind.SingleDictionary:
                    parameterExpressions = ResolveParameterSingleDictionary(scope, parameterTypes);
                    break;
                case EvalCompilerParameterKind.Typed:
                    parameterExpressions = ResolveParameterTyped(scope, parameterTypes);
                    break;
                case EvalCompilerParameterKind.Untyped:
                    parameterExpressions = ResolveParameterUntyped(scope, parameterTypes);
                    break;
                default:
                    parameterExpressions = new List<ParameterExpression>();
                    break;
            }

            return parameterExpressions;
        }
Ejemplo n.º 11
0
        /// <summary>Resolve untyped parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameterUntyped(ExpressionScope scope, IDictionary <string, Type> parameterTypes)
        {
            var parameters = new List <ParameterExpression>();

            foreach (var parameter in parameterTypes)
            {
                var parameterExpression = scope.CreateParameter(typeof(object));
                parameters.Add(parameterExpression);

                scope.CreateLazyVariable(parameter.Key, new LazySingleThread <Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    var innerExpression = parameterExpression.Type != parameter.Value ?
                                          Expression.Assign(innerParameter, Expression.Convert(parameterExpression, parameter.Value)) :
                                          Expression.Assign(innerParameter, parameterExpression);

                    scope.Expressions.Insert(0, innerExpression);

                    return(innerParameter);
                }));
            }

            if (parameterTypes.Count == 1)
            {
                var keyValue = parameterTypes.First();
                if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object)
                {
                    ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value);
                }
            }

            return(parameters);
        }
Ejemplo n.º 12
0
        public override object Execute(object dataContext, ExpressionScope scope)
        {
            var left  = Left.Execute(dataContext, scope);
            var right = (Type)Right.Execute(dataContext, scope);

            return(right.IsInstanceOfType(left) ? left : null);
        }
        public object Execute(object dataContext, ExpressionScope scope)
        {
            var expression = _expression.Execute(dataContext, scope);
            var indexes    = _indexes.Select(i => i.Execute(dataContext, scope));

            return(ObjectHelper.GetIndexProperty(expression, indexes));
        }
Ejemplo n.º 14
0
        public override object Execute(object dataContext, ExpressionScope scope)
        {
            dynamic left  = Left.Execute(dataContext, scope);
            dynamic right = Right.Execute(dataContext, scope);

            return(left == right);
        }
        /// <summary>Resolve dictionary parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List<ParameterExpression> ResolveParameterDictionary(ExpressionScope scope, IDictionary<string, Type> parameterTypes)
        {
            var parameters = new List<ParameterExpression>();

            var parameterDictionary = scope.CreateParameter(typeof (IDictionary));
            parameters.Add(parameterDictionary);

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new Lazy<Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    Expression innerExpression = Expression.Property(parameterDictionary, DictionaryItemPropertyInfo, Expression.Constant(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                        Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                        Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return innerParameter;
                }));
            }

            return parameters;
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Evaluate the model itself e.g. Value types
 /// </summary>
 /// <param name="modelType">The type of the scoped model</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static SelfExpressionNode Self(Type modelType, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return(new SelfExpressionNode
     {
         ModelType = modelType,
         Scope = scope
     });
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Evaluate a field on the model object
 /// </summary>
 /// <param name="modelType">The type of the scoped model</param>
 /// <param name="fieldName">The name of the field</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static FieldExpressionNode Field(Type modelType, string fieldName, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return(new FieldExpressionNode
     {
         FieldInfo = modelType.GetField(fieldName),
         Scope = scope
     });
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Evaluate a field on the model object
 /// </summary>
 /// <param name="modelType">The type of the scoped model</param>
 /// <param name="fieldName">The name of the field</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static FieldExpressionNode Field(Type modelType, string fieldName, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return new FieldExpressionNode
     {
         FieldInfo = modelType.GetField(fieldName),
         Scope = scope
     };
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Evaluate a function call on the model
 /// </summary>
 /// <param name="modelType">The type of the scoped model</param>
 /// <param name="functionName">The name of the function</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static FunctionCallExpressionNode Function(Type modelType, string functionName, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return new FunctionCallExpressionNode
     {
         MethodInfo = modelType.GetMethod(functionName, new Type[0]),
         Scope = scope
     };
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Evaluate a property at runtime against an unknown model type
 /// </summary>
 /// <param name="itemName">The name of the proeprty that will be searched for</param>
 /// <param name="isCaseSenstiive">Indcates whether the expression should be evaluated with case sensitivity</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static LateBoundExpressionNode LateBound(string itemName, bool isCaseSenstiive = true, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return new LateBoundExpressionNode
     {
         ItemName = itemName,
         Scope = scope
     };
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Evaluate a property on the model object
 /// </summary>
 /// <param name="modelType">The type of the scoped model</param>
 /// <param name="propertyName">The name of the property</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static PropertyExpressionNode Property(Type modelType, string propertyName, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return new PropertyExpressionNode
     {
         PropertyInfo = modelType.GetProperty(propertyName),
         Scope = scope
     };
 }
Ejemplo n.º 22
0
		/// <summary>
		/// Evaluate the model itself e.g. Value types
		/// </summary>
		/// <param name="modelType">The type of the scoped model</param>
		/// <param name="scope">The scope this expression evaluated in</param>
		public static SelfExpressionNode Self(Type modelType, SourceLocation location, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
		{
			return new SelfExpressionNode
			{
				Location = location,
				ModelType = modelType,
				Scope = scope
			};
		}
Ejemplo n.º 23
0
		/// <summary>
		/// Evaluate an expression on a sub model, can be nested to traverse any depth of sub models
		/// </summary>
		/// <param name="modelExpression">An expression referencing the model to traverse to</param>
		/// <param name="subModelExpression">An expression to evaluate in the scope of the model that has been traversed to</param>
		/// <param name="scope">The scope this expression evaluated in</param>
		public static SubModelExpressionNode SubModel(ExpressionNode modelExpression, ExpressionNode subModelExpression, SourceLocation location, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
		{
			return new SubModelExpressionNode
			{
				Location = location,
				ModelExpression = modelExpression,
				SubModelExpression = subModelExpression,
				Scope = scope
			};
		}
Ejemplo n.º 24
0
	    /// <summary>
	    /// Evaluate a property on the model object
	    /// </summary>
	    /// <param name="modelType">The type of the scoped model</param>
	    /// <param name="propertyName">The name of the property</param>
	    /// <param name="location"></param>
	    /// <param name="scope">The scope this expression evaluated in</param>
	    /// <param name="recursionLevel"></param>
	    public static PropertyExpressionNode Property(Type modelType, string propertyName, SourceLocation location, ExpressionScope scope = ExpressionScope.CurrentModelOnStack, int recursionLevel = 0)
		{
			return new PropertyExpressionNode
			{
				Location = location,
				PropertyInfo = modelType.GetProperty(propertyName),
				Scope = scope,
                RecursionLevel = recursionLevel
			};
		}
Ejemplo n.º 25
0
	    /// <summary>
	    /// Evaluate a field on the model object
	    /// </summary>
	    /// <param name="modelType">The type of the scoped model</param>
	    /// <param name="fieldName">The name of the field</param>
	    /// <param name="location"></param>
	    /// <param name="scope">The scope this expression evaluated in</param>
	    /// <param name="recursionLevel"></param>
	    public static FieldExpressionNode Field(Type modelType, string fieldName, SourceLocation location, ExpressionScope scope = ExpressionScope.CurrentModelOnStack, int recursionLevel = 0)
		{
			return new FieldExpressionNode
			{
				Location = location,
				FieldInfo = modelType.GetField(fieldName),
				Scope = scope,
                RecursionLevel = recursionLevel
			};
		}
Ejemplo n.º 26
0
        public static TResult Find <TScope, TResult>(this ExpressionScope scope, INamespace <TScope> session, linq.Expression <Func <TScope, TResult> > getItem) where TScope : INamespace
        {
            foreach (var current in scope.Enumerate())
            {
                if (current.Context.TryGetItem(session, getItem, out var value))
                {
                    return(value);
                }
            }

            return(default);
Ejemplo n.º 27
0
        public object Execute(object dataContext, ExpressionScope scope)
        {
            var result = new DynamicWrapper();

            if (_initializer != null)
            {
                _initializer.Initialize(result, dataContext, scope);
            }

            return(result);
        }
Ejemplo n.º 28
0
        public object Execute(object dataContext, ExpressionScope scope)
        {
            // Формирование делегата для исполнения функции

            return(Expression.Lambda(Expression.Call(Expression.Constant(this),
                                                     ExecuteLambdaExpressionMethod,
                                                     Expression.Constant(dataContext),
                                                     Expression.Constant(scope),
                                                     Expression.NewArrayInit(typeof(object), _parameters)),
                                     _parameters)
                   .Compile());
        }
Ejemplo n.º 29
0
        public override Expression VisitStatement(ExprParser.StatementContext context)
        {
            if (context.GetChild(0).GetText() == "return")
            {
                ExpressionScope e = new ExpressionScope();
                e.Name      = "return";
                e.Operation = Operation.RETURN;
                e.Input     = Visit(context.expression());
                return(e);
            }

            return(null);
        }
Ejemplo n.º 30
0
        public void Initialize(object instance, object dataContext, ExpressionScope scope)
        {
            if (instance != null && _properties != null)
            {
                foreach (var property in _properties)
                {
                    var propertyName  = property.Key;
                    var propertyValue = property.Value.Execute(dataContext, scope);

                    instance.SetProperty(propertyName, propertyValue);
                }
            }
        }
Ejemplo n.º 31
0
        public void ProjectionTest()
        {
            // Create Oldedb top set
            SetTopOledb dbTop = new SetTopOledb("Northwind");

            dbTop.ConnectionString = Northwind;
            dbTop.Open();
            dbTop.ImportSchema();

            SetTop wsTop = new SetTop("My Mashup");

            //
            // Load test data
            //
            Set targetSet = Mapper.ImportSet(dbTop.FindSubset("Order Details"), wsTop);

            targetSet.TableDefinition.Populate();

            //
            // Create derived dimensions
            //
            Set od = wsTop.FindSubset("Order Details");

            // Create expression
            Dim        d1   = od.GetGreaterDim("Order ID");
            Dim        d2   = d1.GreaterSet.GetGreaterDim("Customer ID");
            Dim        d3   = d2.GreaterSet.GetGreaterDim("Last Name");
            List <Dim> path = new List <Dim> {
                d1, d2, d3
            };

            Expression expr = Expression.CreateProjectExpression(path, Operation.PROJECTION);

            // Add derived dimension
            Dim derived1 = d3.GreaterSet.CreateDefaultLesserDimension("Customer Last Name", od);

            derived1.Add();

            var funcExpr = ExpressionScope.CreateFunctionDeclaration("Customer Last Name", "Order Details", "String");

            funcExpr.Statements[0].Input = expr; // Return statement
            funcExpr.ResolveFunction(wsTop);
            funcExpr.Resolve();

            derived1.SelectExpression = funcExpr;

            // Update
            derived1.Evaluate();

            Assert.AreEqual("Axen", od.GetValue("Customer Last Name", 10));
        }
Ejemplo n.º 32
0
        private Expression EvaluateScope(ExpressionScope scope)
        {
            switch (scope)
            {
            case ExpressionScope.CurrentModelOnStack: return(this.modelStack.First.Value);

            case ExpressionScope.RootModel: return(this.modelStack.Last.Value);

            case ExpressionScope.ModelOfParentScope: return(this.modelStack.First.Next.Value);

            default:
                throw new VeilCompilerException("Unknown expression scope '{0}'".FormatInvariant(scope));
            }
        }
Ejemplo n.º 33
0
        public object Execute(object dataContext, ExpressionScope scope)
        {
            object result;

            object invokeTarget = null;

            object[] invokeArguments = null;

            if (_invokeTarget != null)
            {
                invokeTarget = _invokeTarget.Execute(dataContext, scope);
            }

            if (_invokeArguments != null)
            {
                invokeArguments =
                    _invokeArguments.Select(i => (i != null) ? i.Execute(dataContext, scope) : null).ToArray();
            }

            // Вызов статического метода
            if (invokeTarget is Type)
            {
                ReflectionExtensions.InvokeMember((Type)invokeTarget, _methodName, invokeArguments, out result,
                                                  _genericArguments);
            }
            // Вызов метода динамического объекта
            else if (invokeTarget is IDynamicMetaObjectProvider)
            {
                // Получение свойства динамического объекта
                var methodDelegate = ObjectHelper.GetProperty(invokeTarget, _methodName) as Delegate;

                if (methodDelegate != null)
                {
                    result = ReflectionExtensions.FastDynamicInvoke(methodDelegate, invokeArguments);
                }
                else
                {
                    ReflectionExtensions.InvokeMember(invokeTarget, _methodName, invokeArguments, out result,
                                                      _genericArguments);
                }
            }
            // Вызов метода строготипизированного обычного объекта
            else
            {
                ReflectionExtensions.InvokeMember(invokeTarget, _methodName, invokeArguments, out result,
                                                  _genericArguments);
            }

            return(result);
        }
Ejemplo n.º 34
0
        public object Execute(object dataContext, ExpressionScope scope)
        {
            var parameters = (_parameters != null)
                ? _parameters.Select(i => i.Execute(dataContext, scope)).ToArray()
                : null;

            var result = Activator.CreateInstance(_type, parameters);

            if (_initializer != null)
            {
                _initializer.Initialize(result, dataContext, scope);
            }

            return(result);
        }
Ejemplo n.º 35
0
        public object Execute(object dataContext, ExpressionScope scope)
        {
            var expression = _expression.Execute(dataContext, scope);

            foreach (var section in _sections)
            {
                var label = section.Key.Execute(dataContext, scope);

                if (Equals(label, expression))
                {
                    return(section.Value.Execute(dataContext, scope));
                }
            }

            return(null);
        }
        public object Execute(object dataContext, ExpressionScope scope)
        {
            object result;

            var expression = _expression.Execute(dataContext, scope);

            if (expression is Type)
            {
                result = ReflectionExtensions.GetMemberValue((Type)expression, _memberName);
            }
            else
            {
                result = ObjectHelper.GetProperty(expression, _memberName);
            }

            return(result);
        }
Ejemplo n.º 37
0
        public object Execute(object dataContext, ExpressionScope scope)
        {
            var expression = _expression.Execute(dataContext, scope);

            if (expression == null)
            {
                if (_type.IsValueType)
                {
                    expression = ReflectionExtensions.GetDefaultValue(_type);
                }
            }
            else
            {
                expression = Convert.ChangeType(expression, _type);
            }

            return(expression);
        }
Ejemplo n.º 38
0
        //
        // Function
        //

        public override Expression VisitFunction(ExprParser.FunctionContext context)
        {
            string type = GetType(context.type()); // Return type
            string name = GetName(context.name()); // Function name

            ExpressionScope e = new ExpressionScope();

            e.Name          = name;
            e.Operation     = Operation.FUNCTION;
            e.OutputSetName = type;

            // Find all parameter declarations and store them as operands of the expression
            int paramCount = context.parameter().Count();

            for (int i = 0; i < paramCount; i++)
            {
                Expression paramExpr = Visit(context.parameter(i));
                if (i == 0)
                {
                    e.Input = paramExpr;
                }
                else
                {
                    e.AddOperand(paramExpr);
                }
            }

            // Find all statements and store them in the expression
            int stmtCount = context.statement().Count();

            for (int i = 0; i < stmtCount; i++)
            {
                ExpressionScope stmtExpr = (ExpressionScope)Visit(context.statement(i));
                if (stmtExpr == null)
                {
                    continue;
                }

                e.AddStatement(stmtExpr);
            }

            return(e);
        }
Ejemplo n.º 39
0
        /// <summary>Resolve lazy member from the member type</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <param name="parameterName">The main parameter name.</param>
        /// <param name="memberType">The member type.</param>
        private static void ResolzeLazyMember(ExpressionScope scope, IDictionary <string, Type> parameterTypes, string parameterName, Type memberType)
        {
            if (Type.GetTypeCode(memberType) == TypeCode.Object)
            {
                var parameterProperties = memberType.GetProperties().Where(x => x.GetIndexParameters().Count() == 0).ToArray();
                var parameterFields     = memberType.GetFields();
                var instanceMethods     = memberType.GetMethods();

                foreach (var propertyInfo in parameterProperties)
                {
                    parameterTypes.Add(propertyInfo.Name, propertyInfo.PropertyType);

                    scope.CreateLazyVariable(propertyInfo.Name, new Lazy <Expression>(() =>
                    {
                        var innerParameter  = scope.CreateVariable(propertyInfo.PropertyType, propertyInfo.Name);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Property(scope.GetValueExpressionOrNull(parameterName), propertyInfo));
                        scope.Expressions.Add(innerExpression);

                        return(innerParameter);
                    }));
                }

                foreach (var fieldInfo in parameterFields)
                {
                    parameterTypes.Add(fieldInfo.Name, fieldInfo.FieldType);

                    scope.CreateLazyVariable(fieldInfo.Name, new Lazy <Expression>(() =>
                    {
                        var innerParameter  = scope.CreateVariable(fieldInfo.FieldType, fieldInfo.Name);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Field(scope.GetValueExpressionOrNull(parameterName), fieldInfo));
                        scope.Expressions.Add(innerExpression);

                        return(innerParameter);
                    }));
                }

                foreach (var method in instanceMethods)
                {
                    scope.InstanceMethods.Add(method, parameterName);
                }
            }
        }
        /// <summary>Resolve lazy member from the member type</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <param name="parameterName">The main parameter name.</param>
        /// <param name="memberType">The member type.</param>
        private static void ResolzeLazyMember(ExpressionScope scope, IDictionary<string, Type> parameterTypes, string parameterName, Type memberType)
        {
            if (Type.GetTypeCode(memberType) == TypeCode.Object)
            {
                var parameterProperties = memberType.GetProperties().Where(x => x.GetIndexParameters().Count() == 0).ToArray();
                var parameterFields = memberType.GetFields();
                var instanceMethods = memberType.GetMethods();

                foreach (var propertyInfo in parameterProperties)
                {
                    parameterTypes.Add(propertyInfo.Name, propertyInfo.PropertyType);

                    scope.CreateLazyVariable(propertyInfo.Name, new Lazy<Expression>(() =>
                    {
                        var innerParameter = scope.CreateVariable(propertyInfo.PropertyType, propertyInfo.Name);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Property(scope.GetValueExpressionOrNull(parameterName), propertyInfo));
                        scope.Expressions.Add(innerExpression);

                        return innerParameter;
                    }));
                }

                foreach (var fieldInfo in parameterFields)
                {
                    parameterTypes.Add(fieldInfo.Name, fieldInfo.FieldType);

                    scope.CreateLazyVariable(fieldInfo.Name, new Lazy<Expression>(() =>
                    {
                        var innerParameter = scope.CreateVariable(fieldInfo.FieldType, fieldInfo.Name);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Field(scope.GetValueExpressionOrNull(parameterName), fieldInfo));
                        scope.Expressions.Add(innerExpression);

                        return innerParameter;
                    }));
                }

                foreach (var method in instanceMethods)
                {
                    scope.InstanceMethods.Add(method, parameterName);
                }
            }
        }
        /// <summary>Resolve typed parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List<ParameterExpression> ResolveParameterTyped(ExpressionScope scope, IDictionary<string, Type> parameterTypes)
        {
            var parameters = new List<ParameterExpression>();

            foreach (var parameter in parameterTypes)
            {
                parameters.Add(scope.CreateParameter(parameter.Value, parameter.Key));
            }

            if (parameterTypes.Count == 1)
            {
                var keyValue = parameterTypes.First();
                if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object)
                {
                    ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value);
                }
            }

            return parameters;
        }
Ejemplo n.º 42
0
        /// <summary>Resolve typed parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameterTyped(ExpressionScope scope, IDictionary <string, Type> parameterTypes)
        {
            var parameters = new List <ParameterExpression>();

            foreach (var parameter in parameterTypes)
            {
                parameters.Add(scope.CreateParameter(parameter.Value, parameter.Key));
            }

            if (parameterTypes.Count == 1)
            {
                var keyValue = parameterTypes.First();
                if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object)
                {
                    ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value);
                }
            }

            return(parameters);
        }
Ejemplo n.º 43
0
        private object ExecuteLambdaExpression(object dataContext, ExpressionScope scope, object[] arguments)
        {
            if (_body != null)
            {
                var lambdaScope = new ExpressionScope(scope);

                // Заполнение контекста параметрами функции

                if (arguments != null)
                {
                    for (var i = 0; i < arguments.Length && i < _parameters.Count; ++i)
                    {
                        lambdaScope.DeclareVariable(_parameters[i].Name, arguments[i]);
                    }
                }

                return(_body.Execute(dataContext, lambdaScope));
            }

            return(null);
        }
        public void Initialize(object instance, object dataContext, ExpressionScope scope)
        {
            if (instance != null)
            {
                if (instance is IList)
                {
                    var list = (IList)instance;

                    foreach (var item in _items)
                    {
                        var itemValue = item.Execute(dataContext, scope);
                        list.Add(itemValue);
                    }
                }
                else
                {
                    var collectionType =
                        instance.GetType()
                        .GetInterfaces()
                        .FirstOrDefault(
                            i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection <>));

                    if (collectionType != null)
                    {
                        var addMethod   = collectionType.GetMethod("Add");
                        var elementType = collectionType.GetGenericArguments().FirstOrDefault();

                        if (addMethod != null && elementType != null && (elementType.IsClass || elementType.IsValueType))
                        {
                            foreach (var item in _items)
                            {
                                var itemValue = Activator.CreateInstance(elementType,
                                                                         item.Execute(dataContext, scope) as object[]);
                                addMethod.Invoke(instance, new[] { itemValue });
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 45
0
        /// <summary>Resolve parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterKind">The parameter kind for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameter(ExpressionScope scope, EvalCompilerParameterKind parameterKind, IDictionary <string, Type> parameterTypes)
        {
            if (parameterTypes == null)
            {
                return(null);
            }

            List <ParameterExpression> parameterExpressions;

            switch (parameterKind)
            {
            case EvalCompilerParameterKind.Dictionary:
                parameterExpressions = ResolveParameterDictionary(scope, parameterTypes);
                break;

            case EvalCompilerParameterKind.Enumerable:
                parameterExpressions = ResolveParameterEnumerable(scope, parameterTypes);
                break;

            case EvalCompilerParameterKind.SingleDictionary:
                parameterExpressions = ResolveParameterSingleDictionary(scope, parameterTypes);
                break;

            case EvalCompilerParameterKind.Typed:
                parameterExpressions = ResolveParameterTyped(scope, parameterTypes);
                break;

            case EvalCompilerParameterKind.Untyped:
                parameterExpressions = ResolveParameterUntyped(scope, parameterTypes);
                break;

            default:
                parameterExpressions = new List <ParameterExpression>();
                break;
            }

            return(parameterExpressions);
        }
        /// <summary>Resolve single dictionary parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameterSingleDictionary(ExpressionScope scope, IDictionary <string, Type> parameterTypes, bool forceFirstParameterProperty = false)
        {
            var parameters = new List <ParameterExpression>();

            var parameterDictionary = scope.CreateParameter(typeof(IDictionary), "{0}");

            parameters.Add(parameterDictionary);

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new Lazy <Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    Expression innerExpression = Expression.Property(parameterDictionary, DictionaryItemPropertyInfo, Expression.Constant(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                                      Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                                      Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return(innerParameter);
                }));
            }

            if (parameterTypes.Count > 0 && forceFirstParameterProperty)
            {
                var keyValue = parameterTypes.First();
                if (Type.GetTypeCode(keyValue.Value) == TypeCode.Object)
                {
                    ResolzeLazyMember(scope, parameterTypes, keyValue.Key, keyValue.Value);
                }
            }

            return(parameters);
        }
Ejemplo n.º 47
0
        /// <summary>Resolve single object parameters used for the code or expression.</summary>
        /// <param name="scope">The expression scope for the code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <returns>A ParameterExpression list used in code or expression to compile.</returns>
        private static List <ParameterExpression> ResolveParameterSingleObject(ExpressionScope scope, IDictionary <string, Type> parameterTypes)
        {
            var parameters = new List <ParameterExpression>();

            var parameterExpression = scope.CreateParameter(typeof(object));

            parameters.Add(parameterExpression);

            var parameterObjectType = parameterTypes["{0}"];
            var parameterObject     = scope.CreateVariable(parameterObjectType, "{0}");

            scope.Expressions.Add(Expression.Assign(parameterObject, Expression.Convert(parameterExpression, parameterObjectType)));

            foreach (var parameter in parameterTypes)
            {
                scope.CreateLazyVariable(parameter.Key, new Lazy <Expression>(() =>
                {
                    var innerParameter = scope.CreateVariable(parameter.Value, parameter.Key);

                    var property = parameterObjectType.GetProperty(parameter.Key);

                    Expression innerExpression = property != null ?
                                                 Expression.Property(parameterObject, property) :
                                                 Expression.Field(parameterObject, parameterObjectType.GetField(parameter.Key));

                    innerExpression = innerExpression.Type != parameter.Value ?
                                      Expression.Assign(innerParameter, Expression.Convert(innerExpression, parameter.Value)) :
                                      Expression.Assign(innerParameter, innerExpression);

                    scope.Expressions.Add(Expression.Assign(innerParameter, innerExpression));

                    return(innerParameter);
                }));
            }

            return(parameters);
        }
Ejemplo n.º 48
0
		/// <summary>
		/// Evaluate a property at runtime against an unknown model type
		/// </summary>
		/// <param name="itemName">The name of the proeprty that will be searched for</param>
		/// <param name="isCaseSenstiive">Indcates whether the expression should be evaluated with case sensitivity</param>
		/// <param name="scope">The scope this expression evaluated in</param>
		public static LateBoundExpressionNode LateBound(string itemName, SourceLocation location, IMemberLocator memberLocator = null, bool isCaseSenstiive = true, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
		{
			return new LateBoundExpressionNode
			{
				Location = location,
                MemberLocator = memberLocator ?? MemberLocator.Default,
				ItemName = itemName,
				Scope = scope
			};
		}
Ejemplo n.º 49
0
        /// <summary>Compile the code or expression and return a TDelegate of type Func or Action to execute.</summary>
        /// <param name="context">The eval context used to compile the code or expression.</param>
        /// <param name="code">The code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <param name="resultType">Type of the compiled code or expression result.</param>
        /// <returns>A TDelegate of type Func or Action that represents the compiled code or expression.</returns>
        internal static EvalDelegate Compile(EvalContext context, string code, ListDictionary parameterTypes, Type resultType)
        {
            var cacheKey = ResolveCacheKey(context, typeof (Func<IDictionary, object>), code, parameterTypes);

            EvalDelegate cachedDelegate;
            if (EvalManager.CacheDelegate.TryGetValue(cacheKey, out cachedDelegate))
            {
                return cachedDelegate;
            }

            Dictionary<string, Type> parameterDict = new Dictionary<string, Type>();
            foreach (DictionaryEntry parameterType in parameterTypes)
            {
                parameterDict.Add((string)parameterType.Key, (Type)parameterType.Value);
            }

            // Options
            var scope = new ExpressionScope
            {
                AliasExtensionMethods = context.AliasExtensionMethods,
                AliasNames = context.AliasNames,
                AliasStaticMembers = context.AliasStaticMembers,
                AliasTypes = context.AliasTypes,
                BindingFlags = context.BindingFlags,
                UseCaretForExponent = context.UseCaretForExponent
            };

            // ADD global constants
            if (context.AliasGlobalConstants.Count > 0)
            {
                scope.Constants = new Dictionary<string, ConstantExpression>(context.AliasGlobalConstants);
            }

            // ADD global variables
            if (context.AliasGlobalVariables.Count > 0)
            {
                foreach (var keyValue in context.AliasGlobalVariables)
                {
#if SQLNET
                    scope.CreateLazyVariable(keyValue.Key, new LazySingleThread<Expression>(() =>
#else
                    scope.CreateLazyVariable(keyValue.Key, new Lazy<Expression>(() =>
#endif
                    {
                        var innerParameter = scope.CreateVariable(keyValue.Value.GetType(), keyValue.Key);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Constant(keyValue.Value));
                        scope.Expressions.Add(innerExpression);
                        return innerParameter;
                    }));
                }
            }

            // Resolve Parameter
            var parameterExpressions = ResolveParameter(scope, parameterDict);

            // CodeAnalysis
            var syntaxRoot = SyntaxParser.ParseText(code);

            // CodeCompiler
            var expression = ExpressionParser.ParseSyntax(scope, syntaxRoot, resultType);

            // Compile the expression
            var compiled = Expression.Lambda<Func<IDictionary, object>>(expression, parameterExpressions).Compile();

            var evalDelegate = new EvalDelegate(cacheKey, compiled);
            EvalManager.CacheDelegate.TryAdd(cacheKey, evalDelegate);

            return evalDelegate;
        }
Ejemplo n.º 50
0
        /// <summary>Compile the code or expression and return a TDelegate of type Func or Action to execute.</summary>
        /// <typeparam name="TDelegate">Type of the delegate (Func or Action) to use to compile the code or expression.</typeparam>
        /// <param name="context">The eval context used to compile the code or expression.</param>
        /// <param name="code">The code or expression to compile.</param>
        /// <param name="parameterTypes">The dictionary of parameter (name / type) used in the code or expression to compile.</param>
        /// <param name="resultType">Type of the compiled code or expression result.</param>
        /// <param name="parameterKind">The parameter kind for the code or expression to compile.</param>
        /// <returns>A TDelegate of type Func or Action that represents the compiled code or expression.</returns>
        internal static TDelegate Compile <TDelegate>(EvalContext context, string code, IDictionary <string, Type> parameterTypes, Type resultType, EvalCompilerParameterKind parameterKind)
        {
            var cacheKey = context.UseCache ? ResolveCacheKey(context, typeof(TDelegate), code, parameterTypes) : "";

            if (context.UseCache)
            {
                var item = EvalManager.Cache.Get(cacheKey);

                if (item != null)
                {
                    return((TDelegate)item);
                }
            }

            // Options
            var scope = new ExpressionScope
            {
                AliasExtensionMethods = context.AliasExtensionMethods,
                //AliasGlobalConstants = context.AliasGlobalConstants,
                //AliasGlobalVariables = context.AliasGlobalVariables,
                AliasNames          = context.AliasNames,
                AliasStaticMembers  = context.AliasStaticMembers,
                AliasTypes          = context.AliasTypes,
                BindingFlags        = context.BindingFlags,
                UseCaretForExponent = context.UseCaretForExponent
            };

            // Resolve Parameter
            var parameterExpressions = ResolveParameter(scope, parameterKind, parameterTypes);

            // ADD global constants
            if (context.AliasGlobalConstants.Count > 0)
            {
                scope.Constants = new Dictionary <string, ConstantExpression>(context.AliasGlobalConstants);
            }

            // ADD global variables
            if (context.AliasGlobalVariables.Count > 0)
            {
                foreach (var keyValue in context.AliasGlobalVariables)
                {
                    scope.CreateLazyVariable(keyValue.Key, new Lazy <Expression>(() =>
                    {
                        var innerParameter  = scope.CreateVariable(keyValue.Value.GetType(), keyValue.Key);
                        var innerExpression = Expression.Assign(innerParameter, Expression.Constant(keyValue.Value));
                        scope.Expressions.Add(innerExpression);
                        return(innerParameter);
                    }));
                }
            }

            // CodeAnalysis
            var syntaxRoot = SyntaxParser.ParseText(code);

            // CodeCompiler
            var expression = ExpressionParser.ParseSyntax(scope, syntaxRoot, resultType);

            // Compile the expression
            var compiled = Expression.Lambda <TDelegate>(expression, parameterExpressions).Compile();

            if (context.UseCache)
            {
                EvalManager.Cache.AddOrGetExisting(new CacheItem(cacheKey, compiled), new CacheItemPolicy());
            }

            return(compiled);
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Evaluate the model itself e.g. Value types
 /// </summary>
 /// <param name="modelType">The type of the scoped model</param>
 /// <param name="scope">The scope this expression evaluated in</param>
 public static SelfExpressionNode Self(Type modelType, ExpressionScope scope = ExpressionScope.CurrentModelOnStack)
 {
     return new SelfExpressionNode
     {
         ModelType = modelType,
         Scope = scope
     };
 }