Exemplo n.º 1
0
 public InputNode(ITerminalNode codeToken, InputType inputType, IdentNode typeNode, IdentNode subNode = null, ConstNode valueNode = null)
     : base(codeToken)
 {
     InputType   = inputType;
     TypeNode    = typeNode;
     SubTypeNode = subNode;
     ValueNode   = valueNode;
 }
Exemplo n.º 2
0
 public virtual AstNode VisitConst(ConstNode n)
 {
     Visit(n.AccessModifier);
     Visit(n.Type);
     Visit(n.Name);
     Visit(n.Value);
     return(n);
 }
Exemplo n.º 3
0
        //Calculates an Expression Tree given it's root node
        private double Evaluate(Node n)
        {
            if (n == null)
            {
                return(-1);
            }

            ConstNode constTest = n as ConstNode;

            if (constTest != null)
            {
                return(constTest.get_val());
            }

            VarNode varTest = n as VarNode;

            if (varTest != null)
            {
                try
                {
                    return(vDict[n.get_name()]);
                }
                catch (Exception c)
                {
                    Console.WriteLine("Key Not Found, Undefined Behavior");
                }
            }

            OpNode opTest = n as OpNode;

            if (opTest != null)
            {
                if (opTest.get_name() == "+")
                {
                    return(Evaluate(opTest.Left) + Evaluate(opTest.Right));
                }

                else if (opTest.get_name() == "-")
                {
                    return(Evaluate(opTest.Left) - Evaluate(opTest.Right));
                }

                else if (opTest.get_name() == "*")
                {
                    return(Evaluate(opTest.Left) * Evaluate(opTest.Right));
                }

                else if (opTest.get_name() == "/")
                {
                    return(Evaluate(opTest.Left) / Evaluate(opTest.Right));
                }
            }

            return(0.0); //default return value
        }
Exemplo n.º 4
0
        public void TestConstNode()
        {
            // Arrange
            var node = new ConstNode(5);

            // Act
            var result = node.Eval(new Dictionary <char, double>());

            // Assert
            Assert.Equal(5, result);
        }
Exemplo n.º 5
0
        public void TestConstNode2()
        {
            // Arrange
            var node       = new ConstNode(5);
            var dictionary = new Dictionary <char, double>()
            {
                { 'x', 5 }
            };

            // Act
            var result = node.Eval(dictionary);

            // Assert
            Assert.Equal(5, result);
        }
Exemplo n.º 6
0
        private ConstNode ParseConstNode()
        {
            StyleToken constToken = tokenStream.Current;

            AssertTokenTypeAndAdvance(StyleTokenType.Const);
            // const name
            string variableName = AssertTokenTypeAndAdvance(StyleTokenType.Identifier);

            AssertTokenTypeAndAdvance(StyleTokenType.EqualSign);

            ConstNode constNode = StyleASTNodeFactory.ConstNode(variableName, ParsePropertyValue());

            constNode.WithLocation(constToken);
            return(constNode);
        }
Exemplo n.º 7
0
 public AstNode VisitConst(ConstNode n)
 {
     if (n.AccessModifier != null)
     {
         Visit(n.AccessModifier);
         Append(" ");
     }
     Append("const ");
     Visit(n.Type);
     Append(" ");
     Visit(n.Name);
     Append(" = ");
     Visit(n.Value);
     // TODO: This is ugly, VisitMethod will append a ";" to this already, but VisitClass won't.
     Append(";");
     return(n);
 }
Exemplo n.º 8
0
        public void TestProductNode()
        {
            // Arrange
            var node1      = new ConstNode(2);
            var node2      = new ConstNode(4);
            var powerNode  = new ProductNode(node1, node2);
            var dictionary = new Dictionary <char, double>()
            {
                { 'x', 5 }
            };

            // Act
            var result = powerNode.Eval(dictionary);

            // Assert
            Assert.Equal(8, result);
        }
Exemplo n.º 9
0
        public void TestPowerNode()
        {
            // Arrange
            var b          = new ConstNode(2);
            var exp        = new ConstNode(4);
            var powerNode  = new PowerNode(b, exp);
            var dictionary = new Dictionary <char, double>()
            {
                { 'x', 5 }
            };

            // Act
            var result = powerNode.Eval(dictionary);

            // Assert
            Assert.Equal(16, result);
        }
Exemplo n.º 10
0
        public void TestAddNode()
        {
            // Arrange
            var node1      = new ConstNode(5);
            var node2      = new ConstNode(4);
            var addNode    = new AddNode(node1, node2);
            var dictionary = new Dictionary <char, double>()
            {
                { 'x', 5 }
            };

            // Act
            var result = addNode.Eval(dictionary);

            // Assert
            Assert.Equal(9, result);
        }
