示例#1
0
 public void GetResultconstantminusfiveaddminusthree()
 {
     tokenExpected = new ConstantToken(-8, false, false);
     tokenActual   = tokenminusFive + tokenminusthree;
     Console.WriteLine(tokenExpected.GetResult().Print() + " | - | " + tokenActual.GetResult().Print());
     Assert.AreEqual(tokenExpected.GetResult().Print(), tokenActual.GetResult().Print());
 }
示例#2
0
 public void subtractRightNegativeValue()
 {
     tokenExpected = new ConstantToken(8, false, false);
     tokenActual   = tokenFive - tokenminusthree;
     Console.WriteLine(tokenExpected.GetResult().Print() + " | - | " + tokenActual.GetResult().Print());
     Assert.AreEqual(tokenExpected.GetResult().Print(), tokenActual.GetResult().Print());
 }
示例#3
0
 public void subtractTwoPosiveValues()
 {
     tokenExpected = new ConstantToken(2, false, false);
     tokenActual   = tokenFive - tokenThree;
     Console.WriteLine(tokenExpected.GetResult().Print() + " | - | " + tokenActual.GetResult().Print());
     Assert.AreEqual(tokenExpected.GetResult().Print(), tokenActual.GetResult().Print());
 }
        private OperationResult ParseConstant()
        {
            string value          = null;
            var    sb             = new StringBuilder();
            string untrimmedFinal = null;

            var wasPoint = false;

            while (Const.Digits.Contains(Input[Pointer]) || Input[Pointer] == Const.Point)
            {
                if (Input[Pointer] == Const.Point)
                {
                    if (!wasPoint)
                    {
                        wasPoint = true;
                    }
                    else
                    {
                        return(OperationResult.CreateFailure("A number cannot have multiple points."));
                    }
                }

                sb.Append(Input[Pointer]);

                if (Pointer + 1 >= Input.Length || (Input[Pointer + 1] != Const.Point && !Const.Digits.Contains(Input[Pointer + 1])))
                {
                    break;
                }
                else
                {
                    Pointer++;
                }
            }

            LastCharacter = Input[Pointer];

            untrimmedFinal = sb.ToString();

            value = untrimmedFinal == "0" ? untrimmedFinal : untrimmedFinal.TrimStart('0');

            var parsedDecimal = decimal.Parse(value);

            var token = new ConstantToken(parsedDecimal);

            if (NegateFlag && _parenthesesStack.Count == 0)
            {
                token.Negate();
                NegateFlag = false;
            }

            _expressionStack.Push(token);
            return(ParseAndSimplify());
        }
示例#5
0
        public void DivideVariableTokenBy1_ReturnsSameVariableToken()
        {
            var q = 2;
            var v = new List <Variable> {
                new Variable('x', 1)
            };
            var a  = new VariableToken(q, v);
            var b  = new ConstantToken(1);
            var op = new BinaryOperationToken {
                Value = "/"
            };

            var res = Simplifier.DoOperation(op, a, b);

            Assert.IsTrue(res.Success);

            Assert.IsTrue(res.Result is VariableToken);
            Assert.IsTrue(((VariableToken)res.Result).Quotient == q);
            Assert.IsTrue(((VariableToken)res.Result).Variables.Except(v).Count() == 0);
        }
        private void ButtonEnter_Click(object sender, EventArgs e)
        {
            if (_tokenizer.TokenList != null)
            {
                bool isvalid = _tokenizer.validate();
                // divide by zero error found
                if (!isvalid)
                {
                    convertedinput.Text = "Sorry, you cannot divide by Zero";
                }
                else
                {
                    if (listofresults.Count > 0)
                    {
                        _tokenizer.constructTree(listofresults[0]);
                        clearvalue();
                    }
                    else
                    {
                        _tokenizer.constructTree();
                    }
                    convertedinput.Text = _tokenizer.ToString();
                    userinput.Clear();
                    _tokenizer.buildTree();
                    ConstantToken resulttoken = _tokenizer.TokenList[0].GetResult();
                    listofresults.Insert(0, resulttoken);
                    resultlistview.Items.Clear();
                    foreach (var a in listofresults)
                    {
                        resultlistview.Items.Add(a.Print());
                    }
                }
            }

            Operator_Click(sender, e);
            _tokenizer.TokenList = null;
            updateDisplay();
        }
