Esempio n. 1
0
        public override object Eval(TemplateContext context)
        {
            object val = null;

            for (int i = 0; i < parts.Count; i++)
            {
                // get variable from context
                if (i == 0 && !parts[i].IsMethod)
                {
                    val = EvalContextVariable(parts[i], context);
                }
                // call built-in function
                else if (i == 0 && parts[i].IsMethod)
                {
                    BuiltinFunctions target = new BuiltinFunctions();
                    target.Context = context;
                    target.Line    = parts[i].Line;
                    target.Column  = parts[i].Column;
                    val            = EvalMethod(target, parts[i], context);
                }
                // call public property
                else if (i > 0 && !parts[i].IsMethod) // property
                {
                    val = EvalProperty(val, parts[i], context);
                }
                // call public method
                else if (i > 0 && parts[i].IsMethod) // property
                {
                    val = EvalMethod(val, parts[i], context);
                }
            }

            return(val);
        }
Esempio n. 2
0
        /// <summary>
        /// Gets a <see cref="ScriptObject"/> with all default builtins registered.
        /// </summary>
        /// <returns>A <see cref="ScriptObject"/> with all default builtins registered</returns>
        public static ScriptObject GetDefaultBuiltinObject()
        {
            var builtinObject = new ScriptObject();

            BuiltinFunctions.Register(builtinObject);
            return(builtinObject);
        }
        public override object Eval(TemplateContext context)
        {
            object val = null;
            for (int i = 0; i < parts.Count; i++)
            {
                // get variable from context
                if (i == 0 && !parts[i].IsMethod)
                {
                    val = EvalContextVariable(parts[i], context);
                }
                // call built-in function
                else if (i == 0 && parts[i].IsMethod)
                {
                    BuiltinFunctions target = new BuiltinFunctions();
                    target.Context = context;
                    target.Line = parts[i].Line;
                    target.Column = parts[i].Column;
                    val = EvalMethod(target, parts[i], context);
                }
                // call public property
                else if(i > 0 && !parts[i].IsMethod) // property
                {
                    val = EvalProperty(val, parts[i], context);
                }
                // call public method
                else if (i > 0 && parts[i].IsMethod) // property
                {
                    val = EvalMethod(val, parts[i], context);
                }
            }

            return val;
        }
Esempio n. 4
0
        public IEnumerable <Symbol> GetSymbols()
        {
            var submission       = this;
            var seenSymbolNames  = new HashSet <string>();
            var builtinFunctions = BuiltinFunctions.GetAll();

            while (submission != null)
            {
                foreach (var function in submission.Functions)
                {
                    if (seenSymbolNames.Add(function.Name))
                    {
                        yield return(function);
                    }
                }

                foreach (var variable in submission.Variables)
                {
                    if (seenSymbolNames.Add(variable.Name))
                    {
                        yield return(variable);
                    }
                }

                foreach (var builtin in builtinFunctions)
                {
                    if (seenSymbolNames.Add(builtin.Name))
                    {
                        yield return(builtin);
                    }
                }

                submission = submission.Previous;
            }
        }
Esempio n. 5
0
 internal FunctionLibrary(FormulaEngine owner)
 {
     _owner            = owner;
     _builtinFunctions = new BuiltinFunctions();
     _functions        = new Hashtable(StringComparer.OrdinalIgnoreCase);
     AddBuiltinFunctions();
 }
Esempio n. 6
0
        public IEnumerable <Symbol> GetSymbols()
        {
            var submission      = this;
            var seenSymbolNames = new HashSet <string>();

            var builtinFunctions = BuiltinFunctions.GetAll().ToList();

            while (submission != null)
            {
                foreach (var @class in submission.Classes.Where(@class => seenSymbolNames.Add(@class.Name)))
                {
                    yield return(@class);
                }

                foreach (var function in submission.Functions.Where(function => seenSymbolNames.Add(function.Name)))
                {
                    yield return(function);
                }

                foreach (var variable in submission.Variables.Where(variable => seenSymbolNames.Add(variable.Name)))
                {
                    yield return(variable);
                }

                foreach (var builtin in builtinFunctions.Where(builtin => seenSymbolNames.Add(builtin.Name)))
                {
                    yield return(builtin);
                }

                submission = submission.Previous;
            }
        }