Exemplo n.º 11
0
            public Brep.Node Build(ConstNode constNode)
            {
                var type = constNode.VariableType as NamedTypeNode;

                if (type == null)
                {
                    throw new InvalidOperationException("Constant can only be of a named type");
                }

                switch (type.Name)
                {
                case "char":
                    return(new Brep.ConstantNode <char>(constNode.Value[0]));

                case "byte":
                    return(new Brep.ConstantNode <byte>(Convert.ToByte(constNode.Value[0])));

                case "int":
                    long res;
                    Int64.TryParse(constNode.Value, out res);
                    return(new Brep.ConstantNode <long>(res));

                case "bool":
                    if (constNode.Value.Equals("true"))
                    {
                        return(new Brep.ConstantNode <bool>(true));
                    }
                    else if (constNode.Value.Equals("false"))
                    {
                        return(new Brep.ConstantNode <bool>(false));
                    }
                    else
                    {
                        throw new InvalidOperationException("Bool can be either true or false but not: " + constNode.Value);
                    }

                case "void":
                    throw new InvalidOperationException("Constant cannot be void");

                default:
                    throw new InvalidOperationException("No constant for a type with name: " + type.Name);
                }
            }
Exemplo n.º 12
0
 private void TransformConstNode(StyleCompileContext context, ConstNode constNode, bool exported)
 {
     if (constNode.value is ConstReferenceNode)
     {
         context.constantsWithReferences.Add(constNode.constName, new StyleConstant {
             name = constNode.constName,
             constReferenceNode = (ConstReferenceNode)constNode.value,
             exported           = exported
         });
     }
     else
     {
         context.constants.Add(new StyleConstant {
             name     = constNode.constName,
             value    = constNode.value,
             exported = exported
         });
     }
 }
Exemplo n.º 13
0
        private FilterDescriptor CreateFilterDescriptor(BinaryOpNode binaryNode)
        {
            NameNode  node = binaryNode.Left as NameNode;
            ConstNode val  = binaryNode.Right as ConstNode;

            if (node == null)
            {
                node = binaryNode.Right as NameNode;
                val  = binaryNode.Left as ConstNode;
            }

            if (node == null)
            {
                throw new ArgumentException("Invalid BinaryOpNode parameter");
            }

            FilterDescriptor filterDescriptor = new FilterDescriptor();

            filterDescriptor.PropertyName = ((NameNode)node).Name;
            filterDescriptor.Value        = val.Value;
            filterDescriptor.Operator     = this.GetOperator(binaryNode.Op);
            return(filterDescriptor);
        }
