Пример #1
0
        public void CompileAndRun()
        {
            DisplayResults item = _singleton.Results[_singleton.Results.Count - 1];

            _singleton._page_calc.DoScroll(item);

            string plain_ole_command = _calculation_buffer[_calculation_buffer.Count - 1];

            calculatorParser parser = Parser(plain_ole_command);
            IParseTree       tree   = parser.expressionResult();

            IParseTree[] all_nodes = DFSVisitor.DFS(tree as ParserRuleContext).ToArray();

            if (CheckForExceptions(plain_ole_command, parser, tree, all_nodes))
            {
                return;
            }
            if (CheckForErrorToken(plain_ole_command, parser, tree, all_nodes))
            {
                return;
            }
            if (CheckForResult(plain_ole_command, parser, tree, all_nodes))
            {
                return;
            }

            string result = "Unknown.";

            Results[Results.Count - 1].result.Text = BuildFormattedCommandAndResult(plain_ole_command, 0, result);
            NotifyPropertyChanged("Results");
        }
Пример #2
0
        private void InDigit(string digit)
        {
            DisplayResults item = _singleton.Results[_singleton.Results.Count - 1];

            _singleton._page_calc.DoScroll(item);

            string plain_ole_command = _calculation_buffer[_calculation_buffer.Count - 1] + digit;

            _calculation_buffer[_calculation_buffer.Count - 1] = plain_ole_command;
            int ErrorPos = plain_ole_command.Length;

            byte[]           byteArray = Encoding.UTF8.GetBytes(plain_ole_command);
            calculatorParser pp        = new calculatorParser(
                new CommonTokenStream(
                    new calculatorLexer(
                        new AntlrInputStream(
                            new StreamReader(
                                new MemoryStream(byteArray)).ReadToEnd()))));
            IParseTree   tree   = pp.expressionResult();
            ITokenStream ts     = pp.TokenStream;
            string       result = AllTokens(ts).Reverse().Skip(1).First().Text;

            Results[Results.Count - 1].result.Text = BuildFormattedCommandAndResult(plain_ole_command, ErrorPos, result);
            NotifyPropertyChanged("Results");
        }
Пример #3
0
 /// <summary>
 /// Using http://programming-pages.com/2013/12/14/antlr-4-with-c-and-visual-studio-2012/ as a guide.
 /// </summary>
 /// <param name="args"></param>
 static void Main(string[] args)
 {
     string test = "a = 10*10";
     var input = new AntlrInputStream(test);
     var lexer = new calculatorLexer(input);
     CommonTokenStream tokens = new CommonTokenStream(lexer);
     var parser = new calculatorParser(tokens);
     var tree = parser.equation();
     Console.WriteLine(tree.ToStringTree(parser));
 }
Пример #4
0
        private calculatorParser Parser(string plain_old_command)
        {
            byte[]           byteArray = Encoding.UTF8.GetBytes(plain_old_command);
            calculatorParser pp        = new calculatorParser(
                new CommonTokenStream(
                    new calculatorLexer(
                        new AntlrInputStream(
                            new StreamReader(
                                new MemoryStream(byteArray)).ReadToEnd()))));

            pp.ErrorHandler = new MyErrorStrategy();
            return(pp);
        }
Пример #5
0
        public Value CalculateFormula(string formula)
        {
            AntlrInputStream  input  = new AntlrInputStream(formula); //2. parse is to AntlrIS
            calculatorLexer   lexer  = new calculatorLexer(input);    //3. lexer created from AntlrIS
            CommonTokenStream tokens = new CommonTokenStream(lexer);  //4. want to save tokens from the lexer
            calculatorParser  parser = new calculatorParser(tokens);  //5. feed these tokens from lexer when creating the parser
            IParseTree        tree   = parser.block();                //6. run parser using parser.prog() and save output in IParseTree
            //Console.WriteLine(tree.ToStringTree(parser));           //7.
            CalcVisitor visitor = new CalcVisitor();                  //8. CalcVisitor will do the evaluations
            Value       ret     = visitor.Visit(tree.GetChild(0));

            //Console.WriteLine(ret);             //z. CalcVisitor performs the actual evaluations + then write output
            return(ret);
        }
Пример #6
0
        static void Main(string[] args)
        {
            StreamReader      inputStream = new StreamReader(Console.OpenStandardInput()); //1. type in our expressions
            AntlrInputStream  input       = new AntlrInputStream(inputStream.ReadLine());  //2. parse is to AntlrIS
            calculatorLexer   lexer       = new calculatorLexer(input);                    //3. lexer created from AntlrIS
            CommonTokenStream tokens      = new CommonTokenStream(lexer);                  //4. want to save tokens from the lexer
            calculatorParser  parser      = new calculatorParser(tokens);                  //5. feed these tokens from lexer when creating the parser
            IParseTree        tree        = parser.block();                                //6. run parser using parser.prog() and save output in IParseTree
            //Console.WriteLine(tree.ToStringTree(parser));           //7.
            CalcVisitor visitor = new CalcVisitor();                                       //8. CalcVisitor will do the evaluations

            //Console.WriteLine("Tree: " + visitor.Visit(tree.GetChild(0)));             //z. CalcVisitor performs the actual evaluations + then write output
            //dont dropout before i can see return
            Console.ReadKey();
        }