Esempio n. 7
0
        private static void MatMul([Global] float[] A, [Global] float[] B, [Global] float[] C,
                                   [Shared] float[] As, [Shared] float[] Bs, uint wA, uint wB)
        {
            // Thread index
            uint tx = ThreadIdx.X;
            uint ty = ThreadIdx.Y;

            // Index of the first sub-matrix of A processed by the block
            uint aBegin = wA * BLOCK_SIZE * BlockIdx.Y;

            // Index of the last sub-matrix of A processed by the block
            uint aEnd = aBegin + wA - 1;

            // Step size used to iterate through the sub-matrices of A
            uint aStep = BLOCK_SIZE;

            // Index of the first sub-matrix of B processed by the block
            uint bBegin = BLOCK_SIZE * BlockIdx.X;

            // Step size used to iterate through the sub-matrices of B
            uint bStep = BLOCK_SIZE * wB;

            // Csub is used to store the element of the block sub-matrix
            // that is computed by the thread
            float Csub = 0;

            // Loop over all the sub-matrices of A and B
            // required to compute the block sub-matrix
            for (uint a = aBegin, b = bBegin; a <= aEnd; a += aStep, b += bStep)
            {
                // Load the matrices from device memory
                // to shared memory; each thread loads
                // one element of each matrix
                As[ty * BLOCK_SIZE + tx] = A[a + wA * ty + tx];
                Bs[ty * BLOCK_SIZE + tx] = B[b + wB * ty + tx];

                // Synchronize to make sure the matrices are loaded
                BuiltinFunctions.SyncThreads();

                // Multiply the two matrices together;
                // each thread computes one element
                // of the block sub-matrix
                for (uint k = 0; k < BLOCK_SIZE; ++k)
                {
                    Csub += As[ty * BLOCK_SIZE + k] * Bs[k * BLOCK_SIZE + tx];
                }

                // Synchronize to make sure that the preceding
                // computation is done before loading two new
                // sub-matrices of A and B in the next iteration
                BuiltinFunctions.SyncThreads();
            }

            // Write the block sub-matrix to device memory;
            // each thread writes one element
            uint c = wB * BLOCK_SIZE * BlockIdx.Y + BLOCK_SIZE * BlockIdx.X;

            C[c + wB * ty + tx] = Csub;
        }
Esempio n. 8
0
    private BoundExpression BindCallExpression(CallExpressionSyntax syntax)
    {
        if (syntax.Arguments.Count == 1 && TypeSymbol.Lookup(syntax.Identifier.Text) is TypeSymbol type)
        {
            return(this.BindConversion(syntax.Arguments[0], type, allowExplicit: true));
        }

        var functions = BuiltinFunctions.GetAll();
        var function  = functions.SingleOrDefault(_ => _.Name == syntax.Identifier.Text);

        if (function == null)
        {
            this.Diagnostics.ReportUndefinedFunction(syntax.Identifier);
            return(new BoundErrorExpression(syntax));
        }

        if (syntax.Arguments.Count != function.Parameters.Length)
        {
            this.Diagnostics.ReportWrongArgumentCount(syntax.Location, function.Name,
                                                      function.Parameters.Length, syntax.Arguments.Count);
            return(new BoundErrorExpression(syntax));
        }

        var boundArguments = ImmutableArray.CreateBuilder <BoundExpression>();

        foreach (var argument in syntax.Arguments)
        {
            var boundArgument = this.BindExpression(argument);
            boundArguments.Add(boundArgument);
        }

        for (var i = 0; i < syntax.Arguments.Count; i++)
        {
            var argumentLocation = syntax.Arguments[i].Location;
            var argument         = boundArguments[i];
            var parameter        = function.Parameters[i];
            boundArguments[i] = this.BindConversion(argumentLocation, argument, parameter.Type);
        }

        if (function == BuiltinFunctions.E || function == BuiltinFunctions.N)
        {
            if (boundArguments[0] is BoundLiteralExpression literalArgument &&
                literalArgument.Type == TypeSymbol.Integer)
            {
                var targetLineNumber = (BigInteger)literalArgument.Value;
                this.LineNumberValidations.Add((targetLineNumber, syntax.Arguments[0].Location));
            }
        }

        if (function == BuiltinFunctions.Defer)
        {
            this.deferWasInvoked = syntax;
            this.doesStatementExistAfterDefer = false;
        }

        return(new BoundCallExpression(syntax, function, boundArguments.ToImmutable()));
    }
Esempio n. 9
0
        private static void PoissonRBSOR_LMem([Global] float[] grid, [Global] float[] laplacian,
                                              int dimX, int dimY, int gstride, int lstride,
                                              float hx, float hy, float omega, int color,
                                              [Shared] float[] buf)
        {
            int threadIdxX = (int)ThreadIdx.X;
            int threadIdxY = (int)ThreadIdx.Y;
            int blockDimX  = (int)BlockDim.X;
            int blockDimY  = (int)BlockDim.Y;
            int blockIdxX  = (int)BlockIdx.X;
            int blockIdxY  = (int)BlockIdx.Y;

            int col_cnt = BuiltinFunctions.Min(AREA_SIZE_X + 2, dimX - blockIdxX * AREA_SIZE_X);
            int row_cnt = BuiltinFunctions.Min(AREA_SIZE_Y + 2, dimY - blockIdxY * AREA_SIZE_Y);

            for (int row = threadIdxY; row < row_cnt; row += blockDimY)
            {
                int x     = threadIdxX + blockIdxX * AREA_SIZE_X;
                int y     = row + blockIdxY * AREA_SIZE_Y;
                int index = x + y * gstride;
                for (int col = threadIdxX; col < col_cnt; col += blockDimX, index += blockDimX)
                {
                    buf[IdxBuf(row, col)] = grid[index];
                }
            }

            BuiltinFunctions.SyncThreads();

            col_cnt -= 2;
            row_cnt -= 2;

            int col_start = 2 * threadIdxX;
            int col_delta = 2 * blockDimX;

            float b  = 2 * hx * hy;
            float a1 = 2 * hy / hx;
            float a2 = 2 * hx / hy;
            float p  = 0.5f * omega / (a1 + a2);
            float q  = 1 - omega;

            for (int row = threadIdxY; row < row_cnt; row += blockDimY)
            {
                int col_offset = col_start + (color + row) % 2;
                int x          = col_offset + blockIdxX * AREA_SIZE_X;
                int y          = row + blockIdxY * AREA_SIZE_Y;
                int index      = x + 1 + (y + 1) * gstride;

                for (int col = col_offset; col < col_cnt; col += col_delta, index += col_delta, x += col_delta)
                {
                    grid[index] = (b * laplacian[x + y * lstride] +
                                   a1 * (buf[IdxBuf(row + 2, col + 1)] + buf[IdxBuf(row, col + 1)]) +
                                   a2 * (buf[IdxBuf(row + 1, col + 2)] + buf[IdxBuf(row + 1, col)])) * p +
                                  buf[IdxBuf(row + 1, col + 1)] * q;
                }
            }
        }
