Ejemplo n.º 1
0
        internal void ParseRoute(string routeString, out IMessageSource messageSource, out string condition, out Endpoint endpoint)
        {
            var errorListener = new ErrorListener();
            var input         = new AntlrInputStream(routeString);
            var lexer         = new RouteLexer(input);
            var tokens        = new CommonTokenStream(lexer);
            var parser        = new RouteParser(tokens);

            parser.RemoveErrorListeners();
            parser.AddErrorListener(errorListener);
            IParseTree tree = parser.route();

            errorListener.Validate();

            var walker   = new ParseTreeWalker();
            var listener = new RouteParserListener(this.endpointFactory);

            walker.Walk(listener, tree);

            condition     = listener.Condition ?? DefaultCondition;
            messageSource = CustomMessageSource.Create(listener.Source);
            endpoint      = listener.Endpoint;
        }
Ejemplo n.º 2
0
        public static string Parser(string filter)
        {
            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            if (String.IsNullOrEmpty(filter))
            {
                return(filter);
            }

            var stream = new AntlrInputStream(filter);
            var lexer  = new ODataLexer(stream);
            var tokens = new CommonTokenStream(lexer);
            var parser = new ODataParser(tokens);
            var tree   = parser.program();

            var visitor = new ODataFilterVisitor();
            var result  = visitor.Visit(tree);

            return(result?.ToString());
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var code             = "3 - (4)";
            var antlrInputStream = new AntlrInputStream(code);
            var lexer            = new Combined1Lexer(antlrInputStream);
            var cts    = new CommonTokenStream(lexer);
            var parser = new Combined1Parser(cts);


            var dynamicMethod = new DynamicMethod("test", typeof(int), Type.EmptyTypes);
            var il            = dynamicMethod.GetILGenerator();

            var visitor = new MyVisitor(il);

            visitor.Visit(parser.expression());
            il.Emit(OpCodes.Ret);

            var method = (Func <int>)dynamicMethod.CreateDelegate(typeof(Func <int>));

            Console.WriteLine(method());

            Console.ReadKey();
        }