示例#7
0
        private void ReturnConst(LexerState state, Symbol trigger)
        {
            Log(LogEventLevel.Information, "Found a constant");
            var value = ConstantToken <float> .Parse(CurrentToken.ToString());

            var con = Constants.FirstOrDefault(x => Math.Abs(x.Value - value) < 1E-5)?.Clone() as ConstantToken <float>;

            if (con == null)
            {
                con = new ConstantToken <float>(CurrentToken.ToString())
                {
                    TokenIndex = ConstIndex,
                    Substring  = CurrentToken.ToString()
                };
                Constants.Add(con);
            }
            else
            {
                Log(LogEventLevel.Information, "The constant is already processed");
            }
            con.Line = Line;
            ReturnToken(con, trigger);
        }
 public ConstantToken Calculate(ConstantToken a, ConstantToken b)
 {
     return(new ConstantToken(operation(a.Value, b.Value)));
 }
示例#9
0
 public ConstantOutput(EType type, dynamic output, ConstantToken instance)
 {
     _type     = type;
     _output   = output;
     _instance = instance;
 }
示例#10
0
        private bool ProcessFor(Token token, Stack <Token> stack, List <Token> prn, IList <LabelToken> labels, VariableStore store)
        {
            if (stack.Peek().Substring == "do" && stack.Peek().Tag == null && prn.Last() is IdentifierToken) //Identifier right after for keyword
            {
                stack.Peek().Tag = new ForContext()
                {
                    Parameter = prn.Last() as IdentifierToken
                };
            }

            var lastFor = stack.First(x => x.Substring == "do");
            var context = lastFor.Tag as ForContext;

            if (token.Substring == "to")
            {
                var workingId = new IdentifierToken($"_r{store.Count + 1}");
                store[workingId]     = new ConstantToken <float>(0);
                context.ToIdentifier = workingId;

                var label = new LabelToken($"_m{labels.Count + 1}");
                labels.Add(label);
                context.LoopLabel = label;


                while (stack.Peek().Substring != "do")
                {
                    prn.Add(stack.Pop());
                }

                prn.Add(label);
                prn.Add(new StringToken(":"));
                prn.Add(context.ToIdentifier);

                return(true);
            }

            if (token.Substring == Environment.NewLine)
            {
                if (token.Line == lastFor.Line)
                {
                    var label = new LabelToken($"_m{labels.Count + 1}");
                    labels.Add(label);
                    context.ExitLabel = label;

                    while (stack.Peek().Substring != "do")
                    {
                        prn.Add(stack.Pop());
                    }

                    prn.Add(new StringToken("="));
                    prn.Add(context.Parameter);
                    prn.Add(context.ToIdentifier);
                    prn.Add(new StringToken("<="));
                    prn.Add(context.ExitLabel);
                    prn.Add(new ConditionalFalseJumpOperation());
                }

                return(true);
            }

            if (token.Substring == "next")
            {
                while (stack.Peek().Substring != "do")
                {
                    prn.Add(stack.Pop());
                }

                prn.Add(context.Parameter);
                prn.Add(context.Parameter);
                prn.Add(new ConstantToken <float>(1));
                prn.Add(new StringToken("+"));
                prn.Add(new StringToken("="));

                prn.Add(context.LoopLabel);
                prn.Add(new UnconditionalJumpOperation());
                prn.Add(context.ExitLabel);
                prn.Add(new StringToken(":"));

                stack.Pop(); //Pop for

                return(true);
            }

            return(false);
        }
示例#11
0
 /// <summary>
 /// Evaluates a given constant token.
 /// </summary>
 /// <param name="token">The token to be evaluated.</param>
 /// <returns>The evaluated value.</returns>
 public abstract T EvaluateConstant(ConstantToken token);