Esempio n. 10
0
        private static BoundScope CreateRootScope()
        {
            var result = new BoundScope(null);

            foreach (var f in BuiltinFunctions.GetAll())
            {
                result.TryDeclareFunction(f);
            }

            return(result);
        }
        public LocalJamList InvokeRule(JamListBase jamList, params JamListBase[] arguments)
        {
            // Todo: Invoke multiple rules?
            var result = new List <string>();

            foreach (var rule in jamList.Elements)
            {
                result.AddRange(BuiltinFunctions.InvokeRule(rule, arguments).Elements);
            }

            return(new LocalJamList(result.ToArray()));
        }
Esempio n. 12
0
        private Action <IStore> PopulateScope(params string[] names)
        {
            return((s) =>
            {
                IFunction function;

                foreach (string name in names)
                {
                    if (!BuiltinFunctions.TryGet(name, out function))
                    {
                        continue;
                    }

                    s[name] = new FunctionValue(function);
                }
            });
        }
Esempio n. 13
0
        private BoundExpression BindCallExpression(CallExpressionSyntax syntax)
        {
            var arguments = ImmutableArray.CreateBuilder <BoundExpression>();

            foreach (var argument in syntax.Arguments)
            {
                var boundArgument = BindExpression(argument);

                arguments.Add(boundArgument);
            }

            var functions = BuiltinFunctions.GetAll();

            var function = functions.SingleOrDefault(f => f.Name == syntax.IdentifierToken.Text);

            if (function == null)
            {
                _diagnostics.ReportUndefinedFunction(syntax.IdentifierToken.Span, syntax.IdentifierToken.Text);

                return(new BoundErrorExpression());
            }

            if (syntax.Arguments.Count != function.Parameters.Length)
            {
                _diagnostics.ReportIncorrectArgumentCount(syntax.Span, function.Name, function.Parameters.Length, syntax.Arguments.Count);

                return(new BoundErrorExpression());
            }

            for (var i = 0; i < function.Parameters.Length; i++)
            {
                var parameter = function.Parameters[i];
                var argument  = arguments[i];

                if (parameter.Type != argument.Type)
                {
                    _diagnostics.ReportTypeMismatch(syntax.Span, argument.Type, function.Parameters[i].Type);

                    return(new BoundErrorExpression());
                }
            }

            return(new BoundCallExpression(function, arguments.ToImmutable()));
        }
Esempio n. 14
0
        private static void PoissonJacobi([Global] float[] input, [Global] float[] output, [Shared] float[] buf,
                                          uint dimX, uint dimY, uint stride,
                                          float a1, float a2, float a3, float a4, float a,
                                          float hx, float hy, float x0, float y0)
        {
            uint col_cnt = BuiltinFunctions.Min(AREA_SIZE_X + 2, dimX - BlockIdx.X * AREA_SIZE_X);
            uint row_cnt = BuiltinFunctions.Min(AREA_SIZE_Y + 2, dimY - BlockIdx.Y * AREA_SIZE_Y);

            for (uint row = ThreadIdx.Y; row < row_cnt; row += BlockDim.Y)
            {
                uint x   = ThreadIdx.X + BlockIdx.X * AREA_SIZE_X;
                uint y   = row + BlockIdx.Y * AREA_SIZE_Y;
                uint idx = x + y * stride;
                for (uint col = ThreadIdx.X; col < col_cnt; col += BlockDim.X, idx += BlockDim.X)
                {
                    buf[IdxBuf(row, col)] = input[idx];
                }
            }

            BuiltinFunctions.SyncThreads();

            col_cnt -= 2;
            row_cnt -= 2;

            for (uint row = ThreadIdx.Y; row < row_cnt; row += BlockDim.Y)
            {
                uint x   = 1 + ThreadIdx.X + BlockIdx.X * AREA_SIZE_X;
                uint y   = 1 + row + BlockIdx.Y * AREA_SIZE_Y;
                uint idx = x + y * stride;
                for (uint col = ThreadIdx.X; col < col_cnt; col += BlockDim.X, idx += BlockDim.X, x += BlockDim.X)
                {
                    float F = 2 * hx * hy * J(x0 + x * hx, y0 + y * hy);
                    output[idx] = (a1 * buf[IdxBuf(row + 2, col + 1)] + a2 * buf[IdxBuf(row + 1, col + 2)] +
                                   a3 * buf[IdxBuf(row, col + 1)] + a4 * buf[IdxBuf(row + 1, col)] + F) / a;
                }
            }
        }
