Esempio n. 1
0
        async private Task Evaluate(S4JToken token)
        {
            if (token == null)
            {
                return;
            }

            bool canBeEvaluated = true;

            if (token.Tags.Count > 0 && TagExecutor != null)
            {
                using (ExecutorContext context = new ExecutorContext(token, GetExecutiongVariables(token)))
                    canBeEvaluated = TagExecutor(context);
            }

            token.IsVisible = canBeEvaluated;
            if (!canBeEvaluated)
            {
                return;
            }

            if (token.State.StateType == EStateType.FUNCTION)
            {
                await EvaluateFunction(token);
            }
            else
            {
                var children = token.Children.ToArray();
                for (var i = 0; i < children.Length; i++)
                {
                    S4JToken child = children[i];
                    await Evaluate(child);
                }
            }
        }
Esempio n. 2
0
 public ExecutorContext(
     S4JToken Token,
     IDictionary <String, object> Variables)
 {
     this.Token     = Token;
     this.Variables = Variables;
 }
Esempio n. 3
0
        async public Task <S4JToken> ExecuteWithParameters(S4JToken MethodDefinition, Dictionary <string, object> Parameters)
        {
            if (MethodDefinition is S4JTokenRoot root)
            {
                if (Parameters != null)
                {
                    foreach (string parameterName in Parameters.Keys)
                    {
                        root.Parameters[parameterName] = Parameters[parameterName];
                    }
                }

                // validate parameters
                foreach (var parameter in root.Parameters)
                {
                    S4JFieldDescription fieldDescription = null;
                    root.ParametersDefinitions.TryGetValue(parameter.Key, out fieldDescription);

                    if (fieldDescription != null)
                    {
                        fieldDescription.Validate(parameter.Value);
                    }
                }
            }

            await Evaluate(MethodDefinition);

            if (MethodDefinition is S4JTokenRoot)
            {
                return(MethodDefinition.Children.LastOrDefault());
            }

            return(MethodDefinition);
        }
Esempio n. 4
0
        async public Task <S4JToken> ExecuteWithParameters(S4JToken MethodDefinition, params Object[] Parameters)
        {
            Dictionary <string, object> parametersAsDict = new Dictionary <string, object>();

            if (MethodDefinition is S4JTokenRoot root)
            {
                if (Parameters != null)
                {
                    int index = 0;
                    foreach (string parameterName in root.Parameters.Keys.ToArray())
                    {
                        object parameterValue = null;
                        if (index < Parameters.Length)
                        {
                            parameterValue = Parameters[index];
                        }

                        if (index < Parameters.Length)
                        {
                            parametersAsDict[parameterName] = parameterValue;
                        }

                        index++;
                    }
                }
            }

            return(await ExecuteWithParameters(
                       MethodDefinition,
                       parametersAsDict));
        }
Esempio n. 5
0
        // public Func<DynServiceFindMethodArgs, S4JToken> ValidateMethodDelegate { get; set; }

        public async Task <S4JToken> ExecuteWithParameters(String MethodName, Tags Tags, params Object[] Parameters)
        {
            S4JToken foundMethod = null;

            using (DynServiceFindMethodArgs args = new DynServiceFindMethodArgs(MethodName, Tags, Parameters))
                foundMethod = FindMethodDelegate(args);

            if (foundMethod == null)
            {
                throw new MethodNotFoundException($"Method {MethodName} was not found");
            }

            return(null);
        }
Esempio n. 6
0
        public async Task <Object> Evaluate(S4JExecutor Executor, S4JToken token, IDictionary <String, object> variables)
        {
            S4JTokenFunction function = token as S4JTokenFunction;
            StringBuilder    code     = new StringBuilder();

            CSharpEvaluatorGlobals       globals        = new CSharpEvaluatorGlobals();
            IDictionary <string, object> globaVariables = globals.Globals as IDictionary <string, object>;

            // var globalObject = new Dictionary<string, object>();

            foreach (KeyValuePair <string, object> keyAndVal in variables)
            {
                globaVariables[keyAndVal.Key] = keyAndVal.Value;
                code.Append("var ").Append(keyAndVal.Key).Append(" = ").Append("Globals.").Append(keyAndVal.Key).Append(";");
            }

            dynamic dbProxy = new ExpandoObject();

            foreach (var source in Executor.Sources)
            {
                (dbProxy as IDictionary <string, object>)[source.Key] = new DbApi(source.Value);
            }
            globaVariables["db"] = dbProxy;
            code.Append("var ").Append("db").Append(" = ").Append("Globals.").Append("db").Append(";");

            code.Append(function.ToJsonWithoutGate());

            var refs = new List <MetadataReference> {
                MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(System.Runtime.CompilerServices.DynamicAttribute).GetTypeInfo().Assembly.Location)
            };

            var imports = ScriptOptions.Default.
                          WithImports(
                "System",
                "System.Text",
                "System.Linq",
                "System.Collections",
                "System.Collections.Generic").
                          WithReferences(refs);

            object result = await CSharpScript.EvaluateAsync(
                code.ToString(),
                imports,
                globals);

            return(result);
        }
