Esempio n. 1
0
        public void ExecuteTest2()
        {
            var functions = new FunctionCollection();

            var func = new UserFunction("f", new IExpression[] { new Number(1) });

            Assert.Throws <KeyNotFoundException>(() => func.Execute(functions));
        }
Esempio n. 2
0
        private int CompareFunc(UserFunction userFunction, List <Variable> paramList)
        {
            var outVar = userFunction.Execute(paramList, null, null);

            if (outVar)
            {
                return(-1);
            }
            return(1);
        }
Esempio n. 3
0
        public void ExecuteTest1()
        {
            var functions = new FunctionCollection();

            functions.Add(new UserFunction("f", new IExpression[] { Variable.X }), new Ln(Variable.X));

            var func = new UserFunction("f", new IExpression[] { new Number(1) });

            Assert.Equal(Math.Log(1), func.Execute(functions));
        }
Esempio n. 4
0
        public void ExecuteTest3()
        {
            var uf1   = new UserFunction("func", new[] { Variable.X }, 1);
            var func  = new DelegateExpression(p => (double)p.Variables["x"] == 10 ? 0 : 1);
            var funcs = new FunctionCollection
            {
                { uf1, func }
            };
            var uf2    = new UserFunction("func", new[] { new Number(12) }, 1);
            var result = uf2.Execute(new ExpressionParameters(funcs));

            Assert.Equal(1, result);
        }
Esempio n. 5
0
        public void ExecuteRecursiveTest()
        {
            var expParams = new ExpressionParameters();

            var exp = new If(new Equal(Variable.X, new Number(0)),
                             new Number(1),
                             new Mul(Variable.X, new UserFunction("f", new[] { new Sub(Variable.X, new Number(1)) })));

            expParams.Functions.Add(new UserFunction("f", new[] { Variable.X }), exp);

            var func = new UserFunction("f", new[] { new Number(4) });

            Assert.Equal(24.0, func.Execute(expParams));
        }
Esempio n. 6
0
        public void ExecuteNullTest()
        {
            var exp = new UserFunction("f", new IExpression[0]);

            Assert.Throws <ArgumentNullException>(() => exp.Execute(null));
        }
