예제 #1
0
        public static IEnumerable <Log> Kill(string input)
        {
            var dot    = new DotTreeGenerator();
            var result = new List <Log>();

            Print(input);

            input = input.ToLowerInvariant().Trim();
            if (Cache.ContainsKey(input))
            {
                result = Cache[input].ToList();
            }
            else
            {
                var parser = ParseWithASTParser(input);
                var tree   = parser.evaluate().Tree;
                PrintString(dot.ToDot(tree));
                Parse(tree, result);
                Cache.Add(input, result);
            }

            TexasRanger.ValidateLogs(result);
            result.ForEach(x => Print(x.ToString()));

            foreach (var log in result)
            {
                log.OriginalInput = input;
                yield return(log.Return());
            }
        }
예제 #2
0
        public static void Loop2()
        {
            bool         exit   = false;
            string       input  = "";
            KermitParser parser = new KermitParser(null);

            //parser.TreeAdaptor = new KermitAdaptor();
            while (!exit)
            {
                if (input == string.Empty)
                {
                    Console.Write("> ");
                }
                else
                {
                    Console.Write(".. ");
                }
                input += Console.ReadLine() + "\n";
                ANTLRStringStream  stream = new ANTLRStringStream(input);
                KermitLexer        lexer  = new KermitLexer(stream);
                TokenRewriteStream tokens = new TokenRewriteStream(lexer);
                parser.TokenStream = tokens;
                try
                {
                    AstParserRuleReturnScope <KermitAST, CommonToken> result = parser.program();
                    var tree             = (CommonTree)result.Tree;
                    DotTreeGenerator gen = new DotTreeGenerator();
                    Console.WriteLine("{0}", gen.ToDot(tree));
                    input = "";

                    //Console.WriteLine(globalScope.ToString());
                }
                catch (PartialStatement)
                {
                }
                catch (ParserException e)
                {
                }
            }
        }
예제 #3
0
        public void TestCreateDot()
        {
            ANTLRStringStream      input  = new ANTLRStringStream("3 * x");
            SimpleExpressionLexer  lexer  = new SimpleExpressionLexer(input);
            CommonTokenStream      tokens = new CommonTokenStream(lexer);
            SimpleExpressionParser parser = new SimpleExpressionParser(tokens);
            var result = parser.expression();

            var tree    = result.Tree;
            var adaptor = parser.TreeAdaptor;

            DotTreeGenerator gen      = new DotTreeGenerator();
            string           output   = gen.ToDot(tree, adaptor);
            string           newline  = Environment.NewLine;
            string           expected =
                @"digraph {" + newline
                + newline
                + @"	ordering=out;"+ newline
                + @"	ranksep=.4;"+ newline
                + @"	bgcolor=""lightgrey""; node [shape=box, fixedsize=false, fontsize=12, fontname=""Helvetica-bold"", fontcolor=""blue"""+ newline
                + @"		width=.25, height=.25, color=""black"", fillcolor=""white"", style=""filled, solid, bold""];"+ newline
                + @"	edge [arrowsize=.5, color=""black"", style=""bold""]"+ newline
                + newline
                + @"  n0 [label=""""];" + newline
                + @"  n1 [label=""*""];" + newline
                + @"  n1 [label=""*""];" + newline
                + @"  n2 [label=""3""];" + newline
                + @"  n3 [label=""x""];" + newline
                + @"  n4 [label=""""];" + newline
                + newline
                + @"  n0 -> n1 // """" -> ""*""" + newline
                + @"  n1 -> n2 // ""*"" -> ""3""" + newline
                + @"  n1 -> n3 // ""*"" -> ""x""" + newline
                + @"  n0 -> n4 // """" -> """"" + newline
                + newline
                + @"}" + newline
                + @"";

            Assert.AreEqual(expected, output);
        }