Exemplo n.º 14
0
    private List <Node> GenerateNode(List <string> lines, Vector2 startPoint, ref int index, Transform parent, bool inBody)
    {
        index++;
        var nodes = new List <Node>();
        var line  = lines[index];

        if (line == KeyWords.begin.ToString() || line == KeyWords.initialization.ToString())
        {
            List <Node> newNodes;
            while ((newNodes = GenerateNode(lines, startPoint, ref index, parent, true)) != null)
            {
                nodes.AddRange(newNodes);
                if (newNodes.Any())
                {
                    startPoint = new Vector2(startPoint.x, newNodes.Last().GetBottom().y) + new Vector2(0, -g_Margin);
                }
            }
        }
        else if (line == KeyWords.end.ToString() || line == KeyWords.end + ".")
        {
            return(null);
        }
        else if (line.StartsWith("function ") || line.StartsWith("procedure "))
        {
            var fNode = parent.AppendNew(Prefabs.FuncNode, startPoint - Prefabs.FuncNode.Offset);
            fNode.Index = index;
            line        = line.TrimString("function").TrimString("procedure").Trim();
            fNode.Name  = line.Cut(0, line.IndexOf('(') - 1);
            fNode.Text  = "Начало <" + fNode.Name + ">";

            do
            {
                int sPos = lines[index].IndexOf("(") + 1;
                int ePos = lines[index].IndexOf(")");
                fNode.Args.Add(lines[index].Cut(sPos, ePos == -1 ? lines[index].Length - 1 : ePos - 1));
            }while (lines[index++].IndexOf(")") == -1);


            while (lines[index] != KeyWords.begin.ToString())
            {
                fNode.Vars.Add(lines[index].TrimString("vars").Trim(')', '(', ' '));
                index++;
            }
            index--;
            fNode.children.AddRange(GenerateNode(lines, (Vector2)fNode.transform.position + new Vector2(0, fNode.ExitPoint.y - g_Margin), ref index, fNode.transform, true));

            var endNode = fNode.transform.AppendNew(Prefabs.BeginEndNode, fNode.GetBottom() - Prefabs.FuncNode.Offset);
            endNode.Text = "Конец";
            fNode.children.Add(endNode);

            nodes.Add(fNode);
        }
        else if (line.StartsWithAny(KeyWords.@if))
        {
            var IfNode = parent.AppendNew(Prefabs.IfNode, startPoint - Prefabs.IfNode.Offset);
            IfNode.Index     = index;
            IfNode.Condition = line.Remove(0, 2).Trim(' ');
            IfNode.TrueNodes.AddRange(GenerateNode(lines, (Vector2)IfNode.transform.position + new Vector2(IfWidth / 2, IfNode.ExitPoint.y - g_Margin), ref index, parent, true));
            if (lines[index + 1] == "else")
            {
                index++;
                IfNode.FalseNodes.AddRange(GenerateNode(lines, (Vector2)IfNode.transform.position + new Vector2(IfNode.TrueNodes.Any(x => x is IfNode) ? -IfWidth : -IfWidth / 2, IfNode.ExitPoint.y - g_Margin), ref index, parent, true));
                if (IfNode.FalseNodes.Any(x => x is IfNode))
                {
                    IfNode.TrueNodes.ForEach(x => x.Translate(new Vector2(IfWidth / 2, 0)));
                }

                if (IfNode.TrueNodes.Any() && IfNode.FalseNodes.Any())
                {
                    var d = -IfNode.TrueNodes.Min(x => x.GetWidthLimits().x) + IfNode.FalseNodes.Max(x => x.GetWidthLimits().y);
                    if (d > 0)
                    {
                        IfNode.TrueNodes.ForEach(x => x.Translate(new Vector2(d / 2 + UIController.MarginLineDistance, 0)));
                        IfNode.FalseNodes.ForEach(x => x.Translate(new Vector2(-d / 2 - UIController.MarginLineDistance, 0)));
                    }
                }
            }
            nodes.Add(IfNode);
            _lastCodeNode = null;
        }
        else if (line.StartsWithAny(KeyWords.@while))
        {
            var WhileNode = parent.AppendNew(Prefabs.WhileNode, startPoint - Prefabs.WhileNode.Offset);
            WhileNode.Index     = index;
            WhileNode.Condition = line.Remove(0, 5).Trim(' ');
            WhileNode.children.AddRange(GenerateNode(lines, (Vector2)WhileNode.transform.position + new Vector2(0, WhileNode.ExitPoint.y - g_Margin), ref index, parent, true));
            nodes.Add(WhileNode);
            _lastCodeNode = null;
        }
        else if (line.StartsWith(KeyWords.repeat))
        {
            var WhileNode = parent.AppendNew(Prefabs.RepeatNode, startPoint - Prefabs.WhileNode.Offset);
            WhileNode.Index = index;
            List <Node> newNodes;
            while ((newNodes = GenerateNode(lines, startPoint, ref index, parent, true)) != null)
            {
                WhileNode.children.AddRange(newNodes);
                if (newNodes.Any())
                {
                    startPoint = new Vector2(startPoint.x, newNodes.Last().GetBottom().y) + new Vector2(0, -g_Margin);
                }

                if (newNodes.LastOrDefault() is UntilNode)
                {
                    break;
                }
            }
            nodes.Add(WhileNode);
        }
        else if (line.StartsWithAny(KeyWords.until))
        {
            var untilNode = parent.AppendNew(Prefabs.UntilNode, startPoint - Prefabs.WhileNode.Offset);
            line = line.Remove(0, 5).Trim();
            untilNode.Condition = line;
            nodes.Add(untilNode);
            _lastCodeNode = null;
        }
        else if (line.StartsWithAny(KeyWords.@for))
        {
            var ForNode = parent.AppendNew(Prefabs.ForNode, startPoint - Prefabs.ForNode.Offset);
            ForNode.Index     = index;
            ForNode.Condition = line.Remove(0, 3).Trim(' ');
            ForNode.children.AddRange(GenerateNode(lines, (Vector2)ForNode.transform.position + new Vector2(0, ForNode.ExitPoint.y - g_Margin), ref index, parent, true));
            nodes.Add(ForNode);
            _lastCodeNode = null;
        }
        else if (line.StartsWith("write(") || line.StartsWith("read(") || line.StartsWith("writeln(") || line.StartsWith("readln(") || line == "writeln" || line == "write" || line == "read" || line == "readln")
        {
            if (_lastCodeNode != null && _lastCodeNode.EndIndex == index - 1 && _lastCodeNode.GetType() == typeof(IONode))
            {
                _lastCodeNode.EndIndex = index;
                _lastCodeNode.Text    += "\n" + line + ";";
                if (_lastCodeNode.EndIndex - _lastCodeNode.Index > MaxNodeLinesCount)
                {
                    _lastCodeNode = null;
                }
            }
            else
            {
                _lastCodeNode          = parent.AppendNew(Prefabs.IONode, startPoint - Prefabs.CodeNode.Offset);
                _lastCodeNode.Index    = index;
                _lastCodeNode.EndIndex = index;
                _lastCodeNode.Text     = line + ";";
                nodes.Add(_lastCodeNode);
            }
        }
        else if (line.StartsWithAny(KeyWords.var) && !inBody)
        {
            VarNode vNode = parent.AppendNew(Prefabs.VarNode, startPoint - Prefabs.VarNode.Offset);
            vNode.Index    = index;
            vNode.EndIndex = index;
            vNode.AddVar(line.Remove(0, 3).Trim());
            while (!lines[index + 1].StartsWithAny(KeyWords.begin, KeyWords.uses, KeyWords.function, KeyWords.procedure, KeyWords.type, KeyWords.@const)) //while (lines[index+1].ContainsAny("begin", "uses", "function", "procedure", "type") == null)
            {
                vNode.AddVar(lines[index + 1]);
                index++;
            }
            nodes.Add(vNode);
        }
        else if (line.StartsWithAny(KeyWords.except))
        {
            var exceptNode = parent.AppendNew(Prefabs.IfNode, startPoint - Prefabs.WhileNode.Offset);
            exceptNode.Index     = index;
            exceptNode.Condition = "{exception occured}";
            List <Node> node;
            while ((node = GenerateNode(lines, (Vector2)exceptNode.transform.position + new Vector2(0, exceptNode.ExitPoint.y - g_Margin), ref index, parent, true)) != null)
            {
                exceptNode.TrueNodes.AddRange(node);
            }
            nodes.Add(exceptNode);
            _lastCodeNode = null;
        }
        else if (line.StartsWithAny(KeyWords.@const))
        {
            ConstNode vNode = parent.AppendNew(Prefabs.ConstNode, startPoint - Prefabs.VarNode.Offset);
            vNode.Index    = index;
            vNode.EndIndex = index;
            vNode.AddVar(line.Remove(0, 5).Trim());
            while (!lines[index + 1].StartsWithAny()) //while (lines[index+1].ContainsAny("begin", "uses", "function", "procedure", "type") == null)
            {
                vNode.AddVar(lines[index + 1]);
                index++;
            }
            nodes.Add(vNode);
        }
        else if (line.StartsWithAny(KeyWords.uses))
        {
            line = line.Remove(0, 4);
            try
            {
                foreach (var lib in line.Split(',').Select(x => x.Trim()))
                {
                    int    inChar   = lib.IndexOf(" in ");
                    string fileName = lib + ".pas";
                    if (inChar != -1)
                    {
                        int l1 = lib.IndexOf("@%");
                        int l2 = lib.IndexOf("%@");
                        if (l1 != -1 && l2 > l1)
                        {
                            fileName = Literals[int.Parse(lib.Cut(l1 + 2, l2 - 1))].Trim(' ', '.', '\'', '/', (char)92);
                        }
                    }

                    print(fileName);
                    if (System.IO.File.Exists(fileName))
                    {
                        string code           = System.IO.File.ReadAllText(fileName);
                        string finCode        = null;
                        int    implementation = code.IndexOf("implementation");
                        code = code.Remove(0, implementation + "implementation".Length);
                        int finalization = code.IndexOf("finalization");
                        int codeLen      = code.Length;
                        if (finalization != -1)
                        {
                            finCode = code.Remove(0, finalization + "finalization".Length);
                            code    = code.Substring(0, finalization) + "end.";
                        }
                        //print(code);
                        var parsed = ParseCode(code);
                        var unit   = GenerateUnit(parsed, ref startPoint, ref TopPoint, lib.Split()[0]);
                        if (unit.Any())
                        {
                            nodes.AddRange(unit);
                            var joint = parent.AppendNew(Prefabs.JointNode, new Vector2(startPoint.x, unit.Last().GetBottom().y));
                            nodes.Add(joint);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
            }
        }
        else if (line.StartsWithAny(KeyWords.type, KeyWords.program))
        {
        }
        else
        {
            var function = Functions.Any() ? line.ContainsAny(Functions.Keys) : null;
            if (function != null)
            {
                FunctionCallNode node = parent.AppendNew(Prefabs.FunctionCallNode, startPoint - Prefabs.CodeNode.Offset);
                node.Index    = index;
                node.Text     = line + ";";
                node.Function = Functions[function];
                nodes.Add(node);
            }
            else
            {
                if (_lastCodeNode != null && _lastCodeNode.EndIndex == index - 1 && _lastCodeNode.GetType() == typeof(CodeNode))
                {
                    _lastCodeNode.EndIndex = index;
                    _lastCodeNode.Text    += "\r\n" + line + ";";
                    if (_lastCodeNode.EndIndex - _lastCodeNode.Index > MaxNodeLinesCount)
                    {
                        _lastCodeNode = null;
                    }
                }
                else
                {
                    _lastCodeNode          = parent.AppendNew(Prefabs.CodeNode, startPoint - Prefabs.CodeNode.Offset);
                    _lastCodeNode.Index    = index;
                    _lastCodeNode.EndIndex = index;
                    _lastCodeNode.Text     = line + ";";
                    nodes.Add(_lastCodeNode);
                }
            }
        }
        return(nodes);
    }
    private void CreateNewObject(Reduction r)
    {
        MathFuncNode arg1, arg2;

        var tableIndex = (ProductionIndex)r.Parent.TableIndex();

        switch (tableIndex)
        {
        case ProductionIndex.Statements:
            // <Statements> ::= <Statements> <Devider> <Statement>
            break;

        case ProductionIndex.Statements2:
            // <Statements> ::= <Statements> <Devider>
            break;

        case ProductionIndex.Statements3:
            // <Statements> ::= <Statement>
            //Funcs.Push(new MathFunc(Args.Pop()));
            break;

        case ProductionIndex.Devider_Semi:
            // <Devider> ::= ';'
            break;

        case ProductionIndex.Devider_Dot:
            // <Devider> ::= '.'
            break;

        case ProductionIndex.Statement_Eq:
            // <Statement> ::= <Expression> '=' <Expression>
            arg2 = Nodes.Pop();
            arg1 = Nodes.Pop();
            Funcs.Push(new MathFunc(arg1, arg2, null, Parameters.Select(p => p.Value)));
            Parameters.Clear();
            break;

        case ProductionIndex.Statement:
            // <Statement> ::= <Expression>
            Funcs.Push(new MathFunc(Nodes.Pop(), null, Parameters.Select(p => p.Value)));
            break;

        case ProductionIndex.Expression:
            // <Expression> ::= <FuncDef>
            break;

        case ProductionIndex.Funcdef_Id_Lparan_Rparan:
            // <FuncDef> ::= Id '(' <ExpressionList> ')'

            PushFunction(r[0].Data.ToString());
            break;

        case ProductionIndex.Funcdef_Id_Apost_Lparan_Rparan:
        // <FuncDef> ::= Id '' '(' <ExpressionList> ')'

        case ProductionIndex.Funcdef_Id_Lparan_Rparan_Apost:

            // <FuncDef> ::= Id '(' <ExpressionList> ')' ''

            PushFunction(r[0].Data.ToString());
            Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] { Nodes.Pop(), null }));

            break;

        case ProductionIndex.Expressionlist_Comma:
            ArgsCount[ArgsCount.Count - 1]++;
            break;

        case ProductionIndex.Expressionlist:
            ArgsCount.Add(1);
            ArgsFuncTypes.Add(null);
            break;

        case ProductionIndex.Expression2:

            // <Expression> ::= <Addition>
            if (AdditionMultiChilds)
            {
                PushOrRemoveFunc(KnownFuncType.Add);
            }

            break;

        case ProductionIndex.Addition_Addliteral:

            // <Addition> ::= <Addition> AddLiteral <Multiplication>
            if (MultiplicationMultiChilds)
            {
                PushOrRemoveFunc(KnownFuncType.Mult);
            }

            if (AdditionMultiChilds)
            {
                ArgsCount[ArgsCount.Count - 1]++;
                if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
                {
                    Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
                }
            }
            else
            {
                PushBinaryFunction(r[1].Data.ToString());
            }
            break;

        case ProductionIndex.Addition_Addliteral2:

            // <Addition> ::= <Addition> AddLiteral <FuncDef>

            if (AdditionMultiChilds)
            {
                ArgsCount[ArgsCount.Count - 1]++;
                if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
                {
                    Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
                }
            }
            else
            {
                PushBinaryFunction(r[1].Data.ToString());
            }
            break;

        case ProductionIndex.Addition_Addliteral3:

            // <Addition> ::= <FuncDef> AddLiteral <Multiplication>
            if (MultiplicationMultiChilds)
            {
                PushOrRemoveFunc(KnownFuncType.Mult);
            }

            if (AdditionMultiChilds)
            {
                PushFunc(KnownFuncType.Add, 2);
                if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
                {
                    Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
                }
            }
            else
            {
                PushBinaryFunction(r[1].Data.ToString());
            }
            break;

        case ProductionIndex.Addition_Addliteral4:

            // <Addition> ::= <FuncDef> AddLiteral <FuncDef>

            if (AdditionMultiChilds)
            {
                PushFunc(KnownFuncType.Add, 2);
                if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
                {
                    Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
                }
            }
            else
            {
                PushBinaryFunction(r[1].Data.ToString());
            }
            break;

        case ProductionIndex.Addition:

            // <Addition> ::= <Multiplication>

            if (MultiplicationMultiChilds)
            {
                PushOrRemoveFunc(KnownFuncType.Mult);
            }

            if (AdditionMultiChilds)
            {
                PushFunc(KnownFuncType.Add);
            }

            break;

        case ProductionIndex.Multiplication_Multliteral:

        // <Multiplication> ::= <Multiplication> MultLiteral <Exponentiation>
        case ProductionIndex.Multiplication_Multliteral2:
            // <Multiplication> ::= <Multiplication> MultLiteral <FuncDef>

            if (MultiplicationMultiChilds)
            {
                if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Div)
                {
                    Nodes.Push(new FuncNode(KnownFuncType.Pow, new MathFuncNode[] { Nodes.Pop(), new ValueNode(-1) }));
                }
                ArgsCount[ArgsCount.Count - 1]++;
            }
            else
            {
                PushBinaryFunction(r[1].Data.ToString());
            }
            break;

        case ProductionIndex.Multiplication:

            // <Multiplication> ::= <Exponentiation>

            if (MultiplicationMultiChilds)
            {
                PushFunc(KnownFuncType.Mult);
            }
            break;

        case ProductionIndex.Multiplication_Multliteral3:
        // <Multiplication> ::= <FuncDef> MultLiteral <Exponentiation>
        case ProductionIndex.Multiplication_Multliteral4:
            // <Multiplication> ::= <FuncDef> MultLiteral <FuncDef>

            if (MultiplicationMultiChilds)
            {
                PushFunc(KnownFuncType.Mult, 2);

                if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Div)
                {
                    Nodes.Push(new FuncNode(KnownFuncType.Pow, new MathFuncNode[] { Nodes.Pop(), new ValueNode(-1) }));
                }
            }
            else
            {
                PushBinaryFunction(r[1].Data.ToString());
            }
            break;

        case ProductionIndex.Exponentiation_Caret:
        // <Exponentiation> ::= <Exponentiation> '^' <Negation>
        case ProductionIndex.Exponentiation_Caret2:
        // <Exponentiation> ::= <Exponentiation> '^' <FuncDef>
        case ProductionIndex.Exponentiation_Caret3:
        // <Exponentiation> ::= <FuncDef> '^' <Negation>
        case ProductionIndex.Exponentiation_Caret4:
            // <Exponentiation> ::= <FuncDef> '^' <FuncDef>

            PushBinaryFunction(r[1].Data.ToString());
            break;

        case ProductionIndex.Exponentiation:
            // <Exponentiation> ::= <Negation>
            break;

        case ProductionIndex.Negation_Addliteral:
        // <Negation> ::= AddLiteral <Value>
        case ProductionIndex.Negation_Addliteral2:
            // <Negation> ::= AddLiteral <FuncDef>
            if (Nodes.Peek().Type == MathNodeType.Value)
            {
                if (r[0].Data.ToString() == "-")
                {
                    Nodes.Push(new ValueNode(-((ValueNode)Nodes.Pop()).Value));
                }
            }
            else
            {
                Nodes.Push(new FuncNode(r[0].Data.ToString(), new MathFuncNode[] { Nodes.Pop() }));
            }
            break;

        case ProductionIndex.Negation:

            // <Negation> ::= <Value>
            break;

        case ProductionIndex.Value_Id:

            // <Value> ::= Id
            var       id = r[0].Data.ToString();
            ConstNode idValue;
            if (Parameters.TryGetValue(id, out idValue))
            {
                Nodes.Push(idValue);
            }
            else
            {
                var newConst = new ConstNode(id);
                Nodes.Push(newConst);
                Parameters.Add(id, newConst);
            }
            break;

        case ProductionIndex.Value_Number1:
        // <Value> ::= 'Number1'
        case ProductionIndex.Value_Number2:
            // <Value> ::= 'Number2'

            try
            {
                var    str        = r[0].Data.ToString();
                var    dotInd     = str.IndexOf('.');
                string intPart    = dotInd == 0 ? "0" : str.Substring(0, dotInd == -1 ? str.Length : dotInd);
                string fracPart   = null;
                string periodPart = null;
                if (dotInd != -1)
                {
                    int braceInd = str.IndexOf('(', dotInd + 1);
                    if (braceInd == -1)
                    {
                        fracPart = str.Substring(dotInd + 1, str.Length - dotInd - 1);
                    }
                    else
                    {
                        fracPart   = str.Substring(dotInd + 1, braceInd - dotInd - 1);
                        periodPart = str.Substring(braceInd + 1, str.Length - braceInd - 2);
                    }
                }
                var result = Rational <long> .FromDecimal(intPart, fracPart, periodPart);

                Nodes.Push(new ValueNode(result));
            }
            catch
            {
                throw new ArgumentException();
            }
            break;

        case ProductionIndex.Value_Lparan_Rparan:

            // <Value> ::= '(' <Expression> ')'
            break;

        case ProductionIndex.Value_Pipe_Pipe:

            // <Value> ::= '|' <Expression> '|'
            Nodes.Push(new FuncNode(KnownFuncType.Abs, new MathFuncNode[] { Nodes.Pop() }));
            break;

        case ProductionIndex.Value_Lparan_Rparan_Apost:

            // <Value> ::= '(' <Expression> ')' ''
            Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] { Nodes.Pop(), null }));
            break;

        case ProductionIndex.Value_Pipe_Pipe_Apost:

            // <Value> ::= '|' <Expression> '|' ''
            Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] {
                new FuncNode(KnownFuncType.Abs, new MathFuncNode[] { Nodes.Pop() }), null
            }));
            break;

            /*case ProductionIndex.Value_Id_Apost:
             *
             *      // <Value> ::= Id ''
             *      Args.Push(new FuncNode(KnownMathFunctionType.Diff, null,
             *              new MathFunctionNode[] {
             *                      new FuncNode(r[0].Data.ToString(), null, new MathFunctionNode[] { null }), null }));
             *      break;*/
        }          //switch
    }