Ejemplo n.º 4
0
        private RuleEngineParser.JRuleContext BuildContext(string expressionText)
        {
            var lexerErrorListener = new LexerErrorListener();
            var antlrInputStream   = new AntlrInputStream(expressionText);
            var lexer = new RuleEngineLexer(antlrInputStream);

            lexer.AddErrorListener(lexerErrorListener);

            var parserErrorListener = new ParserErrorListener();
            var commonTokenStream   = new CommonTokenStream(lexer);
            var parser = new RuleEngineParser(commonTokenStream);

            parser.AddErrorListener(parserErrorListener);

            var context = parser.jRule();

            if (context.exception != null)
            {
                throw new Exception(string.Join(Environment.NewLine, lexerErrorListener.Errors.Union(parserErrorListener.Errors)), context.exception);
            }

            return(context);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get parsed tree nodes from text by antlr4 engine.
        /// </summary>
        /// <param name="text">Original text which will be parsed.</param>
        /// <returns>Parsed tree nodes.</returns>
        private static LGFileParser.FileContext GetFileContentContext(string text, string id)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            var input = new AntlrInputStream(text);
            var lexer = new LGFileLexer(input);

            lexer.RemoveErrorListeners();

            var tokens = new CommonTokenStream(lexer);
            var parser = new LGFileParser(tokens);

            parser.RemoveErrorListeners();
            var listener = new ErrorListener(id);

            parser.AddErrorListener(listener);
            parser.BuildParseTree = true;

            return(parser.file());
        }
        /// <summary>
        /// Parse LG content and achieve the AST.
        /// </summary>
        /// <param name="resource">LG resource.</param>
        /// <returns>The abstract syntax tree of lg file.</returns>
        public static IParseTree AntlrParseTemplates(LGResource resource)
        {
            if (string.IsNullOrEmpty(resource.Content))
            {
                return(null);
            }

            var input = new AntlrInputStream(resource.Content);
            var lexer = new LGFileLexer(input);

            lexer.RemoveErrorListeners();

            var tokens = new CommonTokenStream(lexer);
            var parser = new LGFileParser(tokens);

            parser.RemoveErrorListeners();
            var listener = new ErrorListener(resource.FullName);

            parser.AddErrorListener(listener);
            parser.BuildParseTree = true;

            return(parser.file());
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            StreamReader      stream = new StreamReader(args[0]);
            AntlrInputStream  antlr  = new AntlrInputStream(stream.ReadToEnd());
            GLOSSALexer       lexer  = new GLOSSALexer(antlr);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            GLOSSAParser      parser = new GLOSSAParser(tokens);
            IParseTree        tree   = parser.file();

            ParseTreeWalker        walker           = new ParseTreeWalker();
            GLOSSAParseTreePrinter parseTreePrinter = new GLOSSAParseTreePrinter("parsetree.dot");

            walker.Walk(parseTreePrinter, tree);

            parseTreePrinter.CallGraphViz("parsetree.dot", "parsetree.png");

            IList <IToken> tokensList = tokens.GetTokens();

            foreach (IToken token in tokensList)
            {
                Console.WriteLine(token);
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            using (StreamReader fileStream = new StreamReader(args[0]))
            {
                AntlrInputStream inputStream = new AntlrInputStream(fileStream);

                var          lexer             = new DomainLexer(inputStream);
                var          commonTokenStream = new CommonTokenStream(lexer);
                DomainParser parser            = new DomainParser(commonTokenStream);

                //parser.RemoveErrorListeners();
                //parser.AddErrorListener(new ErrorListener()); // add ours
                //var sw = new Stopwatch();
                //sw.Start();
                var tree = parser.domain();
                //sw.Stop();
                //Console.WriteLine(sw.ElapsedMilliseconds);
                //Console.WriteLine(res);
                ParseTreeWalker walker   = new ParseTreeWalker();
                var             listener = new DomainListener();
                walker.Walk(listener, tree);
            }
        }
Ejemplo n.º 9
0
        public static (IParseTree, Parser, Lexer) Try(string input)
        {
            var str      = new AntlrInputStream(input);
            var lexer    = new XMLLexer(str);
            var tokens   = new CommonTokenStream(lexer);
            var parser   = new XMLParser(tokens);
            var listener = new ErrorListener <IToken>(parser, lexer, tokens);

            parser.AddErrorListener(listener);
            var tree = parser.document();

            if (listener.had_error)
            {
                System.Console.Error.WriteLine("error in parse.");
            }
            else
            {
                System.Console.Error.WriteLine("parse completed.");
            }
            System.Console.Error.WriteLine(tokens.OutputTokens(lexer));
            System.Console.Error.WriteLine(tree.OutputTree(tokens));
            return(tree, parser, lexer);
        }
Ejemplo n.º 10
0
        public static void PrintTokens(string testString)
        {
            //Creating lexer.
            var chars = new AntlrInputStream(testString);
            var lexer = new storkLexer(chars);

            //Getting tokens.
            var tokens = lexer.GetAllTokens();

            //Getting lexer vocabulary.
            var vocab = lexer.Vocabulary;

            //Printing, for each token.
            Console.WriteLine("ANTLR Lexed Tokens:");
            foreach (var tok in tokens)
            {
                Console.WriteLine("[" + vocab.GetSymbolicName(tok.Type) + ", " + tok.Text + "]");
            }
            Console.WriteLine("");

            //Reset lexer so it can still be used.
            lexer.Reset();
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            try
            {
                string        input = "";
                StringBuilder text  = new StringBuilder();
                Console.WriteLine("Input the chat.");

                // to type the EOF character and end the input: use CTRL+D, then press <enter>
                // e.g.
                // hoge says fuga[Enter]
                // fuga says hoge[Enter]
                // CTRL+D
                while ((input = Console.ReadLine()) != "\u0004")
                {
                    text.AppendLine(input);
                }

                AntlrInputStream  inputStream       = new AntlrInputStream(text.ToString());
                SpeakLexer        speakLexer        = new SpeakLexer(inputStream);
                CommonTokenStream commonTokenStream = new CommonTokenStream(speakLexer);
                SpeakParser       speakParser       = new SpeakParser(commonTokenStream);

                SpeakParser.ChatContext chatContext = speakParser.chat();
                MySpeakVisitor          visitor     = new MySpeakVisitor();
                visitor.Visit(chatContext);

                foreach (var line in visitor.Lines)
                {
                    Console.WriteLine("{0} has said \"{1}\"", line.Person, line.Text);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";
            sPrograma     = this.textBox1.Text;
            var entrada = sPrograma + Environment.NewLine;

            byte[]             byteArray  = Encoding.ASCII.GetBytes(entrada);
            MemoryStream       stream     = new MemoryStream(byteArray);
            var                parametro1 = new AntlrInputStream(entrada);
            SIC_gramaticaLexer lex        = new SIC_gramaticaLexer(parametro1);

            //CREAMOS UN LEXER CON LA CADENA QUE ESCRIBIO EL USUARIO
            Antlr4.Runtime.CommonTokenStream tokens = new Antlr4.Runtime.CommonTokenStream(lex);
            //CREAMOS LOS TOKENS SEGUN EL LEXER CREADO
            SIC_gramaticaParser parser = new SIC_gramaticaParser(tokens);

            //CREAMOS EL PARSER CON LOS TOKENS CREADOS
            try
            {
                parser.programa();
                this.separarPrograma();
                this.separarEtiquetas();
                this.separarInstrucciones();
                this.separDirecciones();
                this.calcularDirecciones();
                this.crearTabSim();
                this.codigoOBJ();
                this.llenarDataGrid();
                this.buscarErrores();
                this.crearArchivo();
            }
            catch (Exception error)
            {
                //Console.Error.WriteLine(e.StackTrace);
                MessageBox.Show("A ocurrido un error inesperado " + error.Message);
            }
        }
Ejemplo n.º 13
0
        public DAEDefinition CompileDAE(string text)
        {
            compilerErrors = new List <ErrorMessage>();
            parameters     = new Dictionary <string, double>();
            variables      = new Dictionary <string, Variable>();
            FunctionTable.Init();
            //variables.Add("t", new Variable { Name = "t", InitialValue = 0.0, Initialized = true,VarType = Variable.Type.Algebraic,Count=0 });

            AntlrInputStream        inputStream = new AntlrInputStream(text);
            DAEImplicitGrammarLexer eqLexer     = new DAEImplicitGrammarLexer(inputStream);

            eqLexer.RemoveErrorListeners();
            ErrorListener <int> lexerListener = new ErrorListener <int>();

            eqLexer.AddErrorListener(lexerListener);
            CommonTokenStream        commonTokenStream = new CommonTokenStream(eqLexer);
            DAEImplicitGrammarParser eqParser          = new DAEImplicitGrammarParser(commonTokenStream);
            ErrorListener <IToken>   parserListener    = new ErrorListener <IToken>();

            eqParser.RemoveErrorListeners();
            eqParser.AddErrorListener(parserListener);
            DAEImplicitGrammarParser.CompileUnitContext eqContext = eqParser.compileUnit();
            compilerErrors = lexerListener.getErrors();
            if (compilerErrors.Count > 0)
            {
                throw new Exception("Lexer Error");
            }
            compilerErrors = parserListener.getErrors();
            if (compilerErrors.Count > 0)
            {
                throw new Exception("Parser error");
            }
            DAEImplicitGrammarVisitor visitor = new DAEImplicitGrammarVisitor();
            ASTNode root = visitor.VisitCompileUnit(eqContext);

            return(CompileDAE((RootNode)root));
        }
Ejemplo n.º 14
0
        static void Try(string ffn)
        {
            System.IO.StreamReader file = new System.IO.StreamReader(ffn);
            string line;

            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine("===== Expression =====");
                System.Console.WriteLine(line);
                var str      = new AntlrInputStream(line);
                var lexer    = new XPath31Lexer(str);
                var tokens   = new CommonTokenStream(lexer);
                var parser   = new XPath31Parser(tokens);
                var listener = new ErrorListener <IToken>(parser, lexer, tokens);
                parser.AddErrorListener(listener);
                var tree = parser.xpath();
                if (listener.had_error)
                {
                    System.Console.WriteLine("error in parse.");
                    System.Console.WriteLine(tokens.OutputTokens());
                    System.Console.WriteLine(tree.OutputTree(tokens));
                    return;
                }
                else
                {
                    System.Console.WriteLine(tokens.OutputTokens());
                    System.Console.WriteLine(tree.OutputTree(tokens));
                    System.Console.WriteLine("parse completed.");
                }
                string xpath = "//exprsingle";
                var    names = Antlr4.Runtime.Tree.Xpath.XPath.FindAll(tree, xpath, parser);
                foreach (var n in names)
                {
                    System.Console.WriteLine("match " + n.GetText());
                }
            }
        }
Ejemplo n.º 15
0
        public void VarDeclarationTests()
        {
            VariableEnvironment variables           = new VariableEnvironment();
            FunctionEnvironment functionEnvironment = new FunctionEnvironment();

            string            txt               = "int var";
            AntlrInputStream  inputStream       = new AntlrInputStream(txt);
            BogieLangLexer    lexer             = new BogieLangLexer(inputStream);
            CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
            BogieLangParser   parser            = new BogieLangParser(commonTokenStream);

            BogieLangParser.VarDeclarationContext varDeclarationContext = parser.varDeclaration();
            BogieLangBaseVisitor <object>         visitor = new BogieLangBaseVisitor <object>();

            visitor.Visit(varDeclarationContext);
            VarDeclaration varDeclaration = VarDeclaration.Compile(varDeclarationContext);

            varDeclaration.Execute(functionEnvironment, variables);
            Assert.True(variables["var"].BogieLangType == BogieLangType.INTEGER);
            Assert.True(variables["var"].Value == null);
            Assert.True(variables["var"].Identifer == "var");

            variables.Clear();
            txt                   = "int var=123";
            inputStream           = new AntlrInputStream(txt);
            lexer                 = new BogieLangLexer(inputStream);
            commonTokenStream     = new CommonTokenStream(lexer);
            parser                = new BogieLangParser(commonTokenStream);
            varDeclarationContext = parser.varDeclaration();
            visitor               = new BogieLangBaseVisitor <object>();
            visitor.Visit(varDeclarationContext);
            varDeclaration = VarDeclaration.Compile(varDeclarationContext);
            varDeclaration.Execute(functionEnvironment, variables);
            Assert.True(variables["var"].BogieLangType == BogieLangType.INTEGER);
            Assert.True((int)variables["var"].Value == 123);
            Assert.True(variables["var"].Identifer == "var");
        }
Ejemplo n.º 16
0
        private static void validationParse()
        {
            AntlrInputStream w3inputstream;

            var rulesChunk = DB.GetRuleValiations(100);

            foreach (var ruleValsPoco in rulesChunk)
            {
                w3inputstream = new AntlrInputStream(ruleValsPoco.xpath);
                var w3Lexer  = new XPath1W3Lexer(w3inputstream);
                var w3Tokens = new CommonTokenStream(w3Lexer);
                var w3Parser = new XPath1W3Parser(w3Tokens)
                {
                    BuildParseTree = true
                };
                var w3Tree = w3Parser.start();

                //w3tree.ToStringTree(w3parser);
                XPath1W3Visitor w3Visitor = new XPath1W3Visitor();

                ruleValsPoco.ConvertedCode = w3Visitor.Visit(w3Tree);

                w3inputstream = new AntlrFileStream(ruleValsPoco.xpathCondAlt);
                w3Lexer       = new XPath1W3Lexer(w3inputstream);
                w3Tokens      = new CommonTokenStream(w3Lexer);
                w3Parser      = new XPath1W3Parser(w3Tokens)
                {
                    BuildParseTree = true
                };
                w3Tree = w3Parser.start();

                //w3tree.ToStringTree(w3parser);
                w3Visitor = new XPath1W3Visitor();

                ruleValsPoco.ConvertedCondCode = w3Visitor.Visit(w3Tree);
            }
        }
        static public void RunModel(string inputText, ref List <ErrorMessage> errorList, ref List <string> output)
        {
            AntlrInputStream inputStream = new AntlrInputStream(inputText);

            PowerModel.NewModel.ModelGrammarLexer modelLexer = new PowerModel.NewModel.ModelGrammarLexer(inputStream);
            ErrorListener <int> lexerErrorListener           = new ErrorListener <int>();

            modelLexer.RemoveErrorListeners();
            modelLexer.AddErrorListener(lexerErrorListener);
            CommonTokenStream commonTokenStream = new CommonTokenStream(modelLexer);

            PowerModel.NewModel.ModelGrammarParser modelParser = new PowerModel.NewModel.ModelGrammarParser(commonTokenStream);
            ErrorListener <IToken> parserErrorListener         = new ErrorListener <IToken>();

            modelParser.RemoveErrorListeners();
            modelParser.AddErrorListener(parserErrorListener);

            PowerModel.NewModel.ModelGrammarParser.ModelContext modelContext = modelParser.model();
            errorList.AddRange(lexerErrorListener.GetErrors());
            errorList.AddRange(parserErrorListener.GetErrors());
            if (errorList.Count > 0)
            {
                return;
            }
            PowerModel.NewModel.Grammar.Visitor visitor = new PowerModel.NewModel.Grammar.Visitor();
            PowerModel.NewModel.Grammar.Node    root    = visitor.VisitModel(modelContext);
            var model = PowerModel.NewModel.ModelInterpreter.GetInstanse().Generate((PowerModel.NewModel.Grammar.ModelNode)root, ref errorList, ref output);

            if (errorList.Count > 0)
            {
                return;
            }
            string solverOutput = model.Solve();

            //string solverOutput = model.GetEquations();
            output.Add(solverOutput);
        }
Ejemplo n.º 18
0
        public Questionnaire BuildAST(string inputString)
        {
            MemoryStream inputStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString ?? ""));

            AntlrInputStream  antlrInputStream = new AntlrInputStream(inputStream);
            QLLexer           lexer            = new QLLexer(antlrInputStream);
            CommonTokenStream tokens           = new CommonTokenStream(lexer);

            _parser = new QLParser(tokens);

            //Replaxe lexer/parser error listeners
            lexer.RemoveErrorListeners();
            _parser.RemoveErrorListeners();
            lexer.AddErrorListener(new LexerErrorListener()
            {
                OnError = LexerErrors.Add
            });
            _parser.AddErrorListener(new ParserErrorListener()
            {
                OnError = ParserErrors.Add
            });

            //set manager on partial parser class
            _parser.SetIdManager(Memory);

            //build AST
            _parseTree = _parser.questionnaire();
            AST        = _parser.GetAST();

            //check for lexer/parser errors
            if (!LexerErrors.Any() && !ParserErrors.Any())
            {
                TypeChecker.Run(AST);
            }

            return(AST);
        }