예제 #4
0
        public static void Main(string [] args)
        {
            String            inputString = " Lot --> A t(4,5,6) extrude(rand(2,32)) B ";
            ANTLRStringStream input       = new ANTLRStringStream(inputString);

            //Stream inputStream = Console.OpenStandardInput ();
            //ANTLRInputStream input = new ANTLRInputStream (inputStream);
            CGALexer          lexer  = new CGALexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            CGAParser         parser = new CGAParser(tokens);                           // Create parser
            var result = parser.ruleDefinition();

            CommonTree Tree = (CommonTree)result.Tree;

            Console.WriteLine(Tree.ToStringTree());                                   // Print out the tree

            DotTreeGenerator gen = new DotTreeGenerator();
            var st = gen.ToDot(Tree);

            Console.WriteLine(st);
            //Console.WriteLine (TreeUtilities.toTree (inputStream).ToStringTree());

            //Preorder (Tree, 0);                                             // Print out the tree with TAB GRAPH
        }
예제 #5
0
        public VM.CompiledScript Compile(ICharStream input)
        {
            try
            {
                LSLTreeAdaptor lslAdaptor = new LSLTreeAdaptor();


                //
                // Initial parse and AST creation
                //
                LSLLexer          lex    = new LSLLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                LSLParser         p      = new LSLParser(tokens);
                p.TreeAdaptor        = lslAdaptor;
                p.TraceDestination   = _traceRedirect;
                lex.TraceDestination = _traceRedirect;
                LSLParser.prog_return r = p.prog();

                if (p.NumberOfSyntaxErrors > 0)
                {
                    _listener.Error(Convert.ToString(p.NumberOfSyntaxErrors) + " syntax error(s)");
                    return(null);
                }


                //
                // Definitions
                //
                CommonTree           t     = (CommonTree)r.Tree;
                CommonTreeNodeStream nodes = new CommonTreeNodeStream(lslAdaptor, t);
                nodes.TokenStream = tokens;

                SymbolTable symtab = new SymbolTable(tokens, Defaults.SystemMethods.Values, DefaultConstants.Constants.Values);
                symtab.StatusListener = _listener;

                Def def = new Def(nodes, symtab);
                def.TraceDestination = _traceRedirect;
                def.Downup(t);

                nodes.Reset();

                if (_listener.HasErrors() || def.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }


                //
                // Type and more semantic checks
                //
                Compiler.Types types = new Compiler.Types(nodes, symtab);
                types.TraceDestination = _traceRedirect;
                types.Downup(t);

                nodes.Reset();

                if (_listener.HasErrors() || types.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }


                StringTemplateGroup templates;
                using (TextReader fr = new StreamReader(Path.Combine(_templatePath, "ByteCode.stg")))
                {
                    templates = new StringTemplateGroup(fr);
                    fr.Close();
                }

                if (_outputAstGraph)
                {
                    DotTreeGenerator dotgen = new DotTreeGenerator();
                    string           dot    = dotgen.ToDot(t);

                    TextWriter tw = new StreamWriter("ast.txt");
                    tw.WriteLine(dot);
                    tw.Close();
                }

                Analyze analyze = new Analyze(nodes, symtab);
                analyze.TraceDestination = _traceRedirect;
                analyze.Downup(t);

                nodes.Reset();

                foreach (Compiler.BranchAnalyze.FunctionBranch b in analyze.FunctionBranches.Where(pred => pred.Type != null))
                {
                    if (!b.AllCodePathsReturn())
                    {
                        if (_listener != null)
                        {
                            _listener.Error("line: " + b.Node.Line + ":" +
                                            b.Node.CharPositionInLine + " " + b.Node.Text + "(): Not all control paths return a value");
                        }
                    }
                }

                if (_listener.HasErrors() || analyze.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }


                //
                // Bytecode generation
                //
                Gen g = new Gen(nodes, symtab);
                g.TemplateGroup    = templates;
                g.TraceDestination = _traceRedirect;

                Gen.script_return ret = g.script();

                if (_listener.HasErrors() || g.NumberOfSyntaxErrors > 0)
                {
                    return(null);
                }

                if (ret.Template == null)
                {
                    return(null);
                }

                StringTemplate template = ret.Template;

                if (_byteCodeDebugging)
                {
                    _byteCode = template.ToString();
                }

                //
                // Bytecode compilation
                //
                AssemblerLexer    alex    = new AssemblerLexer(new ANTLRStringStream(template.ToString()));
                CommonTokenStream atokens = new CommonTokenStream(alex);
                AssemblerParser   ap      = new AssemblerParser(atokens);
                BytecodeGenerator bcgen   = new BytecodeGenerator(Defaults.SystemMethods.Values);

                ap.SetGenerator(bcgen);
                ap.TraceDestination = _traceRedirect;

                try
                {
                    ap.program();

                    if (_listener.HasErrors() || p.NumberOfSyntaxErrors > 0)
                    {
                        _listener.Error(Convert.ToString(ap.NumberOfSyntaxErrors) + " bytecode generation error(s)");
                        return(null);
                    }

                    return(bcgen.Result);
                }
                catch (GenerationException e)
                {
                    _listener.Error(e.Message);
                }

                return(null);
            }
            catch (TooManyErrorsException e)
            {
                _listener.Error(String.Format("Too many errors {0}", e.InnerException.Message));
            }
            catch (RecognitionException e)
            {
                _listener.Error("line: " + e.Line.ToString() + ":" + e.CharPositionInLine.ToString() + " " + e.Message);
            }
            catch (Exception e)
            {
                string message = e.Message;

                while ((e = e.InnerException) != null)
                {
                    message += "\n" + e.Message;
                }

                _listener.Error(message);
            }

            return(null);
        }