Esempio n. 15
0
        public override void Visit(Function function)
        {
            // if raw result is preferred, display functions as it is
            if ((Options & EvaluateOptions.RawResult) == EvaluateOptions.RawResult)
            {
                throw new RawExpressionException();
            }

            var args = new FunctionArgs
            {
                Parameters = new Expression[function.Expressions.Length]
            };

            // Don't call parameters right now, instead let the function do it as needed.
            // Some parameters shouldn't be called, for instance, in a if(), the "not" value might be a division by zero
            // Evaluating every value could produce unexpected behaviour
            for (int i = 0; i < function.Expressions.Length; i++)
            {
                args.Parameters[i] = new Expression(function.Expressions[i], _options);
                args.Parameters[i].EvaluateFunction  += EvaluateFunction;
                args.Parameters[i].EvaluateParameter += EvaluateParameter;

                // Assign the parameters of the Expression to the arguments so that custom Functions and Parameters can use them
                args.Parameters[i].Parameters = Parameters;
            }

            // Calls external implementation
            OnEvaluateFunction(IgnoreCase ? function.Identifier.Name.ToLower() : function.Identifier.Name, args);

            // If an external implementation was found get the result back
            if (args.HasResult)
            {
                Result = args.Result;
                return;
            }

            string functionName = function.Identifier.Name.ToLower();

            if (BuiltinFunctions.Has(functionName))
            {
                Result = BuiltinFunctions.ValidateAndEvaluate(functionName, function, this);
            }
            else
            {
                throw new ArgumentException("Function not found",
                                            function.Identifier.Name);
            }

            /*
             * switch (function.Identifier.Name.ToLower())
             * {
             #region Abs
             *  case "abs":
             *
             *      CheckCase("Abs", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Abs() takes exactly 1 argument");
             *
             *      Result = Math.Abs(Convert.ToDecimal(
             *          Evaluate(function.Expressions[0]))
             *          );
             *
             *      break;
             *
             #endregion
             *
             #region Acos
             *  case "acos":
             *
             *      CheckCase("Acos", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Acos() takes exactly 1 argument");
             *
             *      Result = Math.Acos(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Asin
             *  case "asin":
             *
             *      CheckCase("Asin", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Asin() takes exactly 1 argument");
             *
             *      Result = Math.Asin(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Atan
             *  case "atan":
             *
             *      CheckCase("Atan", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Atan() takes exactly 1 argument");
             *
             *      Result = Math.Atan(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Ceiling
             *  case "ceiling":
             *
             *      CheckCase("Ceiling", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Ceiling() takes exactly 1 argument");
             *
             *      Result = Math.Ceiling(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Cos
             *
             *  case "cos":
             *
             *      CheckCase("Cos", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Cos() takes exactly 1 argument");
             *
             *      Result = Math.Cos(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Exp
             *  case "exp":
             *
             *      CheckCase("Exp", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Exp() takes exactly 1 argument");
             *
             *      Result = Math.Exp(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Floor
             *  case "floor":
             *
             *      CheckCase("Floor", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Floor() takes exactly 1 argument");
             *
             *      Result = Math.Floor(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region IEEERemainder
             *  case "ieeeremainder":
             *
             *      CheckCase("IEEERemainder", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 2)
             *          throw new ArgumentException("IEEERemainder() takes exactly 2 arguments");
             *
             *      Result = Math.IEEERemainder(Convert.ToDouble(Evaluate(function.Expressions[0])), Convert.ToDouble(Evaluate(function.Expressions[1])));
             *
             *      break;
             *
             #endregion
             *
             #region Log
             *  case "log":
             *
             *      CheckCase("Log", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 2)
             *          throw new ArgumentException("Log() takes exactly 2 arguments");
             *
             *      Result = Math.Log(Convert.ToDouble(Evaluate(function.Expressions[0])), Convert.ToDouble(Evaluate(function.Expressions[1])));
             *
             *      break;
             *
             #endregion
             *
             #region Log10
             *  case "log10":
             *
             *      CheckCase("Log10", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Log10() takes exactly 1 argument");
             *
             *      Result = Math.Log10(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Pow
             *  case "pow":
             *
             *      CheckCase("Pow", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 2)
             *          throw new ArgumentException("Pow() takes exactly 2 arguments");
             *
             *      Result = Math.Pow(Convert.ToDouble(Evaluate(function.Expressions[0])), Convert.ToDouble(Evaluate(function.Expressions[1])));
             *
             *      break;
             *
             #endregion
             *
             #region Round
             *  case "round":
             *
             *      CheckCase("Round", function.Identifier.Name);
             *
             *      if (!(function.Expressions.Length == 2 || function.Expressions.Length == 1))
             *          throw new ArgumentException("Round() takes 1 or 2 arguments");
             *
             *      int digits = 0;
             *      if (function.Expressions.Length == 2)
             *      {
             *          digits = Convert.ToInt16(Evaluate(function.Expressions[1]));
             *      }
             *
             *      MidpointRounding rounding = (_options & EvaluateOptions.RoundAwayFromZero) == EvaluateOptions.RoundAwayFromZero ? MidpointRounding.AwayFromZero : MidpointRounding.ToEven;
             *
             *      Result = Math.Round(Convert.ToDouble(Evaluate(function.Expressions[0])), digits, rounding);
             *
             *      break;
             *
             #endregion
             *
             #region Sign
             *  case "sign":
             *
             *      CheckCase("Sign", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Sign() takes exactly 1 argument");
             *
             *      Result = Math.Sign(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Sin
             *  case "sin":
             *
             *      CheckCase("Sin", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Sin() takes exactly 1 argument");
             *
             *      Result = Math.Sin(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Sqrt
             *  case "sqrt":
             *
             *      CheckCase("Sqrt", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Sqrt() takes exactly 1 argument");
             *
             *      Result = Math.Sqrt(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Tan
             *  case "tan":
             *
             *      CheckCase("Tan", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Tan() takes exactly 1 argument");
             *
             *      Result = Math.Tan(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Truncate
             *  case "truncate":
             *
             *      CheckCase("Truncate", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 1)
             *          throw new ArgumentException("Truncate() takes exactly 1 argument");
             *
             *      Result = Math.Truncate(Convert.ToDouble(Evaluate(function.Expressions[0])));
             *
             *      break;
             *
             #endregion
             *
             #region Max
             *  case "max":
             *
             *      CheckCase("Max", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 2)
             *          throw new ArgumentException("Max() takes exactly 2 arguments");
             *
             *      object maxleft = Evaluate(function.Expressions[0]);
             *      object maxright = Evaluate(function.Expressions[1]);
             *
             *      Result = Numbers.Max(maxleft, maxright);
             *      break;
             *
             #endregion
             *
             #region Min
             *  case "min":
             *
             *      CheckCase("Min", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 2)
             *          throw new ArgumentException("Min() takes exactly 2 arguments");
             *
             *      object minleft = Evaluate(function.Expressions[0]);
             *      object minright = Evaluate(function.Expressions[1]);
             *
             *      Result = Numbers.Min(minleft, minright);
             *      break;
             *
             #endregion
             *
             #region if
             *  case "if":
             *
             *      CheckCase("if", function.Identifier.Name);
             *
             *      if (function.Expressions.Length != 3)
             *          throw new ArgumentException("if() takes exactly 3 arguments");
             *
             *      bool cond = Convert.ToBoolean(Evaluate(function.Expressions[0]));
             *
             *      Result = cond ? Evaluate(function.Expressions[1]) : Evaluate(function.Expressions[2]);
             *      break;
             *
             #endregion
             *
             #region in
             *  case "in":
             *
             *      CheckCase("in", function.Identifier.Name);
             *
             *      if (function.Expressions.Length < 2)
             *          throw new ArgumentException("in() takes at least 2 arguments");
             *
             *      object parameter = Evaluate(function.Expressions[0]);
             *
             *      bool evaluation = false;
             *
             *      // Goes through any values, and stop whe one is found
             *      for (int i = 1; i < function.Expressions.Length; i++)
             *      {
             *          object argument = Evaluate(function.Expressions[i]);
             *          if (CompareUsingMostPreciseType(parameter, argument) == 0)
             *          {
             *              evaluation = true;
             *              break;
             *          }
             *      }
             *
             *      Result = evaluation;
             *      break;
             *
             #endregion
             *
             *  default:
             *      throw new ArgumentException("Function not found",
             *          function.Identifier.Name);
             * }*/
        }