Exemplo n.º 16
0
	private void CreateNewObject(Reduction r)
	{
		MathFuncNode arg1, arg2;

		var tableIndex = (ProductionIndex)r.Parent.TableIndex();
		switch (tableIndex)
		{
			case ProductionIndex.Statements:
				// <Statements> ::= <Statements> <Devider> <Statement>
				break;

			case ProductionIndex.Statements2:
				// <Statements> ::= <Statements> <Devider>
				break;

			case ProductionIndex.Statements3:
				// <Statements> ::= <Statement>
				//Funcs.Push(new MathFunc(Args.Pop()));
				break;

			case ProductionIndex.Devider_Semi:
				// <Devider> ::= ';'
				break;

			case ProductionIndex.Devider_Dot:
				// <Devider> ::= '.'
				break;

			case ProductionIndex.Statement_Eq:
				// <Statement> ::= <Expression> '=' <Expression>
				arg2 = Nodes.Pop();
				arg1 = Nodes.Pop();
				Funcs.Push(new MathFunc(arg1, arg2, null, Parameters.Select(p => p.Value)));
				Parameters.Clear();
				break;

			case ProductionIndex.Statement:
				// <Statement> ::= <Expression>
				Funcs.Push(new MathFunc(Nodes.Pop(), null, Parameters.Select(p => p.Value)));
				break;

			case ProductionIndex.Expression:
				// <Expression> ::= <FuncDef>
				break;

			case ProductionIndex.Funcdef_Id_Lparan_Rparan:
				// <FuncDef> ::= Id '(' <ExpressionList> ')'

				PushFunction(r[0].Data.ToString());
				break;

			case ProductionIndex.Funcdef_Id_Apost_Lparan_Rparan:
			// <FuncDef> ::= Id '' '(' <ExpressionList> ')'

			case ProductionIndex.Funcdef_Id_Lparan_Rparan_Apost:

				// <FuncDef> ::= Id '(' <ExpressionList> ')' ''

				PushFunction(r[0].Data.ToString());
				Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] { Nodes.Pop(), null }));

				break;

			case ProductionIndex.Expressionlist_Comma:
				ArgsCount[ArgsCount.Count - 1]++;
				break;

			case ProductionIndex.Expressionlist:
				ArgsCount.Add(1);
				ArgsFuncTypes.Add(null);
				break;

			case ProductionIndex.Expression2:

				// <Expression> ::= <Addition>
				if (AdditionMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Add);

				break;

			case ProductionIndex.Addition_Addliteral:

				// <Addition> ::= <Addition> AddLiteral <Multiplication>
				if (MultiplicationMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Mult);

				if (AdditionMultiChilds)
				{
					ArgsCount[ArgsCount.Count - 1]++;
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition_Addliteral2:

				// <Addition> ::= <Addition> AddLiteral <FuncDef>

				if (AdditionMultiChilds)
				{
					ArgsCount[ArgsCount.Count - 1]++;
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition_Addliteral3:

				// <Addition> ::= <FuncDef> AddLiteral <Multiplication>
				if (MultiplicationMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Mult);

				if (AdditionMultiChilds)
				{
					PushFunc(KnownFuncType.Add, 2);
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)

						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition_Addliteral4:

				// <Addition> ::= <FuncDef> AddLiteral <FuncDef>

				if (AdditionMultiChilds)
				{
					PushFunc(KnownFuncType.Add, 2);
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Sub)
						Nodes.Push(new FuncNode(KnownFuncType.Neg, new MathFuncNode[] { Nodes.Pop() }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Addition:

				// <Addition> ::= <Multiplication>

				if (MultiplicationMultiChilds)
					PushOrRemoveFunc(KnownFuncType.Mult);

				if (AdditionMultiChilds)
					PushFunc(KnownFuncType.Add);

				break;

			case ProductionIndex.Multiplication_Multliteral:

			// <Multiplication> ::= <Multiplication> MultLiteral <Exponentiation>
			case ProductionIndex.Multiplication_Multliteral2:
				// <Multiplication> ::= <Multiplication> MultLiteral <FuncDef>

				if (MultiplicationMultiChilds)
				{
					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Div)
						Nodes.Push(new FuncNode(KnownFuncType.Exp, new MathFuncNode[] { Nodes.Pop(), new ValueNode(-1) }));
					ArgsCount[ArgsCount.Count - 1]++;
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Multiplication:

				// <Multiplication> ::= <Exponentiation>

				if (MultiplicationMultiChilds)
					PushFunc(KnownFuncType.Mult);
				break;

			case ProductionIndex.Multiplication_Multliteral3:
			// <Multiplication> ::= <FuncDef> MultLiteral <Exponentiation>
			case ProductionIndex.Multiplication_Multliteral4:
				// <Multiplication> ::= <FuncDef> MultLiteral <FuncDef>

				if (MultiplicationMultiChilds)
				{
					PushFunc(KnownFuncType.Mult, 2);

					if (KnownFunc.BinaryNamesFuncs[r[1].Data.ToString()] == KnownFuncType.Div)
						Nodes.Push(new FuncNode(KnownFuncType.Exp, new MathFuncNode[] { Nodes.Pop(), new ValueNode(-1) }));
				}
				else
					PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Exponentiation_Caret:
				// <Exponentiation> ::= <Exponentiation> '^' <Negation>
			case ProductionIndex.Exponentiation_Caret2:
				// <Exponentiation> ::= <Exponentiation> '^' <FuncDef>
			case ProductionIndex.Exponentiation_Caret3:
				// <Exponentiation> ::= <FuncDef> '^' <Negation>
			case ProductionIndex.Exponentiation_Caret4:
				// <Exponentiation> ::= <FuncDef> '^' <FuncDef>

				PushBinaryFunction(r[1].Data.ToString());
				break;

			case ProductionIndex.Exponentiation:
				// <Exponentiation> ::= <Negation>
				break;

			case ProductionIndex.Negation_Addliteral:
				// <Negation> ::= AddLiteral <Value>
			case ProductionIndex.Negation_Addliteral2:
				// <Negation> ::= AddLiteral <FuncDef>
				if (Nodes.Peek().Type == MathNodeType.Value)
				{
					if (r[0].Data.ToString() == "-")
						Nodes.Push(new ValueNode(-((ValueNode)Nodes.Pop()).Value));
				}
				else
					Nodes.Push(new FuncNode(r[0].Data.ToString(), new MathFuncNode[] { Nodes.Pop() }));
				break;

			case ProductionIndex.Negation:

				// <Negation> ::= <Value>
				break;

			case ProductionIndex.Value_Id:

				// <Value> ::= Id
				var id = r[0].Data.ToString();
				ConstNode idValue;
				if (Parameters.TryGetValue(id, out idValue))
					Nodes.Push(idValue);
				else
				{
					var newConst = new ConstNode(id);
					Nodes.Push(newConst);
					Parameters.Add(id, newConst);
				}
				break;

			case ProductionIndex.Value_Number1:
				// <Value> ::= 'Number1'
			case ProductionIndex.Value_Number2:
				// <Value> ::= 'Number2'

				try
				{
					var str = r[0].Data.ToString();
					var dotInd = str.IndexOf('.');
					string intPart = dotInd == 0 ? "0" : str.Substring(0, dotInd == -1 ? str.Length : dotInd);
					string fracPart = null;
					string periodPart = null;
					if (dotInd != -1)
					{
						int braceInd = str.IndexOf('(', dotInd + 1);
						if (braceInd == -1)
							fracPart = str.Substring(dotInd + 1, str.Length - dotInd - 1);
						else
						{
							fracPart = str.Substring(dotInd + 1, braceInd - dotInd - 1);
							periodPart = str.Substring(braceInd + 1, str.Length - braceInd - 2);
						}
					}
					var result = Rational<long>.FromDecimal(intPart, fracPart, periodPart);
					Nodes.Push(new ValueNode(result));
				}
				catch
				{
					throw new ArgumentException();
				}
				break;

			case ProductionIndex.Value_Lparan_Rparan:

				// <Value> ::= '(' <Expression> ')'
				break;

			case ProductionIndex.Value_Pipe_Pipe:

				// <Value> ::= '|' <Expression> '|'
				Nodes.Push(new FuncNode(KnownFuncType.Abs, new MathFuncNode[] { Nodes.Pop() }));
				break;

			case ProductionIndex.Value_Lparan_Rparan_Apost:

				// <Value> ::= '(' <Expression> ')' ''
				Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] { Nodes.Pop(), null }));
				break;

			case ProductionIndex.Value_Pipe_Pipe_Apost:

				// <Value> ::= '|' <Expression> '|' ''
				Nodes.Push(new FuncNode(KnownFuncType.Diff, new MathFuncNode[] {
						new FuncNode(KnownFuncType.Abs, new MathFuncNode[] { Nodes.Pop() }), null }));
				break;

			/*case ProductionIndex.Value_Id_Apost:

				// <Value> ::= Id ''
				Args.Push(new FuncNode(KnownMathFunctionType.Diff, null,
					new MathFunctionNode[] {
						new FuncNode(r[0].Data.ToString(), null, new MathFunctionNode[] { null }), null }));
				break;*/
		}  //switch
	}