예제 #6
0
        static void Main(string[] args)
        {
            string code = @"

when [ToPractice] is 'cardiology of bob'

*[Insurance] is 'blue cross' +[Insurance] is 'blah' +[Insurance] is 'blah3'
*[DocumentCount] greater than 1
*[DocumentCount] less than 3

when [ToPractice] is 'test'
*[DocumentCount] greater than 10
            
";

            var lexer  = new DslLexer(new ANTLRStringStream(code));
            var tokens = new CommonTokenStream(lexer);

            var parser = new DslParser(tokens);

            parser.TreeAdaptor = new BridgeAdapter();
            var result = parser.program();

            //Generate .dot graph. View it at http://mdaines.github.io/viz.js/
            var graphGenerator = new DotTreeGenerator();
            var dotFile        = graphGenerator.ToDot(result.Tree);

            if (lexer.Errors.Count > 0)
            {
                foreach (var error in lexer.Errors)
                {
                    Console.WriteLine(error);
                }

                return;
            }

            if (parser.Errors.Count > 0)
            {
                foreach (var error in parser.Errors)
                {
                    Console.WriteLine(error);
                }

                return;
            }

            var bridge = new BridgeVisitor(result.Tree);
            var ast    = bridge.CreateAst();

            var codeGen  = new CodeGenVisitor(ast);
            var codeUnit = codeGen.Generate();

            //Code Gen;
            string codeString = Persist.ToCSharpSource(codeUnit);

            //Compile
            var persist  = new Persist(codeUnit);
            var assembly = persist.ToAssembly();

            if (persist.Errors.Count > 0)
            {
                foreach (var error in persist.Errors)
                {
                    Console.WriteLine(error);
                }

                return;
            }

            //Run
            var instance   = assembly.CreateInstance("Code");
            var method     = assembly.GetType("Code").GetMethod("Run");
            var methodArgs = new Args {
                ToPractice = "test", Insurance = "blue cross", DocumentCount = 5
            };
            var codeResult = (bool)method.Invoke(instance, new[] { methodArgs });

            Console.WriteLine(codeResult);
        }