Esempio n. 16
0
 private static float J(float x, float y)
 {
     return(BuiltinFunctions.Sin(x * y) * (x * x + y * y));
 }
Esempio n. 17
0
 private FunctionLibrary(SerializationInfo info, StreamingContext context)
 {
     _owner            = (FormulaEngine)info.GetValue("Owner", typeof(FormulaEngine));
     _builtinFunctions = (BuiltinFunctions)info.GetValue("BuiltinFunctions", typeof(BuiltinFunctions));
     _functions        = (IDictionary)info.GetValue("Functions", typeof(IDictionary));
 }
Esempio n. 18
0
        public override void Visit(Function function)
        {
            var args = new FunctionArgs
            {
                Parameters = new Expression[function.Expressions.Length]
            };

            // Don't call parameters right now, instead let the function do it as needed.
            // Some parameters shouldn't be called, for instance, in a if(), the "not" value might be a division by zero
            // Evaluating every value could produce unexpected behaviour
            for (int i = 0; i < function.Expressions.Length; i++)
            {
                args.Parameters[i] = new Expression(function.Expressions[i], _options);
                args.Parameters[i].EvaluateFunction  += EvaluateFunction;
                args.Parameters[i].EvaluateParameter += EvaluateParameter;

                // Assign the parameters of the Expression to the arguments so that custom Functions and Parameters can use them
                args.Parameters[i].Parameters = Parameters;
            }

            // Calls external implementation
            bool found = OnValidateFunction(IgnoreCase ? function.Identifier.Name.ToLower() : function.Identifier.Name, args);

            string[][] tempVariables = null;
            // validate builtin function
            if (!found)
            {
                string functionName = function.Identifier.Name.ToLower();
                if (BuiltinFunctions.Has(functionName))
                {
                    BuiltinFunctions.Validate(functionName, function);
                    found         = true;
                    tempVariables = BuiltinFunctions.TempVariables(functionName);
                }
            }

            if (!found)
            {
                // function not found OR parameter is invalid
                throw new Exception("Function \"" + function.Identifier.Name + "\" not defined");
            }

            Result.Append(function.Identifier.Name);

            Result.Append("(");

            for (int i = 0; i < function.Expressions.Length; i++)
            {
                string[] tempVars = null;
                if (tempVariables != null && i < tempVariables.Length)
                {
                    tempVars = tempVariables[i];
                    if (tempVars != null)
                    {
                        foreach (string var in tempVars)
                        {
                            this.Parameters[var] = new RawIdentifierExpression(var);
                        }
                    }
                }
                function.Expressions[i].Accept(this);
                if (tempVars != null)
                {
                    foreach (string var in tempVars)
                    {
                        this.Parameters.Remove(var);
                    }
                }
                if (i < function.Expressions.Length - 1)
                {
                    Result.Append(",");
                }
            }

            // trim spaces before adding a closing paren
            while (Result[Result.Length - 1] == ' ')
            {
                Result.Remove(Result.Length - 1, 1);
            }

            Result.Append(")");
        }
 public void DynamicInclude(JamListBase value)
 {
     BuiltinFunctions.Include(value);
 }
 public override AbstractStatementNode ReleaseInstruction()
 {
     return(BuiltinFunctions.RecoverMemory(new AddressableIdentifierNode(this)));
 }