Esempio n. 7
0
        public async Task <Object> Evaluate(S4JExecutor Executor, S4JToken token, IDictionary <String, object> variables)
        {
            S4JTokenFunction function = token as S4JTokenFunction;
            StringBuilder    code     = new StringBuilder();

            DynLanEvaluatorGlobals       globals        = new DynLanEvaluatorGlobals();
            IDictionary <string, object> globaVariables = globals.Globals as IDictionary <string, object>;

            // var globalObject = new Dictionary<string, object>();

            foreach (KeyValuePair <string, object> keyAndVal in variables)
            {
                globaVariables[keyAndVal.Key /*.ToUpper()*/] = keyAndVal.Value;

                /*if (keyAndVal.Value == null)
                 * {
                 *  code.Append($"object {keyAndVal.Key} = {keyAndVal.Value.SerializeJson()};\n");
                 * }
                 * else
                 * {
                 *  code.Append($"var {keyAndVal.Key} = {keyAndVal.Value.SerializeJson()};\n");
                 * }*/
            }

            Dictionary <String, Object> dbProxy = new Dictionary <String, Object>();

            foreach (var source in Executor.Sources)
            {
                dbProxy[source.Key] = new DbApi(source.Value);
            }
            globaVariables["db"] = dbProxy;

            code.Append(function.ToJsonWithoutGate());

            // string finalCode = MyStringHelper.AddReturnStatement(code.ToString());

            Object result = new Compiler().
                            Compile(code.ToString()).
                            Eval(globaVariables);

            return(result);
        }
Esempio n. 8
0
        public async Task <Object> Evaluate(S4JExecutor Executor, S4JToken token, IDictionary <String, object> variables)
        {
            S4JTokenFunction functionToken = token as S4JTokenFunction;
            S4JStateFunction functionState = token.State as S4JStateFunction;

            MyQuery query = new MyQuery();

            foreach (KeyValuePair <string, object> keyAndVal in variables)
            {
                BuildScriptForVariable(query, keyAndVal.Key, keyAndVal.Value);
            }

            query.Append(functionToken.ToJsonWithoutGate());

            String connectionString = Executor.Sources.Get(functionState.FunctionName);

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                var result = con.SelectItems(query.ToString());
                return(result);
            }
        }