예제 #7
0
        public string Compile(ICharStream input)
        {
            try
            {
                LSLTreeAdaptor lslAdaptor = new LSLTreeAdaptor();

                LSLLexer          lex    = new LSLLexer(input);
                CommonTokenStream tokens = new CommonTokenStream(lex);
                LSLParser         p      = new LSLParser(tokens);
                p.TreeAdaptor        = lslAdaptor;
                p.TraceDestination   = _traceDestination;
                lex.TraceDestination = _traceDestination;
                LSLParser.prog_return r = p.prog();

                if (p.NumberOfSyntaxErrors > 0)
                {
                    if (_listener != null)
                    {
                        _listener.Error(Convert.ToString(p.NumberOfSyntaxErrors) + " syntax error(s)");
                    }

                    return(null);
                }

                CommonTree           t     = (CommonTree)r.Tree;
                CommonTreeNodeStream nodes = new CommonTreeNodeStream(lslAdaptor, t);
                nodes.TokenStream = tokens;

                SymbolTable symtab = new SymbolTable(tokens, Defaults.SystemMethods.Values, DefaultConstants.Constants.Values);

                if (this.Listener != null)
                {
                    symtab.StatusListener = this.Listener;
                }

                Def def = new Def(nodes, symtab);
                def.TraceDestination = _traceDestination;
                def.Downup(t);

                CommonTreeNodeStream nodes2 = new CommonTreeNodeStream(lslAdaptor, t);
                nodes2.TokenStream = tokens;

                Types types = new Types(nodes2, symtab);
                types.TraceDestination = _traceDestination;
                types.Downup(t);

                if (_listener != null)
                {
                    if (_listener.HasErrors())
                    {
                        return(null);
                    }
                }

                CommonTreeNodeStream nodes4 = new CommonTreeNodeStream(lslAdaptor, t);
                nodes4.TokenStream = tokens;

                CommonTreeNodeStream nodes3 = new CommonTreeNodeStream(lslAdaptor, t);
                nodes3.TokenStream = tokens;

                TextReader          fr        = new StreamReader("ByteCode.stg");
                StringTemplateGroup templates = new StringTemplateGroup(fr);
                fr.Close();

                DotTreeGenerator dotgen = new DotTreeGenerator();
                string           dot    = dotgen.ToDot(t);

                TextWriter tw = new StreamWriter("ast.txt");
                tw.WriteLine(dot);
                tw.Close();

                Analyze analyze = new Analyze(nodes4, symtab);
                types.TraceDestination = _traceDestination;
                analyze.Downup(t);

                foreach (FunctionBranch b in analyze.FunctionBranches.Where(pred => pred.Type != null))
                {
                    if (!b.AllCodePathsReturn())
                    {
                        if (_listener != null)
                        {
                            _listener.Error("line: " + b.Node.Line + ":" +
                                            b.Node.CharPositionInLine + " " + b.Node.Text + "(): Not all control paths return a value");
                        }
                    }
                }

                Gen g = new Gen(nodes3, symtab);
                g.TemplateGroup    = templates;
                g.TraceDestination = _traceDestination;
                StringTemplate template = g.script().Template;


                if (template != null)
                {
                    string bcOut = template.ToString();
                    Console.WriteLine("** byte code **\n" + bcOut);
                    return(bcOut);
                }
            }
            catch (TooManyErrorsException e)
            {
                if (_listener != null)
                {
                    _listener.Error(String.Format("Too many errors {0}", e.InnerException.Message));
                }
            }
            catch (RecognitionException e)
            {
                if (_listener != null)
                {
                    _listener.Error("line: " + e.Line.ToString() + ":" + e.CharPositionInLine.ToString() + " " + e.Message);
                }
            }
            catch (Exception e)
            {
                if (_listener != null)
                {
                    _listener.Error(e.Message);
                }
            }

            return(null);
        }