Esempio n. 21
0
    // Use this for initialization
    public void Start()
    {
        Debug.Assert(CurrentStatus == Status.NotInitialized);
        Debug.Assert(GameInstance == null);
        DontDestroyOnLoad(gameObject);
        GameInstance  = this;
        CurrentStatus = Status.Initializing;

        GlobalUI.OnAcquireJson("{}");

        var audioSources = GetComponents <AudioSource>();

        MusicAudioSource = audioSources[0];
        SoundAudioSource = audioSources[1];

        GlobalImageScaleFactor  = 1.5f;
        GlobalMusicVolume       = 1f;
        GlobalSoundEffectVolume = 1f;

        GameLogger      = new Logger(new GameLogHandler(LogFilePath));
        ResourceManager = new ResourceManager();
        ResourceManager.AddResourceDataProvider(new LocalFileProvider(DataPath));

        Bound           = gameObject.AddComponent <BoxCollider>();
        Bound.isTrigger = true;

        LuaVM = new LuaSvr();
        LuaVM.init(null, () =>
        {
            var l = LuaVM.luaState.L;

            LuaDLL.lua_pushglobaltable(l);
            LuaTable globalTable;
            LuaObject.checkType(l, -1, out globalTable);
            if (globalTable == null)
            {
                throw new Exception("Cannot get global table");
            }
            GlobalTable = globalTable;
            LuaDLL.lua_pop(l, 1);

            LuaDLL.lua_gc(l, LuaGCOptions.LUA_GCSTOP, 0);

            LuaDLL.luaL_openlibs(l);

            BuiltinFunctions.Register(l);
            BuiltinFunctions.InitMetaTable(l);

            LuaDLL.lua_gc(l, LuaGCOptions.LUA_GCRESTART, -1);

            ResourceManager.FindResourceAs <ResLuaScript>("launch").Execute(LuaVM.luaState);
            ResourceManager.FindResourceAs <ResLuaScript>("core.lua").Execute(LuaVM.luaState);

            var gameInit = globalTable["GameInit"] as LuaFunction;
            if (gameInit == null)
            {
                throw new Exception("GameInit does not exist or is not a function");
            }

            _gameExitFunc = globalTable["GameExit"] as LuaFunction;
            if (_gameExitFunc == null)
            {
                throw new Exception("GameExit does not exist or is not a function");
            }

            _focusLoseFunc = globalTable["FocusLoseFunc"] as LuaFunction;
            if (_focusLoseFunc == null)
            {
                throw new Exception("FocusLoseFunc does not exist or is not a function");
            }

            _focusGainFunc = globalTable["FocusGainFunc"] as LuaFunction;
            if (_focusGainFunc == null)
            {
                throw new Exception("FocusGainFunc does not exist or is not a function");
            }

            _frameFunc = globalTable["FrameFunc"] as LuaFunction;
            if (_frameFunc == null)
            {
                throw new Exception("FrameFunc does not exist or is not a function");
            }

            _renderFunc = globalTable["RenderFunc"] as LuaFunction;
            if (_renderFunc == null)
            {
                throw new Exception("RenderFunc does not exist or is not a function");
            }

            gameInit.call();

            CurrentStatus = Status.Initialized;
        });
    }
        private void Generate(AbstractNode node)
        {
            var debugNodeTypes = new NodeType[]
            {
                /*NodeType.Block,
                 * NodeType.Literal,
                 * NodeType.Identifier,
                 * NodeType.Loop,
                 * NodeType.Operation,*/
            };

            if (debugNodeTypes.Contains(node.Type))
            {
                Debug(node.ToString());
            }
            switch (node.Type)
            {
            case NodeType.Block:
                ((BlockNode)node).Statements.ForEach(Generate);
                break;

            case NodeType.Operation:
                var operation = (OperationNode)node;

                // Operations that require two integer as input
                var integerOperations = new[]
                {
                    OperatorType.BitwiseAnd,
                    OperatorType.AndAlso,
                    OperatorType.BitwiseOr,
                    OperatorType.OrElse
                };

                var outputIntegerOperations = new[]
                {
                    OperatorType.Equals,
                    OperatorType.Greater,
                    OperatorType.NotGreater,
                    OperatorType.Less,
                    OperatorType.NotLess,
                    OperatorType.NotEquals
                };

                /*
                 *  We accept floating only, sometimes we need integer (logical and/or)
                 *  In this case, we cast the floating into an integer and cast back the result into a floating one.
                 */
                var requireInteger         = integerOperations.Contains(operation.Operator);
                var requireOutputTransform = outputIntegerOperations.Contains(operation.Operator);

                Generate(operation.LeftOperand);
                if (requireInteger)
                {
                    Write("ftoi");
                }

                Generate(operation.RightOperand);
                if (requireInteger)
                {
                    Write("ftoi");
                }

                switch (operation.Operator)
                {
                case OperatorType.Add:
                    Write("add.f");
                    break;

                case OperatorType.Sub:
                    Write("sub.f");
                    break;

                case OperatorType.Mul:
                    Write("mul.f");
                    break;

                case OperatorType.Div:
                    Write("div.f");
                    break;

                case OperatorType.BitwiseAnd:
                case OperatorType.AndAlso:
                    Write("and");
                    break;

                case OperatorType.BitwiseOr:
                case OperatorType.OrElse:
                    Write("or");
                    break;

                case OperatorType.Equals:
                    Write("cmpeq.f");
                    break;

                case OperatorType.NotEquals:
                    Write("cmpne.f");
                    break;

                case OperatorType.NotGreater:
                    Write("cmple.f");
                    break;

                case OperatorType.Less:
                    Write("cmplt.f");
                    break;

                case OperatorType.NotLess:
                    Write("cmpge.f");
                    break;

                case OperatorType.Greater:
                    Write("cmpgt.f");
                    break;

                case OperatorType.EuclidianDiv:
                    Write(Drop());
                    Write(Drop());
                    Generate(BuiltinFunctions.EuclidianDiv(operation.LeftOperand, operation.RightOperand));
                    break;

                case OperatorType.Mod:
                    Write(Drop());
                    Write(Drop());
                    Generate(BuiltinFunctions.Mod(operation.LeftOperand, operation.RightOperand));
                    break;

                case OperatorType.Pow:
                    Write(Drop());
                    Write(Drop());
                    Generate(BuiltinFunctions.Pow(operation.LeftOperand, operation.RightOperand));
                    break;
                }
                if (requireInteger || requireOutputTransform)
                {
                    Write("itof");
                }
                break;

            case NodeType.Declaration:
                var dcl = (AddressableDeclarationNode)node;
                switch (dcl.Identifier.Symbol.Type)
                {
                case ObjectType.Floating:
                    Generate(dcl.Expression);
                    Write
                    (
                        Set(dcl.Identifier.Symbol.Pointer)
                    );
                    break;

                case ObjectType.Pointer:
                    var indexExpressions = ((MultiExpressionNode)dcl.Expression).Expressions;
                    indexExpressions.Reverse();
                    AbstractExpressionNode finalExpression = LiteralNode.One;
                    for (var i = 0; i < indexExpressions.Count - 1; i++)
                    {
                        finalExpression = new OperationNode
                                          (
                            OperatorType.Mul,
                            new OperationNode
                            (
                                OperatorType.Add,
                                LiteralNode.One,
                                indexExpressions[i]
                            ),
                            finalExpression
                                          );
                    }
                    finalExpression = new OperationNode
                                      (
                        OperatorType.Mul,
                        indexExpressions.Last(),
                        finalExpression
                                      );
                    Generate(BuiltinFunctions.BorrowMemory(finalExpression));
                    Write(Set(dcl.Identifier.Symbol.Pointer));
                    var tempVar = new AddressableIdentifierNode(new PrimitiveVariableSymbol("", PointerIndex + 1));
                    Write(Pushf());
                    Generate(BuiltinFunctions.BorrowMemory(new LiteralNode(indexExpressions.Count)));
                    Write(Set(tempVar.Symbol.Pointer));
                    indexExpressions.Reverse();
                    for (var i = 0; i < indexExpressions.Count; i++)
                    {
                        Generate
                        (
                            new PointerAssignationNode
                            (
                                new OperationNode
                                (
                                    OperatorType.Add,
                                    tempVar,
                                    new LiteralNode(i)
                                ),
                                indexExpressions[i]
                            )
                        );
                    }

                    /*
                     *      var a = bmem(6);
                     *      var b = bmem(2);
                     *      :b = 2;
                     *      :b + 1 = 2;
                     *      init_array(a, b, 2);
                     */
                    Generate(BuiltinFunctions.InitArray(dcl.Identifier, tempVar, new LiteralNode(indexExpressions.Count)));
                    Write(Get(tempVar.Symbol.Pointer));
                    Generate(BuiltinFunctions.RecoverMemory(tempVar));
                    break;
                }
                break;

            case NodeType.Reference:
                var refnode = (ReferenceNode)node;
                Write
                (
                    Pushf(refnode.Identifier.Symbol.Pointer)
                );
                break;

            case NodeType.Dereference:
                var deref = (DereferenceNode)node;
                Generate(deref.Expression);
                Writes
                (
                    Ftoi(),
                    MemRead(),
                    Itof()
                );
                break;

            case NodeType.Assignation:
                var assign = (AssignationNode)node;
                Generate(assign.ValueExpression);
                Write
                (
                    Set(assign.Identifier.Symbol.Pointer)
                );
                break;

            case NodeType.Drop:
                Write(Drop());
                break;

            case NodeType.PointerAssignation:
                var ptrAssign = (PointerAssignationNode)node;
                Generate(ptrAssign.AddressExpression);
                Write
                (
                    Ftoi()
                );
                Generate(ptrAssign.ValueExpression);
                Writes
                (
                    Ftoi(),
                    MemWrite()
                );
                break;

            case NodeType.Literal:
                var lit = (LiteralNode)node;
                Write(Pushf(lit.Value));
                break;

            case NodeType.Identifier:
                var ident = (AddressableIdentifierNode)node;
                Write
                (
                    Get(ident.Symbol.Pointer)
                );
                break;

            case NodeType.Crash:
                Write("halt");
                break;

            case NodeType.Print:
                if (node is PrintExpressionNode)
                {
                    var printe = (PrintExpressionNode)node;
                    Generate(printe.Expression);
                    Write("out.f");
                }
                else
                {
                    var prints = (PrintStringNode)node;
                    foreach (var c in prints.Content)
                    {
                        Write($"push.i {(int)c}");
                        Write("out.c");
                    }
                }
                Write("push.i 10");
                Write("out.c");
                break;

            case NodeType.Loop:
                var loop = (LoopNode)node;
                {
                    Write(DeclareLabel(BeginLoop(loop.UniqueId)));
                    Generate(loop.Conditional);
                    Write(DeclareLabel(IterationLoop(loop.UniqueId)));
                    Generate(loop.Iteration);
                    Write(Jump(BeginLoop(loop.UniqueId)));
                    Write(DeclareLabel(EndLoop(loop.UniqueId)));
                }
                break;

            case NodeType.Break:
                var breakNode = (BreakNode)node;
                Write(Jump(EndLoop(breakNode.LoopId)));
                break;

            case NodeType.Continue:
                var cont = (ContinueNode)node;
                Write(Jump(EndIf(cont.CondId)));
                break;

            case NodeType.Conditional:
                var cond = (ConditionalNode)node;
                {
                    Generate(cond.Expression);
                    Write(JumpFalse(Else(cond.UniqueId)));
                    Generate(cond.TrueStatement);
                    Write(Jump(EndIf(cond.UniqueId)));
                    Write(DeclareLabel(Else(cond.UniqueId)));
                    Generate(cond.FalseStatement);
                    Write(DeclareLabel(EndIf(cond.UniqueId)));
                }
                break;

            case NodeType.MultiExpression:
                var multi = (MultiExpressionNode)node;
                foreach (var expression in multi.Expressions)
                {
                    Generate(expression);
                }
                break;

            case NodeType.Function:
                var fun = (FunctionNode)node;
                Write(DeclareLabel(fun.Identifier.Symbol.Name));
                PointerIndex = fun.Arguments.Count - 1;
                PreGenerate(fun.Statement);
                Generate(fun.Statement);
                if (fun.Identifier.Symbol.Name != "start")
                {
                    Write(Pushf());
                    Write(Ret());
                }
                else
                {
                    Write(Halt());
                }
                break;

            case NodeType.Return:
                var ret = (ReturnNode)node;
                Generate(ret.Expression);
                Write(Ret());
                break;

            case NodeType.Call:
                var call = (CallNode)node;
                Write(Prep(call.Target.Symbol.Name));
                foreach (var arg in call.Parameters)
                {
                    Generate(arg);
                }
                Write(Call(call.Parameters.Count));
                break;

            case NodeType.Root:
                var root = (RootNode)node;
                foreach (var f in root.Functions)
                {
                    Generate(f);
                }
                break;
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Gets a <see cref="ScriptObject"/> with all default builtins registered.
        /// </summary>
        /// <returns>A <see cref="ScriptObject"/> with all default builtins registered</returns>
        public static ScriptObject GetDefaultBuiltinObject()
        {
            BuiltinFunctions builtinObject = new BuiltinFunctions();

            return(builtinObject);
        }