Ejemplo n.º 19
0
        public IStatement Parse(string source)
        {
            var inputStream       = new AntlrInputStream(source);
            var lexer             = new FSQLLexer(inputStream);
            var commonTokenStream = new CommonTokenStream(lexer);
            var parser            = new FSQLParser(commonTokenStream);

            IStatement results = new Unimplemented(source);

            var stmtContext = parser.statement();


            //IProgramPart parseResults;
            try {
                results = Visit(stmtContext) as IStatement;
                if (results == null)
                {
                    throw new SyntaxErrorException($"Could not parse '{source}'.");
                }
            } catch (Exception) {
                if (!source.StartsWith("@_ ="))
                {
                    source = "@_ = " + source;
                    if (!source.EndsWith(";"))
                    {
                        source = source + ";";
                    }
                    results = Parse(source);
                }
                else
                {
                    throw;
                }
            }

            return(results);
        }
Ejemplo n.º 20
0
        public Tree Compile(string input)
        {
            var inputStream       = new AntlrInputStream(input);
            var casmLexer         = new CasmLexer(inputStream);
            var commonTokenStream = new CommonTokenStream(casmLexer);
            var casmParser        = new CasmParser(commonTokenStream);

            var progContext = casmParser.prog();
            var tree        = new Tree();

            var compilerListener = new CompilerListener(tree);

            var walker = new ParseTreeWalker();

            walker.Walk(compilerListener, progContext);

            // Replace immediate operands that have label placeholders with the label's position.
            var labelMap = new Dictionary <string, uint>();

            foreach (var label in tree.Nodes.OfType <Label>())
            {
                labelMap[label.Name] = label.Position;
            }

            foreach (var instruction in tree.Nodes.OfType <Instruction>())
            {
                foreach (var immediateOperand in instruction.Operands.OfType <ImmediateOperand>())
                {
                    if (immediateOperand.LabelName != null)
                    {
                        immediateOperand.Value = labelMap[immediateOperand.LabelName];
                    }
                }
            }

            return(tree);
        }