示例#12
0
 internal TruthyConstantExpression(ConstantToken <TSource> token)
 {
     Token = token;
 }
示例#13
0
        internal static LogicalExpression <TSource> CompileLogicalExpression <TSource, TToken>(string text, Func <string, TToken> pathToken)
            where TToken : Token <TSource>
        {
            LogicalExpression <TSource> result = null;

            var whereMatch = parser.Match(text);

            if (whereMatch == null || !whereMatch.Success)
            {
                throw new ArgumentException("Invalid expression \"" + text + "\".");
            }

            var exprCaptures = whereMatch.Groups["expr"].Captures;
            var nextCaptures = whereMatch.Groups["next"].Captures;

            AndExpressionGroup <TSource> andGroup = null;

            for (var i = 0; i < exprCaptures.Count; i++)
            {
                var exprText = exprCaptures[i].Value.Trim();
                var nextText = nextCaptures[i].Value.Trim();

                IEvaluate <TSource> expr;

                if (Regex.IsMatch(exprText, @"^\(.*\)$"))
                {
                    expr = CompileLogicalExpression <TSource, TToken>(exprText.Substring(1, exprText.Length - 2), pathToken);
                }
                else
                {
                    var exprMatch = exprParser.Match(exprText);

                    if (exprMatch == null || !exprMatch.Success)
                    {
                        throw new Exception("Invalid expression \"" + exprText + "\".");
                    }

                    var leftText  = exprMatch.Groups["left"].Value.Trim();
                    var opText    = exprMatch.Groups["op"].Value.Trim();
                    var rightText = exprMatch.Groups["right"].Value.Trim();

                    if (string.IsNullOrEmpty(opText))
                    {
                        // No operator, so this is a truthy property or constant check.

                        object value;
                        if (JavaScriptHelpers.TryParseConstant(leftText, out value))
                        {
                            expr = new TruthyConstantExpression <TSource>(new ConstantToken <TSource>(value));
                        }
                        else
                        {
                            expr = new PathExpression <TSource>(pathToken(leftText));
                        }
                    }
                    else
                    {
                        // Parse the comparison operator.
                        LogicalOperator op = ParseLogicalOperator(opText);

                        // Parse the left-hand token.
                        Token <TSource> leftToken;
                        object          leftValue;
                        if (JavaScriptHelpers.TryParseConstant(leftText, out leftValue))
                        {
                            leftToken = new ConstantToken <TSource>(leftValue);
                        }
                        else
                        {
                            leftToken = pathToken(leftText);
                        }

                        // Parse the right-hand token.
                        Token <TSource> rightToken;
                        object          rightValue;
                        if (JavaScriptHelpers.TryParseConstant(rightText, out rightValue))
                        {
                            rightToken = new ConstantToken <TSource>(rightValue);
                        }
                        else
                        {
                            rightToken = pathToken(rightText);
                        }

                        // Create the expression from "left op right".
                        expr = new CompareExpression <TSource>(leftToken, op, rightToken);
                    }
                }

                if (nextText == "&&" && andGroup == null)
                {
                    // There is currently no active and group and the next expression
                    // will be "ANDed", so start a new and group, beginning with this expression.
                    andGroup = AndExpressionGroup <TSource> .Begin(expr);
                }
                else if (andGroup != null)
                {
                    // There is an active and group expression, so add this expression to it.
                    andGroup.And(expr);
                }
                else if (result != null)
                {
                    // There is currently a result, so or it with this expression.
                    result = result.Or(expr);
                }
                else
                {
                    // There is currently no result, so use this expression as the result.
                    result = new TruthyExpressionWrapper <TSource>(expr);
                }

                // Add the existing group if we have reached the end of the expression, or the next expression will be "ORed".
                if ((string.IsNullOrEmpty(nextText) || nextText == "||") && andGroup != null)
                {
                    if (result == null)
                    {
                        result = andGroup;
                    }
                    else
                    {
                        result = result.Or(andGroup);
                    }
                    andGroup = null;
                }
            }

            return(result);
        }
        private static OperationResult Add(ValueToken left, ValueToken right)
        {
            if (left is ConstantToken && right is ConstantToken)
            {
                var token = new ConstantToken(((ConstantToken)left).NumericValue + ((ConstantToken)right).NumericValue);

                return(OperationResult.CreateSuccess(token));
            }

            if (left is ConstantToken && right is VariableToken)
            {
                return(OperationResult.CreateSuccess(
                           new ExpressionToken(new List <Token> {
                    left, new BinaryOperationToken {
                        Value = "+"
                    }, right
                })
                           ));
            }

            if (left is ConstantToken && right is ExpressionToken)
            {
                var members = ((ExpressionToken)right).Members;

                var newExpression = new ExpressionToken(new List <Token>(members));

                if (members.Any(x => x is ConstantToken))
                {
                    var c = newExpression.Members.Where(x => x is ConstantToken).FirstOrDefault() as ConstantToken;

                    c.NumericValue += ((ConstantToken)left).NumericValue;
                }
                else
                {
                    newExpression.Members.AddRange(new List <Token> {
                        new BinaryOperationToken {
                            Value = "+"
                        }, left
                    });
                }

                return(OperationResult.CreateSuccess(newExpression));
            }

            if (left is ConstantToken && right is FractionToken)
            {
                return(OperationResult.CreateSuccess(
                           new ExpressionToken(new List <Token> {
                    left, new BinaryOperationToken {
                        Value = "+"
                    }, right
                })
                           ));
            }

            if (left is VariableToken && right is ConstantToken)
            {
                return(OperationResult.CreateSuccess(
                           new ExpressionToken(new List <Token> {
                    left, new BinaryOperationToken {
                        Value = "+"
                    }, right
                })
                           ));
            }

            if (left is VariableToken && right is VariableToken)
            {
                if (((VariableToken)left).Variables.Except(((VariableToken)right).Variables).Count() == 0)
                {
                    var token = new VariableToken(((VariableToken)left).Quotient + ((VariableToken)right).Quotient, ((VariableToken)left).Variables);

                    return(OperationResult.CreateSuccess(token));
                }
                else
                {
                    return(OperationResult.CreateSuccess(
                               new ExpressionToken(new List <Token> {
                        left, new BinaryOperationToken {
                            Value = "+"
                        }, right
                    })
                               ));
                }
            }

            if (left is VariableToken && right is ExpressionToken)
            {
                var members = ((ExpressionToken)right).Members;

                var newExpression = new ExpressionToken(new List <Token>(members));

                if (members.Any(x => x is VariableToken v && v.Variables.Except(((VariableToken)left).Variables).Count() == 0))
                {
                    var v = newExpression.Members
                            .Where(x => x is VariableToken v && v.Variables.Except(((VariableToken)left).Variables).Count() == 0)
                            .FirstOrDefault() as VariableToken;

                    v.Quotient += ((VariableToken)left).Quotient;
                }
                else
                {
                    newExpression.Members.AddRange(new List <Token> {
                        new BinaryOperationToken {
                            Value = "+"
                        }, left
                    });
                }

                return(OperationResult.CreateSuccess(newExpression));
            }
示例#15
0
        public override string EvaluateConstant(ConstantToken token)
        {
            string symbol = token.Symbol == ParserSymbols.Pi ? "&pi;" : token.Symbol;

            return($"<mi>{symbol}</mi>");
        }
示例#16
0
 public override double EvaluateConstant(ConstantToken token) => ConstantsDict[token.Symbol];
示例#17
0
 public override Expression EvaluateConstant(ConstantToken token)
 => ConstantsDict[token.Symbol];
示例#18
0
 public override string EvaluateConstant(ConstantToken token) => token.Symbol;
示例#19
0
 public ConstantToken Calculate(ConstantToken x)
 {
     return(new ConstantToken(function(x.Value)));
 }
示例#20
0
 public NullOutput(ConstantToken instance)
 {
     _instance = instance;
 }
示例#21
0
 public override BigDecimal EvaluateConstant(ConstantToken token)
 {
     return(DecimalEvaluator.ConstantsDict[token.Symbol]);
 }