Esempio n. 7
0
        /// <summary>
        ///     Executes an expression.
        /// </summary>
        public SkryptObject ExecuteExpression(Node node, ScopeContext scopeContext)
        {
            _engine.CurrentNode = node;

            var op = Operator.AllOperators.Find(o => o.OperationName == node.Body);

            if (op != null)
            {
                // Do return operation.
                if (op.OperationName == "return")
                {
                    if ((scopeContext.Properties & ScopeProperties.InMethod) == 0)
                    {
                        _engine.ThrowError("Can't use return operator outside method", node.Token);
                    }

                    // Return null if no value was given.
                    SkryptObject result = node.Nodes.Count == 1
                        ? ExecuteExpression(node.Nodes[0], scopeContext)
                        : new Library.Native.System.Null();

                    scopeContext.ReturnObject = result;

                    return(null);
                }

                // Do break operation.
                if (op.OperationName == "break")
                {
                    if ((scopeContext.Properties & ScopeProperties.InLoop) == 0)
                    {
                        _engine.ThrowError("Can't use break operator outside loop", node.Token);
                    }

                    scopeContext.Properties |= ScopeProperties.BrokeLoop;
                    return(null);
                }

                // Do continue operation.
                if (op.OperationName == "continue")
                {
                    if ((scopeContext.Properties & ScopeProperties.InLoop) == 0)
                    {
                        _engine.ThrowError("Can't use continue operator outside loop", node.Token);
                    }

                    scopeContext.Properties |= ScopeProperties.SkippedLoop;
                    return(null);
                }

                // Do access operation.
                if (op.OperationName == "access")
                {
                    var target = ExecuteExpression(node.Nodes[0], scopeContext);
                    var result = ExecuteAccess(target, node.Nodes[1], scopeContext);

                    scopeContext.Caller = result.Owner;

                    // Execute result as method if its a getter property.
                    if (result.Property.Value.GetType() == typeof(GetMethod))
                    {
                        var ex = ((GetMethod)result.Property.Value).Execute(_engine, result.Owner, new SkryptObject[0], new ScopeContext {
                            ParentScope = scopeContext
                        });

                        return(ex.ReturnObject);
                    }
                    else
                    {
                        return(result.Property.Value);
                    }
                }

                // Do assignment operation.
                if (op.OperationName == "assign")
                {
                    // Solve right side.
                    var result = ExecuteExpression(node.Nodes[1], scopeContext);

                    // Copy value of results like numbers, string etc, so variables that
                    // are assigned to eachother don't edit eachothers values.
                    if (typeof(SkryptType).IsAssignableFrom(result.GetType()))
                    {
                        if (((SkryptType)result).CreateCopyOnAssignment)
                        {
                            result = result.Clone();
                        }
                    }

                    // Left side is an identifier.
                    if (node.Nodes[0].Nodes.Count == 0 && node.Nodes[0].Type == TokenTypes.Identifier)
                    {
                        if (GeneralParser.Keywords.Contains(node.Nodes[0].Body))
                        {
                            _engine.ThrowError("Setting variable names to keywords is disallowed");
                        }

                        var variable = GetVariable(node.Nodes[0].Body, scopeContext);

                        if (variable != null && !scopeContext.StrictlyLocal)
                        {
                            if ((variable.Modifiers & Modifier.Const) != 0)
                            {
                                _engine.ThrowError("Variable is marked as constant and can thus not be modified.", node.Nodes[0].Token);
                            }

                            if ((variable.Modifiers & Modifier.Strong) != 0)
                            {
                                if (variable.Value.Name != result.Name)
                                {
                                    _engine.ThrowError($"Can't set strong variable of type {variable.Value.Name} to {result.Name}", node.Nodes[0].Token);
                                }
                            }

                            variable.Value = result;
                        }
                        else
                        {
                            scopeContext.SetVariable(node.Nodes[0].Body, result, node.Modifiers);
                        }
                    }
                    // Left side is an expression.
                    else if (node.Nodes[0].Body == "access")
                    {
                        var target       = ExecuteExpression(node.Nodes[0].Nodes[0], scopeContext);
                        var accessResult = ExecuteAccess(target, node.Nodes[0].Nodes[1], scopeContext, true);

                        if ((accessResult.Property.Modifiers & Modifier.Const) != 0)
                        {
                            _engine.ThrowError("Property is marked as constant and can thus not be modified.", node.Nodes[0].Nodes[1].Token);
                        }

                        if ((accessResult.Property.Modifiers & Modifier.Strong) != 0)
                        {
                            if (accessResult.Property.Value.Name != result.Name)
                            {
                                _engine.ThrowError($"Can't set strong property of type {accessResult.Property.Value.Name} to {result.Name}", node.Nodes[0].Nodes[1].Token);
                            }
                        }

                        if (accessResult.Property.IsSetter)
                        {
                            ((SetMethod)accessResult.Property.Value).Execute(_engine, target, result, new ScopeContext {
                                ParentScope = scopeContext
                            });
                        }
                        else
                        {
                            accessResult.Property.Value = result;
                        }

                        //SetFunctionOwner(result, target);
                    }
                    // Left side is an expression.
                    else if (node.Nodes[0].Body == "Index")
                    {
                        ExecuteIndexSet(result, (IndexNode)node.Nodes[0], scopeContext);
                    }
                    else
                    {
                        _engine.ThrowError("Left hand side needs to be a variable or property!", node.Nodes[0].Token);
                    }

                    return(result);
                }

                // Evaluate node as binary expression.
                if (op.Members == 2)
                {
                    var leftResult  = ExecuteExpression(node.Nodes[0], scopeContext);
                    var rightResult = ExecuteExpression(node.Nodes[1], scopeContext);

                    return(_engine.Eval(op, leftResult, rightResult, node));
                }

                // Evaluate node as unary expression.
                if (op.Members == 1)
                {
                    var leftResult = ExecuteExpression(node.Nodes[0], scopeContext);

                    return(_engine.Eval(op, leftResult, node));;
                }
            }
            // Create array literal instance.
            else if (node.Type == TokenTypes.ArrayLiteral)
            {
                var arrayNode = (ArrayNode)node;
                var array     = _engine.Create <Library.Native.System.Array>();

                // Solve all expressions within the array and add the resulting values.
                for (var i = 0; i < arrayNode.Values.Count; i++)
                {
                    var subNode = arrayNode.Values[i];

                    var result = ExecuteExpression(subNode, scopeContext);

                    array.List.Add(result);
                }

                return(array);
            }
            // Create function literal instance.
            else if (node.Type == TokenTypes.FunctionLiteral)
            {
                var result = new UserFunction {
                    Name      = "method",
                    Signature = node.Body,
                    BlockNode = node.Nodes[0],
                    CallName  = node.Body.Split('_')[0],
                    Path      = _engine.CurrentExecutingFile
                };

                foreach (var snode in node.Nodes[1].Nodes)
                {
                    result.Parameters.Add(snode.Body);
                }

                return(result);
            }
            else if (node.Type == TokenTypes.Conditional)
            {
                var conditionNode = (ConditionalNode)node;
                var conditionBool = ExecuteExpression(conditionNode.Condition, scopeContext);

                if (conditionBool.ToBoolean())
                {
                    return(ExecuteExpression(conditionNode.Pass, scopeContext));
                }
                else
                {
                    return(ExecuteExpression(conditionNode.Fail, scopeContext));
                }
            }
            else
            {
                switch (node.Type)
                {
                case TokenTypes.NumericLiteral:
                    return(_engine.Create <Library.Native.System.Numeric>(((NumericNode)node).Value));

                case TokenTypes.StringLiteral:
                    return(_engine.Create <Library.Native.System.String>(((StringNode)node).Value));

                case TokenTypes.BooleanLiteral:
                    return(_engine.Create <Library.Native.System.Boolean>(((BooleanNode)node).Value));

                case TokenTypes.NullLiteral:
                    return(_engine.Create <Library.Native.System.Null>());
                }
            }

            // Get variable
            if (node.Type == TokenTypes.Identifier)
            {
                var foundVariable = GetVariable(node.Body, scopeContext);

                if (foundVariable != null)
                {
                    return(foundVariable.Value);
                }

                _engine.ThrowError("Variable '" + node.Body + "' does not exist in the current context!", node.Token);
            }

            // Do index operation
            if (node.Type == TokenTypes.Index)
            {
                return(ExecuteIndex((IndexNode)node, scopeContext));
            }

            // Do function call operation.
            if (node.Type == TokenTypes.Call)
            {
                var callNode  = (CallNode)node;
                var arguments = new List <SkryptObject>();

                // Solve argument expressions.
                foreach (var subNode in callNode.Arguments)
                {
                    var result = ExecuteExpression(subNode, scopeContext);

                    arguments.Add(result);
                }

                // Get the value that's being called.
                var foundFunction = ExecuteExpression(callNode.Getter, scopeContext);

                var caller = scopeContext.Caller;

                SkryptObject BaseType = null;

                bool isConstructor    = false;
                bool validConstructor = true;

                // Check if we're creating a new instance of a type.
                if (!typeof(SkryptMethod).IsAssignableFrom(foundFunction.GetType()))
                {
                    var find     = foundFunction.GetProperty("Constructor");
                    var typeName = foundFunction.GetProperty("TypeName").ToString();

                    validConstructor = foundFunction.GetType() == typeof(SkryptObject);

                    foundFunction = find ?? new SkryptMethod {
                        Name = "Constructor"
                    };

                    BaseType = GetType(typeName, scopeContext);

                    // Create new instance of type and set that as the caller.
                    caller = (SkryptType)Activator.CreateInstance(BaseType.GetType());
                    caller.ScopeContext = _engine.CurrentScope;
                    caller.Engine       = _engine;
                    caller.Name         = typeName;
                    caller.GetPropertiesFrom(BaseType);

                    isConstructor = true;
                }

                // Create new scope to use within the function.
                var methodContext = new ScopeContext {
                    ParentScope = scopeContext,
                    // Create new call stack for method.
                    CallStack  = new CallStack(((SkryptMethod)foundFunction).Name, callNode.Getter.Token, scopeContext.CallStack, ""),
                    Properties = scopeContext.Properties | ScopeProperties.InMethod
                };

                _engine.CurrentStack = methodContext.CallStack;

                ScopeContext methodScopeResult = null;

                // Function is defined in Skrypt.
                if (foundFunction.GetType() == typeof(UserFunction))
                {
                    UserFunction function = (UserFunction)foundFunction;

                    // Create variables for each parameter based on the given arguments.
                    for (var i = 0; i < function.Parameters.Count; i++)
                    {
                        var          parName = function.Parameters[i];
                        SkryptObject input;

                        // Set to null if there's no argument.
                        input = i < arguments.Count ? arguments[i] : new Library.Native.System.Null();

                        methodContext.Variables[parName] = new Variable {
                            Name  = parName,
                            Value = input,
                            Scope = methodContext
                        };
                    }

                    methodContext.CallStack.Path = _engine.CurrentExecutingFile;

                    _engine.CurrentExecutingFile = function.Path;

                    methodScopeResult = function.Execute(_engine, caller, arguments.ToArray(), methodContext);
                }
                // Function is defined in C#.
                else if (foundFunction.GetType() == typeof(SharpMethod))
                {
                    methodScopeResult = ((SharpMethod)foundFunction).Execute(_engine, caller, arguments.ToArray(), methodContext);
                }
                else if (!validConstructor)
                {
                    _engine.ThrowError("Cannot call value, as it is not a function!", callNode.Getter.Token);
                }

                if (isConstructor)
                {
                    caller.ScopeContext = _engine.CurrentScope;
                    caller.Engine       = _engine;

                    return(caller);
                }
                else
                {
                    return(methodScopeResult.ReturnObject);
                }
            }

            return(null);
        }