Esempio n. 9
0
        async private Task EvaluateFunction(S4JToken token)
        {
            if (token == null)
            {
                return;
            }

            IDictionary <String, object> variables = GetExecutiongVariables(token);
            S4JTokenFunction             function  = token as S4JTokenFunction;

            object result = null;

            bool canBeEvaluated = true;

            if (token.Tags.Count > 0 && TagExecutor != null)
            {
                using (ExecutorContext context = new ExecutorContext(token, variables))
                    canBeEvaluated = TagExecutor(context);
            }

            token.IsVisible = canBeEvaluated;
            if (canBeEvaluated)
            {
                result = await function.Evaluator?.Evaluate(this, token, variables);
            }

            function.IsEvaluated = true;
            function.Result      = result;

            if (function.Parent is S4JTokenObject objectParent &&
                token.IsObjectSingleKey)
            {
                EvaluateFunctionInsideObject(
                    objectParent,
                    function,
                    result);
            }
Esempio n. 10
0
        private static S4JState GetStateBegin(char[] code, Int32 index, S4JStateBag StateBag, S4JToken prevToken)
        {
            if (prevToken == null)
            {
                return(null);
            }

            //foreach (S4JState state in StateBag.GetStates(prevToken.State.AllowedStatesNames))
            {
                // sprawdzamy rozpoczecie stanu
                // if (prevToken == null /*||
                //    prevToken.State.IsAllowed(state)*///)
                {
                    Boolean             isAllowed    = false;
                    List <S4JStateGate> matchedGates = new List <S4JStateGate>();

                    S4JState foundState = null;

                    // pobszukiwanie rozpoczecia stanu
                    var allowedStates = StateBag.GetAllowedStates(prevToken?.State);
                    //foreach (S4JState state in )
                    for (var i = 0; i < allowedStates.Length; i++)
                    {
                        var state = allowedStates[i];

                        Int32 gateStartCount = 0;
                        foreach (S4JStateGate gate in state.Gates)
                        {
                            if (S4JParserHelper.Is(code, index, gate.Start))
                            {
                                // jesli znaleziony ciag jest wiekszy od ostatniego
                                if (gateStartCount < gate.Start.Length && matchedGates.Count > 0)
                                {
                                    matchedGates.Clear();
                                }
                                matchedGates.Add(gate.Clone());
                                isAllowed      = true;
                                foundState     = state;
                                gateStartCount = gate.Start.Length;
                                //break;
                            }
                        }

                        //if (isAllowed)
                        //    break;
                    }

                    if (isAllowed)
                    {
                        S4JState newState = foundState.Clone();
                        newState.FoundGates = matchedGates;
                        return(newState);
                    }
                }
            }

            /*foreach (S4JState state in StateBag)
             * {
             *  // sprawdzamy rozpoczecie stanu
             *  if (prevToken == null ||
             *      prevToken.State.IsAllowed(state))
             *  {
             *      Boolean isAllowed = false;
             *      List<S4JStateGate> matchedGates = new List<S4JStateGate>();
             *
             *      // pobszukiwanie rozpoczecia stanu
             *      foreach (S4JStateGate gate in state.Gates)
             *      {
             *          if (S4JParserHelper.Is(code, index, gate.Start))
             *          {
             *              matchedGates.Add(gate.Clone());
             *              isAllowed = true;
             *          }
             *      }
             *
             *      if (isAllowed)
             *      {
             *          S4JState newState = state.Clone();
             *          newState.FoundGates = matchedGates;
             *          return newState;
             *      }
             *  }
             * }*/

            return(null);
        }
Esempio n. 11
0
        private static S4JState GetStateEnd(char[] code, Int32 index, S4JStateBag StateBag, S4JToken prevToken)
        {
            if (prevToken == null)
            {
                return(null);
            }

            if (prevToken?.State?.FoundGates == null)
            {
                return(null);
            }

            foreach (var gate in prevToken.State.FoundGates)
            {
                // TODO GATE
                char[] end = gate.End;
                if (S4JParserHelper.Is(code, index, end))
                {
                    prevToken.State.FoundGates.RemoveAll(g => g != gate);

                    return(prevToken?.State);
                }
            }

            return(null);
        }
Esempio n. 12
0
        private static IEnumerable <S4JStateStackEvent> Analyse(char[] code, int index, S4JStateBag StateBag, S4JTokenStack stateStack) // S4JStateStack stateStack)
        {
            // sprawdzamy zakończenie stanu
            S4JToken prevToken = stateStack.Peek();

            if (GetStateEnd(code, index, StateBag, prevToken) != null)
            {
                Int32 nextIndex = index + (prevToken.State.FoundGates.First().End == null ? 0 : (prevToken.State.FoundGates.First().End.Length - 1)) + 1;

                yield return(new S4JStateStackEvent()
                {
                    NewIndex = S4JParserHelper.SkipWhiteSpaces(code, nextIndex),
                    State = prevToken.State,
                    Popped = true,
                    // Chars = end
                });

                yield break;
            }

            prevToken = stateStack.Peek();
            S4JState state = GetStateBegin(code, index, StateBag, prevToken);

            if (state != null)
            {
                Int32 nextIndex = index + (state.FoundGates?.FirstOrDefault()?.Start == null ?
                                           0 :
                                           (state.FoundGates.First().Start.Length - 1)) + 1;

                yield return(new S4JStateStackEvent()
                {
                    // NewIndex = null,
                    NewIndex = state.IsQuotation ?
                               nextIndex :
                               // state.IsCollection ?
                               S4JParserHelper.SkipWhiteSpaces(code, nextIndex),
                    //   index + (matchedGate?.Start == null ? 0 : (matchedGate.Start.Count - 1)) + 1,
                    State = state,
                    Pushed = true,
                    // Chars = matchedGate?.Start ?? new[] { code[index] }
                });
            }
            else
            {
                Int32?newIndex = null;

                // pominiecie białych znaków do nastepnego 'stanu'
                // tylko jesli nie nie jestesmy w cytacie
                if (!prevToken.State.IsQuotation &&
                    !prevToken.State.IsComment)
                {
                    newIndex = S4JParserHelper.SkipWhiteSpaces(code, index + 1);
                    if (newIndex != null)
                    {
                        S4JState stateBegin = GetStateBegin(code, newIndex.Value, StateBag, prevToken);
                        S4JState stateEnd   = GetStateEnd(code, newIndex.Value, StateBag, prevToken);

                        if (stateBegin != null || stateEnd != null)
                        {
                            newIndex = newIndex;
                        }
                        else
                        {
                            newIndex = null;
                        }
                    }
                    else
                    {
                        newIndex = Int32.MaxValue;
                    }
                }

                yield return(new S4JStateStackEvent()
                {
                    NewIndex = newIndex,
                    State = stateStack.Peek()?.State,
                    Chars = new[] { code[index] }
                });
            }
        }
Esempio n. 13
0
        public S4JTokenRoot Parse(String Text, S4JStateBag stateBag)
        {
            char[] chars = Text.Trim().ToCharArray();

            S4JTokenStack valueStack = new S4JTokenStack();
            S4JTokenRoot  rootVal    = new S4JTokenRoot()
            {
                State = stateBag.RootState
            };

            valueStack.Push(rootVal);

            Int32 startIndex = S4JParserHelper.
                               SkipWhiteSpaces(chars, 0) ?? Int32.MaxValue;

            for (int i = startIndex; i < chars.Length; i++)
            {
                foreach (S4JStateStackEvent stackEvent in Analyse(chars, i, stateBag, valueStack))
                {
                    if (stackEvent.NewIndex != null)
                    {
                        i = stackEvent.NewIndex.Value - 1;
                    }

                    // zdjęcie ze stosu
                    if (stackEvent.Popped)
                    {
                        S4JToken currentVal = valueStack.Peek(); // PeekNonValue();
                        if (stackEvent.Chars != null)
                        {
                            currentVal.AppendCharsToToken(stackEvent.Chars);
                        }

                        // zatwierdzenie tokena
                        currentVal = valueStack.Peek();
                        if (currentVal != null)
                        {
                            currentVal.Commit();
                        }

                        currentVal.OnPop();
                        valueStack.Pop();
                    }

                    else
                    {
                        if (stackEvent.State.StateType == EStateType.S4J_VALUE_DELIMITER)
                        {
                            if (valueStack.Peek() != null)
                            {
                                valueStack.Peek().MarkLastChildAsObjectKey();
                                valueStack.Peek().Commit();
                            }
                        }

                        else if (stackEvent.State.StateType == EStateType.S4J_COMA)
                        {
                            if (valueStack.Peek() != null)
                            {
                                valueStack.Peek().Commit();
                            }
                        }

                        else
                        {
                            if (stackEvent.Pushed &&
                                stackEvent.State.IsSimpleValue == false)
                            {
                                S4JToken prevVal  = valueStack.Peek();
                                S4JToken newToken = new S4JTokenFactory().To_token(stackEvent.State);

                                valueStack.Push(newToken);

                                newToken.Parent = prevVal;

                                if (!stackEvent.State.IsComment)
                                {
                                    prevVal.AddChildToToken(newToken);
                                }
                            }

                            if (stackEvent.Chars != null)
                            {
                                if (stackEvent.State.IsSimpleValue)
                                {
                                }

                                S4JToken currentVal = valueStack.Peek();
                                currentVal.AppendCharsToToken(stackEvent.Chars);
                            }
                        }
                    }
                }
            }

            while (valueStack.Count > 0)
            {
                S4JToken currentVal = valueStack.Peek();
                if (currentVal != null)
                {
                    currentVal.Commit();
                }
                currentVal.OnPop();
                valueStack.Pop();
            }

            /*if (String.IsNullOrEmpty(rootVal.Name))
             * {
             *  return rootVal.Children.Single() as S4JToken;
             * }*/

            return(rootVal);
        }
Esempio n. 14
0
 public void Dispose()
 {
     Token     = null;
     Variables = null;
 }