Ejemplo n.º 21
0
 private void PoeFilterInit(string path)
 {
     try
     {
         if (!string.IsNullOrEmpty(path))
         {
             using (var fileStream = new StreamReader(path))
             {
                 var input  = new AntlrInputStream(fileStream.ReadToEnd());
                 var lexer  = new PoeFilterLexer(input);
                 var tokens = new CommonTokenStream(lexer);
                 var parser = new PoeFilterParser.Model.PoeFilterParser(tokens);
                 parser.RemoveErrorListeners();
                 parser.AddErrorListener(new ErrorListener());
                 var tree = parser.main();
                 visitor = new PoeFilterVisitor(tree, GameController, Settings);
             }
         }
         else
         {
             Settings.Alternative.Value = false;
         }
     }
     catch (SyntaxErrorException ex)
     {
         Settings.FilePath.Value    = string.Empty;
         Settings.Alternative.Value = false;
         MessageBox.Show($"Line: {ex.Line}:{ex.CharPositionInLine}, {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         visitor = null;
     }
     catch (Exception ex)
     {
         Settings.FilePath.Value    = string.Empty;
         Settings.Alternative.Value = false;
         MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Ejemplo n.º 22
0
            public static TryCatch <SqlQuery> Parse(string text)
            {
                if (text == null)
                {
                    throw new ArgumentNullException(nameof(text));
                }

                AntlrInputStream  str    = new AntlrInputStream(text);
                sqlLexer          lexer  = new sqlLexer(str);
                CommonTokenStream tokens = new CommonTokenStream(lexer);
                sqlParser         parser = new sqlParser(tokens)
                {
                    ErrorHandler = ThrowExceptionOnErrors.Singleton,
                };
                ErrorListener <IToken> listener = new ErrorListener <IToken>(parser, lexer, tokens);

                parser.AddErrorListener(listener);

                sqlParser.ProgramContext programContext;
                try
                {
                    programContext = parser.program();
                }
                catch (Exception ex)
                {
                    return(TryCatch <SqlQuery> .FromException(ex));
                }

                if (listener.parseException != null)
                {
                    return(TryCatch <SqlQuery> .FromException(listener.parseException));
                }

                SqlQuery sqlQuery = (SqlQuery)CstToAstVisitor.Singleton.Visit(programContext);

                return(TryCatch <SqlQuery> .FromResult(sqlQuery));
            }
Ejemplo n.º 23
0
        /// <summary>
        /// Opens the TNS names file. This API includes an error list.
        /// </summary>
        /// <param name="tnsNamesFileInfo">The TNS names file information.</param>
        /// <param name="errors">The error list.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">tnsNamesFileInfo</exception>
        public static TnsNamesFile OpenTnsNamesFileIncludeErrors([NotNull] TnsNamesFileInfo tnsNamesFileInfo, out TnsNamesListenerErrorNode[] errors)
        {
            if (tnsNamesFileInfo == null)
            {
                throw new ArgumentNullException(nameof(tnsNamesFileInfo));
            }

            var listener = new TnsNamesListener();

            using (var fileStream = new FileStream(tnsNamesFileInfo.Filepath, FileMode.Open, FileAccess.Read))
            {
                var inputStream       = new AntlrInputStream(fileStream);
                var lexer             = new TnsNamesLexer(inputStream);
                var commonTokenStream = new CommonTokenStream(lexer);
                var parser            = new TnsNamesParser(commonTokenStream);

#if RELEASE
                lexer.ErrorListeners.Clear();
                parser.ErrorListeners.Clear();
#endif

                var parse = parser.configuration_file();
                ParseTreeWalker.Default.Walk(listener, parse);
            }

            // Convert internal representation to public API representation
            var tnsNames = from tnsNameNode in listener.TnsItems
                           let databaseAddressNodes = tnsNameNode.DatabaseAddresses
                                                      let databaseAddresses = databaseAddressNodes.Select(CreateDatabaseAddress).ToArray()
                                                                              let rawDescription = tnsNameNode.ParameterContext.parameterValue().children[1].GetText().ToUpperInvariant()
                                                                                                   select new TnsNameInfo(tnsNameNode.TnsName, rawDescription, tnsNameNode.ServiceName, databaseAddresses);

            var iFileEntries = listener.IfileEntries.Select(p => new TnsNamesFileInfo(p, TnsNamesSource.IfileEntry, tnsNamesFileInfo));

            errors = listener.ErrorNodes.ToArray();
            return(new TnsNamesFile(tnsNamesFileInfo, iFileEntries.ToArray(), tnsNames.ToArray()));
        }
        public static bool TryGetLineStatements(string text, int lineNumber, out IList <IParseTree> statementTrees, out IList <IToken> tokens)
        {
            Contract.Requires <ArgumentNullException>(text != null, "text");
            Contract.Requires <ArgumentOutOfRangeException>(lineNumber >= 0);

            try
            {
                AntlrInputStream  input       = new AntlrInputStream(text);
                JavaLexer         lexer       = new JavaLexer(new JavaUnicodeStreamV4(input));
                CommonTokenStream tokenStream = new CommonTokenStream(lexer);
                JavaParser        parser      = new JavaParser(tokenStream);

                parser.Interpreter.PredictionMode = PredictionMode.Sll;
                parser.BuildParseTree             = true;
                JavaParser.CompilationUnitContext result = parser.compilationUnit();

                statementTrees = null;
                tokens         = tokenStream.GetTokens();

                AssociatedTreeListener listener = new AssociatedTreeListener(lineNumber, tokens);
                ParseTreeWalker.Default.Walk(listener, result);
                statementTrees = listener.StatementTrees;

                return(true);
            }
            catch (Exception e)
            {
                if (ErrorHandler.IsCriticalException(e))
                {
                    throw;
                }

                statementTrees = null;
                tokens         = null;
                return(false);
            }
        }
Ejemplo n.º 25
0
        public async Task Init(INethermindApi nethermindApi)
        {
            _api            = nethermindApi;
            _txPool         = _api.TxPool;
            _blockProcessor = _api.MainBlockProcessor;

            _config = _api.Config <IDslConfig>();
            if (_config.Enabled)
            {
                _logger = _api.LogManager.GetClassLogger();
                if (_logger.IsInfo)
                {
                    _logger.Info("Initializing DSL plugin ...");
                }

                var dslScript = await LoadDSLScript();

                var inputStream = new AntlrInputStream(dslScript);
                var lexer       = new DslGrammarLexer(inputStream);
                var tokens      = new CommonTokenStream(lexer);
                var parser      = new DslGrammarParser(tokens);
                parser.BuildParseTree = true;
                IParseTree tree = parser.init();

                _listener                   = new ParseTreeListener();
                _listener.OnEnterInit       = OnInitEntry;
                _listener.OnEnterExpression = OnExpressionEntry;
                _listener.OnEnterCondition  = OnConditionEntry;
                _listener.OnExitInit        = BuildPipeline;
                ParseTreeWalker.Default.Walk(_listener, tree);

                if (_logger.IsInfo)
                {
                    _logger.Info("DSL plugin initialized.");
                }
            }
        }
Ejemplo n.º 26
0
        public GraphQLResultNode Compile(QueryRequest request)
        {
            // Setup our Antlr parser
            var stream = new AntlrInputStream(request.Query);
            var lexer  = new EntityGraphQLLexer(stream);
            var tokens = new CommonTokenStream(lexer);
            var parser = new EntityGraphQLParser(tokens);

            parser.BuildParseTree = true;
            parser.ErrorHandler   = new BailErrorStrategy();
            try
            {
                var tree    = parser.graphQL();
                var visitor = new GraphQLVisitor(_schemaProvider, _methodProvider, request.Variables);
                // visit each node. it will return a linq expression for each entity requested
                var node = visitor.Visit(tree);
                return((GraphQLResultNode)node);
            }
            catch (ParseCanceledException pce)
            {
                if (pce.InnerException != null)
                {
                    if (pce.InnerException is NoViableAltException nve)
                    {
                        throw new EntityGraphQLCompilerException($"Error: line {nve.OffendingToken.Line}:{nve.OffendingToken.Column} no viable alternative at input '{nve.OffendingToken.Text}'");
                    }
                    else if (pce.InnerException is InputMismatchException ime)
                    {
                        var expecting = string.Join(", ", ime.GetExpectedTokens());
                        throw new EntityGraphQLCompilerException($"Error: line {ime.OffendingToken.Line}:{ime.OffendingToken.Column} extraneous input '{ime.OffendingToken.Text}' expecting {expecting}");
                    }
                    System.Console.WriteLine(pce.InnerException.GetType());
                    throw new EntityGraphQLCompilerException(pce.InnerException.Message);
                }
                throw new EntityGraphQLCompilerException(pce.Message);
            }
        }
Ejemplo n.º 27
0
        public Func <TScope, TLocals, TReturn> Parse <TScope, TLocals, TReturn>(string input)
        {
            try
            {
                var scopeType        = typeof(TScope);
                var localsType       = typeof(TLocals);
                var antlrInputStream = new AntlrInputStream(input);
                var lex = new AngularLexer(antlrInputStream);
                lex.AddErrorListener(new StopOnErrorListener());
                var cts = new CommonTokenStream(lex);
                PrintTokens(cts);
                var parse = new AngularParser(cts)
                {
                    ErrorHandler = new BailErrorStrategy()
                };
                parse.AddErrorListener(new StopOnErrorListener());
                var root            = parse.program();
                var scopeParameter  = Expression.Parameter(scopeType, "s");
                var localsParameter = Expression.Parameter(localsType, "l");
                var helperParameter = Expression.Parameter(typeof(TypedJavascriptObjectHelper), "h");
                CommonAngularBuilderVisitor visitor = new CommonAngularBuilderVisitor(scopeParameter, localsParameter, helperParameter);
                var expression = visitor.Visit(root);
                expression = ExpressionHelpers.CastIfDifferentType(expression, typeof(TReturn));
                var functionExpression = Expression.Lambda <Func <TScope, TLocals, TypedJavascriptObjectHelper, TReturn> >(
                    expression, scopeParameter, localsParameter, helperParameter);
                var function = functionExpression.Compile();
                var helper   = new TypedJavascriptObjectHelper();
                return((s, l) => function(s, l, helper));
            }
            catch (ParseCanceledException ex) when(ex.InnerException is InputMismatchException)
            {
                var mismatch = (InputMismatchException)ex.InnerException;
                var token    = mismatch.OffendingToken;

                throw new AngularException($"Compile failed on {token.Line}:{token.Column}: {token.Text} ");
            }
        }
        /// <summary>
        /// Parses the given date.
        /// </summary>
        /// <param name="date">The date in string format including "hash tags" (e.g. #01-01-1900#)</param>
        /// <returns>The root of the parse tree.</returns>
        public VBADateParser.DateLiteralContext Parse(string date)
        {
            var stream = new AntlrInputStream(date);
            var lexer  = new VBADateLexer(stream);
            var tokens = new CommonTokenStream(lexer);
            var parser = new VBADateParser(tokens);

            parser.AddErrorListener(new ExceptionErrorListener(CodeKind.SnippetCode)); // notify?
            VBADateParser.CompilationUnitContext tree;
            try
            {
                parser.Interpreter.PredictionMode = PredictionMode.Sll;
                tree = parser.compilationUnit();
            }
            catch (Exception ex)
            {
                Logger.Warn(ex, "SLL mode failed for {0}. Retrying using LL.", date);
                tokens.Reset();
                parser.Reset();
                parser.Interpreter.PredictionMode = PredictionMode.Ll;
                tree = parser.compilationUnit();
            }
            return(tree.dateLiteral());
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            Program.Initiation();

            while (true)
            {
                Console.Write(">> ");

                StreamReader streamReader = new StreamReader(Console.OpenStandardInput());

                try
                {
                    AntlrInputStream inputStream = new AntlrInputStream(streamReader.ReadLine());
                    if (inputStream.ToString().Contains("\u001a") || inputStream.ToString().Contains("\u0004"))
                    {
                        Console.WriteLine("EOF");
                        break;
                    }

                    FA_LanguageLexer  fA_LanguageLexer  = new FA_LanguageLexer(inputStream);
                    CommonTokenStream commonTokenStream = new CommonTokenStream(fA_LanguageLexer);
                    FA_LanguageParser fA_LanguageParser = new FA_LanguageParser(commonTokenStream);
                    IParseTree        parseTree         = fA_LanguageParser.conversation();
                    FA_Visitor        fA_Visitor        = new FA_Visitor(Program.functions);

                    // Print tree and output result
                    Console.WriteLine(parseTree.ToStringTree(fA_LanguageParser));
                    Console.WriteLine(fA_Visitor.Visit(parseTree).ToString());
                }
                catch (System.NullReferenceException e)
                {
                    Console.WriteLine("error: " + e.Message);
                    continue;
                }
            }
        }
Ejemplo n.º 30
0
        public Stylesheet Parse(string fileName, Stream input, bool isReference)
        {
            var charStream = new AntlrInputStream(input);
            var lexer      = new LessLexer(charStream);

            var tokenStream = new CommonTokenStream(lexer);

            var parser = new LessParser(tokenStream)
            {
                ErrorHandler = new BailErrorStrategy()
            };

            try {
                var lessStylesheet = parser.stylesheet();

                return((Stylesheet)lessStylesheet.Accept(new SyntaxTreeToParseTreeVisitor(tokenStream, isReference)));
            } catch (ParseCanceledException ex) when(ex.InnerException is InputMismatchException ime)
            {
                throw ParserException.FromToken(fileName, ime.OffendingToken);
            } catch (ParseCanceledException ex) when(ex.InnerException is NoViableAltException nvae)
            {
                throw ParserException.FromToken(fileName, nvae.OffendingToken);
            }
        }