Esempio n. 8
0
        /// <summary>
        ///     Allows you to invoke a function from the engine's global scope.
        /// </summary>
        public SkryptObject Invoke(string name, params object[] arguments)
        {
            var parameters    = new SkryptObject[arguments.Length];
            var foundMethod   = GetVariable(name, _engine.GlobalScope).Value;
            var input         = new List <SkryptObject>();
            var methodContext = new ScopeContext {
                ParentScope = _engine.GlobalScope
            };

            for (int i = 0; i < arguments.Length; i++)
            {
                object arg = arguments[i];

                if (arg.GetType() == typeof(int) || arg.GetType() == typeof(float) || arg.GetType() == typeof(double))
                {
                    parameters[i] = new Library.Native.System.Numeric(Convert.ToDouble(arg));
                }
                else if (arg.GetType() == typeof(string))
                {
                    parameters[i] = new Library.Native.System.String((string)arg);
                }
                else if (arg.GetType() == typeof(bool))
                {
                    parameters[i] = new Library.Native.System.Boolean((bool)arg);
                }
                else if (arg == null)
                {
                    parameters[i] = new Library.Native.System.Null();
                }

                parameters[i].GetPropertiesFrom(GetType(((SkryptType)parameters[i]).TypeName, _engine.GlobalScope));

                input.Add(parameters[i]);
            }

            ScopeContext methodScopeResult = null;

            if (foundMethod.GetType() == typeof(UserFunction))
            {
                UserFunction method = (UserFunction)foundMethod;

                for (var i = 0; i < method.Parameters.Count; i++)
                {
                    var          parName = method.Parameters[i];
                    SkryptObject inp;

                    inp = i < input.Count ? input[i] : new Library.Native.System.Null();

                    methodContext.Variables[parName] = new Variable {
                        Name  = parName,
                        Value = inp,
                        Scope = methodContext
                    };
                }

                methodScopeResult = method.Execute(_engine, null, input.ToArray(), methodContext);
            }
            else if (foundMethod.GetType() == typeof(SharpMethod))
            {
                methodScopeResult = ((SharpMethod)foundMethod).Execute(_engine, null, input.ToArray(), methodContext);
            }
            else
            {
                _engine.ThrowError("Cannot call value, as it is not a function!");
            }

            return(methodScopeResult.ReturnObject);
        }