示例#1
0
        public ProxyProcessOutput ProcessInput(string inputText, AppArgs args)
        {
            var input     = new AntlrInputStream(inputText);
            var allTypes  = _assemblies.SelectMany(x => x.GetTypes()).ToArray();
            var lexerType = allTypes
                            .FirstOrDefault(x => x.BaseType == typeof(Lexer) && x.Name.Equals(args.GrammarName + "lexer", StringComparison.CurrentCultureIgnoreCase));

            if (lexerType == null)
            {
                throw new ApplicationException(string.Format("Lexer {0} not found.", args.GrammarName));
            }
            var lexer             = (Lexer)Activator.CreateInstance(lexerType, new object[] { input });
            var commonTokenStream = new CommonTokenStream(lexer);

            commonTokenStream.Fill();

            if (args.ShowTokens)
            {
                foreach (var token in commonTokenStream.GetTokens())
                {
                    Console.WriteLine(((CommonToken)token).ToString());
                }
            }

            if (args.StartRuleName == LEXER_START_RULE_NAME)
            {
                return(null);
            }


            var parserType = allTypes
                             .FirstOrDefault(x => x.BaseType == typeof(Parser) && x.Name.Equals(args.GrammarName + "parser", StringComparison.CurrentCultureIgnoreCase));

            if (parserType == null)
            {
                throw new ApplicationException(string.Format("Parser {0} not found.", args.GrammarName));
            }
            var parser = (Parser)Activator.CreateInstance(parserType, new object[] { commonTokenStream });


            if (args.Diagnoctics)
            {
                parser.AddErrorListener(new DiagnosticErrorListener());
                parser.Interpreter.PredictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION;
            }

            if (args.ShowTree || args.ShowGui)
            {
                parser.BuildParseTree = true;
            }

            if (args.SLL)
            { // overrides diagnostics
                parser.Interpreter.PredictionMode = (PredictionMode.SLL);
            }

            parser.Trace = args.Trace;

            var errorListener = new MyErrorListener();

            parser.AddErrorListener(errorListener);

            MethodInfo rootMethod = parserType.GetMethod(args.StartRuleName);

            if (rootMethod == null)
            {
                throw new ApplicationException($"Start rule \"{args.StartRuleName}\" does not exist");
            }
            IParseTree rootContext;

            rootContext = (IParseTree)rootMethod.Invoke(parser, new object[] { });

            if (args.ShowTree)
            {
                Console.WriteLine(rootContext.ToStringTree(parser));
            }

            var             visitor = new InfoCollectorVisitor(errorListener.ContextTokenMapping);
            ParseTreeWalker walker  = new ParseTreeWalker();

            walker.Walk(visitor, rootContext);

            var output = new ProxyProcessOutput();

            //last non error context
            output.LastNonErrorContextToken = $"{visitor.LastNonErrorContext.Start.StartIndex}:{visitor.LastNonErrorContext.Stop?.StopIndex} {visitor.LastNonErrorContext.GetText()}";

            RuleContext ctx = visitor.LastNonErrorContext;

            do
            {
                output.LastNonErrorContextNameStack.Insert(output.LastNonErrorContextNameStack.Count, parser.RuleNames[ctx.RuleIndex]);
                ctx = ctx.Parent;
            } while (ctx != null);


            //last context
            output.LastContextToken = $"{visitor.LastContext.Start.StartIndex}:{visitor.LastContext.Stop?.StopIndex} {visitor.LastContext.GetText()}";

            ctx = visitor.LastContext;
            do
            {
                output.LastContextNameStack.Insert(output.LastContextNameStack.Count, parser.RuleNames[ctx.RuleIndex]);
                ctx = ctx.Parent;
            } while (ctx != null);



            //Last error context
            if (visitor.LastErrorContext != null)
            {
                output.LastErrorContextToken =
                    $"{visitor.LastErrorContext.Start.StartIndex}:{visitor.LastErrorContext.Stop?.StopIndex} {GetSourceText(visitor.LastErrorContext)} ({parser.RuleNames[visitor.LastErrorContext.RuleIndex]})";
            }

            output.Model = new DisplayNodeBuilder(errorListener.TokenExceptionMapping, errorListener.ContextTokenMapping, parser.RuleNames)
                           .GetDisplayNodeFromParseTree(rootContext, args.RuleIndex);
            return(output);
        }
示例#2
0
        public static AppArgs ReadOptionsFromArgs(string[] args)
        {
            var appArg = new AppArgs();

            if (args.Length < 3)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("AntlrTestRig.exe GrammarName startRuleName\n" +
                              "  [-tokens] [-tree] [-gui] [-ps file.ps] [-encoding encodingname]\n" +
                              "  [-trace] [-diagnostics] [-SLL]\n" +
                              "  [-folder]\n" +
                              "  [input-filename(s)]");
                sb.AppendLine("Use startRuleName='tokens' if GrammarName is a lexer grammar.");
                sb.AppendLine("Omitting input-filename makes rig read from stdin, end with Ctrl+Z and Enter");
                Console.WriteLine(sb.ToString());
                return(null);
            }

            int i = 1; //starts with 1, the 0 is the app file itself

            appArg.GrammarName = args[i];
            i++;
            appArg.StartRuleName = args[i];
            i++;
            while (i < args.Length)
            {
                String arg = args[i];
                i++;
                if (arg[0] != '-')
                { // input file name
                    appArg.InputFile = arg;
                    continue;
                }
                if (arg.Equals("-tree"))
                {
                    appArg.ShowTree = true;
                }
                if (arg.Equals("-gui"))
                {
                    appArg.ShowGui = true;
                }
                if (arg.Equals("-tokens"))
                {
                    appArg.ShowTokens = true;
                }
                else if (arg.Equals("-trace"))
                {
                    appArg.Trace = true;
                }
                else if (arg.Equals("-SLL"))
                {
                    appArg.SLL = true;
                }
                else if (arg.Equals("-diagnostics"))
                {
                    appArg.Diagnoctics = true;
                }
                else if (arg.Equals("-encoding"))
                {
                    if (i >= args.Length)
                    {
                        Console.WriteLine("missing encoding on -encoding");
                        return(null);
                    }
                    appArg.Encoding = args[i];
                    i++;
                }

                else if (arg.Equals("-folder"))
                {
                    if (i >= args.Length)
                    {
                        Console.WriteLine("missing encoding on -folder");
                        return(null);
                    }
                    appArg.Folder = args[i];
                    i++;
                }
                else if (arg.Equals("-ruleindex"))
                {
                    appArg.RuleIndex = true;
                }
            }

            return(appArg);
        }