Exemplo n.º 17
0
        private FilterDescriptor CreateFilterDescriptor(BinaryOpNode binaryNode)
        {
            bool         flag         = false;
            NameNode     nameNode     = binaryNode.Left as NameNode;
            ConstNode    constNode1   = binaryNode.Right as ConstNode;
            ZeroOpNode   zeroOpNode   = (ZeroOpNode)null;
            FunctionNode functionNode = (FunctionNode)null;

            if (constNode1 == null)
            {
                zeroOpNode = binaryNode.Right as ZeroOpNode;
            }
            if (constNode1 == null && binaryNode.Right is UnaryOpNode)
            {
                UnaryOpNode right = binaryNode.Right as UnaryOpNode;
                flag       = right.Op.Name == "Not";
                zeroOpNode = right.Right as ZeroOpNode;
            }
            if (constNode1 == null && binaryNode.Right is FunctionNode)
            {
                functionNode = binaryNode.Right as FunctionNode;
            }
            if (nameNode == null)
            {
                nameNode   = binaryNode.Right as NameNode;
                constNode1 = binaryNode.Left as ConstNode;
                if (constNode1 == null)
                {
                    zeroOpNode = binaryNode.Left as ZeroOpNode;
                }
                if (constNode1 == null && binaryNode.Left is UnaryOpNode)
                {
                    zeroOpNode = (binaryNode.Left as UnaryOpNode).Right as ZeroOpNode;
                }
                if (constNode1 == null && binaryNode.Left is FunctionNode)
                {
                    functionNode = binaryNode.Left as FunctionNode;
                }
            }
            if (nameNode == null)
            {
                throw new ArgumentException("Invalid BinaryOpNode parameter");
            }
            FilterDescriptor filterDescriptor = new FilterDescriptor();

            filterDescriptor.PropertyName = nameNode.Name;
            if (constNode1 != null)
            {
                filterDescriptor.Value = constNode1.Value;
            }
            else if (zeroOpNode != null)
            {
                filterDescriptor.Value = this.GetValueFormText(zeroOpNode.Operator.Name);
            }
            else if (functionNode != null)
            {
                StringBuilder stringBuilder = new StringBuilder();
                foreach (ConstNode constNode2 in functionNode.Arguments)
                {
                    stringBuilder.Append(constNode2.Value);
                    stringBuilder.Append(", ");
                }
                stringBuilder.Length  -= 2;
                filterDescriptor.Value = (object)stringBuilder.ToString();
            }
            filterDescriptor.Operator = this.GetOperator(binaryNode.Op);
            if (binaryNode.Op == Operator.Is && filterDescriptor.Value == null)
            {
                filterDescriptor.Operator = FilterOperator.IsNull;
            }
            if (flag)
            {
                filterDescriptor.Operator = this.GetNegativeOperator(filterDescriptor.Operator);
            }
            return(filterDescriptor);
        }
Exemplo n.º 18
0
 private bool HasSideEffects(ConstNode node)
 {
     return(false);
 }