Пример #7
0
        private bool CheckForErrorToken(string plain_ole_command, calculatorParser parser, IParseTree tree, IParseTree[] all_nodes)
        {
            IEnumerable <IParseTree> eni_nodes_iterator = all_nodes.Where((IParseTree n) =>
            {
                ErrorNodeImpl nn = n as ErrorNodeImpl;
                return(nn != null);
            });

            IParseTree[] all_eni_nodes_iterator = eni_nodes_iterator.ToArray();
            if (!all_eni_nodes_iterator.Any())
            {
                return(false);
            }

            // For now, report nothing if there isn't an equal.
            foreach (var en in all_eni_nodes_iterator)
            {
                ErrorNodeImpl eni = en as ErrorNodeImpl;
                if (eni != null)
                {
                    if (eni.GetText() == "<missing '='>")
                    {
                        return(false);
                    }
                }
            }

            var enn = all_eni_nodes_iterator.First() as ErrorNodeImpl;

            if (enn == null)
            {
                return(false);
            }

            int ErrorPos = enn.Payload.StartIndex;

            if (ErrorPos < 0)
            {
                ErrorPos = 0;
            }

            string result = "Extraneous input.";

            Results[Results.Count - 1].result.Text = BuildFormattedCommandAndResult(plain_ole_command, ErrorPos, result);
            NotifyPropertyChanged("Results");

            return(true);
        }
Пример #8
0
        private bool CheckForExceptions(string plain_ole_command, calculatorParser parser, IParseTree tree, IParseTree[] all_nodes)
        {
            IEnumerable <IParseTree> re_nodes_iterator = all_nodes.Where((IParseTree n) =>
            {
                ParserRuleContext nn = n as ParserRuleContext;
                if (nn == null)
                {
                    return(false);
                }
                return(nn.exception != null);
            });

            IParseTree[] all_re_nodes = re_nodes_iterator.ToArray();
            if (all_re_nodes.Length == 0)
            {
                return(false);
            }

            RecognitionException re = (all_re_nodes.First() as ParserRuleContext)?.exception;

            if (re.OffendingToken.Type == calculatorParser.Eof)
            {
                return(false);
            }

            IntervalSet s;

            (parser.ErrorHandler as MyErrorStrategy).LASet.TryGetValue(re, out s);
            string error_str = "Expecting " + s.ToString(parser.Vocabulary);
            int    ErrorPos  = re.OffendingToken.StartIndex;

            string result = error_str;

            Results[Results.Count - 1].result.Text = BuildFormattedCommandAndResult(plain_ole_command, ErrorPos, result);
            NotifyPropertyChanged("Results");

            return(true);
        }
Пример #9
0
        private bool CheckForResult(string plain_ole_command, calculatorParser parser, IParseTree tree, IParseTree[] all_nodes)
        {
            string result   = "";
            int    ErrorPos = plain_ole_command.Length;

            // Find last good term.
            try
            {
                ComputeCompleteness completeness_visitor = new ComputeCompleteness();
                completeness_visitor.Visit(tree);

                ComputeLinqExpr linq_visitor = new ComputeLinqExpr(completeness_visitor);
                Expression      top_expr     = linq_visitor.Visit(tree);

                var list = all_nodes.Where((nn) =>
                {
                    ParserRuleContext prc = nn as ParserRuleContext;
                    if (prc == null)
                    {
                        return(false);
                    }
                    bool r;
                    if (!completeness_visitor.Results.TryGetValue(prc, out r))
                    {
                        return(false);
                    }
                    return(r);
                });
                IParseTree[] find = list.ToArray();
                if (find.Length == 0)
                {
                    return(false);
                }

                ParserRuleContext child = find.Reverse().First() as ParserRuleContext;
                // Grab parent as partial results are valuable.
                ParserRuleContext parent = child.Parent as ParserRuleContext;

                // Eval.
                try
                {
                    Expression exp = null;
                    linq_visitor.Results.TryGetValue(parent != null ? parent : child, out exp);
                    Type     type          = exp.Type;
                    Delegate compiled_expr = Expression.Lambda(exp, null).Compile();
                    var      res           = compiled_expr.DynamicInvoke();
                    result = res.ToString();
                }
                catch (Exception e)
                {
                }

                //Res res;
                //visitor.Results.TryGetValue(parent != null ? parent : child, out res);
                //result = res.Value.ToString();
            }
            catch (Helpers.EvaluationException e)
            {
                ErrorPos = e.ErrorPos;
                result   = e.Message;
            }
            catch (Exception e)
            {
                ErrorPos = 0;
                result   = e.Message;
            }

            Results[Results.Count - 1].result.Text = BuildFormattedCommandAndResult(plain_ole_command, ErrorPos, result);
            NotifyPropertyChanged("Results");

            return(true);
        }