Ejemplo n.º 1
0
        public override ParserFunc <TFuture> BuildParser <TFuture>(Future <T, TFuture> future)
        {
            return((scanner, context) =>
            {
                var s1 = scanner;
                var s2 = scanner.Fork();

                return context.ChooseBest(Parser1.BuildParser(future)(s1, context), Parser2.BuildParser(future)(s2, context));
            });
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            //Load specs
            (FileInfo, FileInfo)? s = SpecificationsManager.GetSpecification("test-002");
            FileStream ts = s.Value.Item1.OpenRead();
            FileStream gs = s.Value.Item2.OpenRead();

            //Parse tokens
            TokenSchemeCollection t = new TokenSchemeCollection();

            t.ReadFromStream(ts);

            //Parse grammar
            GrammarSchemeCollection g = new GrammarSchemeCollection();

            g.ReadFromStream(gs);

            //Load test
            FileInfo   test       = TestsManager.GetTest("test_ast");
            FileStream testStream = test.OpenRead();

            //Parse test File
            Parser1 p1 = new Parser1()
            {
                BaseTokens = t, BaseGrammar = g
            };
            TokenCollection    tokens  = p1.ParseTokensFromStream(testStream);
            Stack <int>        history = p1.ParseHistory(tokens);
            AbstractSyntaxTree ast     = new AbstractSyntaxTree();

            ast.CreateTree(g, tokens, ReverseHistory(history));

            Console.WriteLine(ast);
            ast.BreakDownLists();
            Console.WriteLine(ast);

            //Parse to abstract
            CFLRuntime     rt      = new CFLRuntime();
            ProgramBuilder builder = new ProgramBuilder(rt);
            Container      cnt     = builder.BuildFromTree(ast);

            //Console.WriteLine("Calculate sum of n squares with CFL [Enter integer]:");
            //object n = Console.ReadLine().EvaluateMathExpression();
            //Console.WriteLine(rt.Execute("sum_n_squares", ("n", n)));

            Console.WriteLine("Count number of prime numbers below n with CFL [Enter integer n]:");
            object n = Console.ReadLine().EvaluateMathExpression();

            Console.WriteLine(rt.Execute("primes_below_n", ("n", n)));
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            //string filename = Console.ReadLine();
            System.IO.StreamReader stream = new System.IO.StreamReader("a.txt");
            string line;

            while (!stream.EndOfStream)
            {
                line = stream.ReadToEnd();
                Lexer1  lexer  = new Lexer1(new AntlrInputStream(line));
                Parser1 parser = new Parser1(new CommonTokenStream(lexer));
                parser.main_rule();
            }
            Console.WriteLine("\npress any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 4
0
    public static IParser Create(string type)
    {
        IParser parser;

        switch (type)
        {
        case "1":
            parser = new Parser1();
            break;

        case "2":
            parser = new Parser2();
            break;

        default:
            throw new ArgumentOutOfRangeException("type");
        }

        return(parser);
    }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            //Load specs
            (FileInfo, FileInfo)? s = SpecificationsManager.GetSpecification("test-002");
            FileStream ts = s.Value.Item1.OpenRead();
            FileStream gs = s.Value.Item2.OpenRead();

            //Parse tokens
            TokenSchemeCollection t = new TokenSchemeCollection();

            t.ReadFromStream(ts);

            //Parse grammar
            GrammarSchemeCollection g = new GrammarSchemeCollection();

            g.ReadFromStream(gs);

            //Load test
            FileInfo   test       = TestsManager.GetTest("test_ast");
            FileStream testStream = test.OpenRead();

            //Parse test File
            Parser1 p1 = new Parser1()
            {
                BaseTokens = t, BaseGrammar = g
            };
            TokenCollection    tokens  = p1.ParseTokensFromStream(testStream);
            Stack <int>        history = p1.ParseHistory(tokens);
            AbstractSyntaxTree ast     = new AbstractSyntaxTree();

            ast.CreateTree(g, tokens, ReverseHistory(history));

            Console.WriteLine(ast);
            ast.BreakDownLists();
            Console.WriteLine(ast);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Attempts to match an input string starting at the given index.
        /// </summary>
        /// <param name="input">String to match.</param>
        /// <param name="index">Index to begin matching at.</param>
        /// <returns>An <see cref="IParseResult{T}"/> containing the parsed value.</returns>
        public override IParseResult <SequenceResult <T1, T2> > Parse(string input, int index)
        {
            var i       = index;
            var result1 = Parser1.Parse(input, i);

            if (!result1.Success)
            {
                var failure = (ParseFail <T1>)result1;
                return(new ParseFail <SequenceResult <T1, T2> >(failure.FailureType, failure.Index, failure.Message));
            }

            i += result1.Length;
            var result2 = Parser2.Parse(input, i);

            if (!result2.Success)
            {
                var failure = (ParseFail <T2>)result2;
                return(new ParseFail <SequenceResult <T1, T2> >(failure.FailureType, failure.Index, failure.Message));
            }

            var value = new SequenceResult <T1, T2>(result1.Value, result2.Value);

            return(new ParseSuccess <SequenceResult <T1, T2> >(string.Concat(result1.Text, result2.Text), value, index));
        }
Ejemplo n.º 7
0
                public static long Evaluate(string formula)
                {
                    var p = new Parser1(formula);

                    return(p._ret);
                }
Ejemplo n.º 8
0
        void ParserToken(Parser1 parser)
        {
            string x = cur_token.text;

            switch (parser.state)
            {
            case ParserState.INITIALIZE:
            case ParserState.WAITING_FOR_DECL_OR_RULE:
                if (parser.state == ParserState.INITIALIZE)
                {
                    parser.prevrule    = null;
                    parser.preccounter = 0;
                    parser.firstrule   = parser.lastrule = null;
                    parser.gp.nrule    = 0;
                }
                if (x[0] == '%')
                {    //定义
                    parser.state = ParserState.WAITING_FOR_DECL_KEYWORD;
                }
                else if (char.IsLower(x[0]))
                {    //非终结符
                    parser.left     = Symbol_new(x);
                    parser.nrhs     = 0;
                    parser.lhsalias = null;
                    parser.state    = ParserState.WAITING_FOR_ARROW;
                }
                else if (x[0] == '{')
                {    //c#代码块
                    if (parser.prevrule == null)
                    {
                        ErrorMsg("There is no prior rule upon which to attach the code fragment which begins on this line.");
                        parser.errorcnt++;
                    }
                    else if (parser.prevrule.code != null)
                    {
                        ErrorMsg("Code fragment beginning on this line is not the first to follow the previous rule.");
                        parser.errorcnt++;
                    }
                    else
                    {
                        parser.prevrule.line   = parser.tokenlineno;
                        parser.prevrule.code   = x;
                        parser.prevrule.noCode = 0;
                    }
                }
                else if (x[0] == '[')
                {    //伪终结符开始
                    parser.state = ParserState.PRECEDENCE_MARK_1;
                }
                else
                {
                    ErrorMsg("Token \"{0}\" should be either \"%%\" or a nonterminal name.", x);
                    parser.errorcnt++;
                }
                break;


            case ParserState.PRECEDENCE_MARK_1: //伪终结符开始
                if (!char.IsUpper(x[0]))
                {                               //伪终结符首字母必须大写
                    ErrorMsg("The precedence symbol must be a terminal.");
                    parser.errorcnt++;
                }
                else if (parser.prevrule == null)
                {
                    ErrorMsg("There is no prior rule to assign precedence \"[%s]\".", x);
                    parser.errorcnt++;
                }
                else if (parser.prevrule.precsym != null)
                {
                    ErrorMsg("Precedence mark on this line is not the first to follow the previous rule.");
                    parser.errorcnt++;
                }
                else
                {
                    parser.prevrule.precsym = Symbol_new(x);
                }
                parser.state = ParserState.PRECEDENCE_MARK_2;
                break;

            case ParserState.PRECEDENCE_MARK_2:    //伪终结符结束
                if (x[0] != ']')
                {
                    ErrorMsg("Missing \"]\" on precedence mark.");
                    parser.errorcnt++;
                }
                parser.state = ParserState.WAITING_FOR_DECL_OR_RULE;
                break;

            case ParserState.WAITING_FOR_ARROW:    //产生式定义
                if (x[0] == ':' && x[1] == ':' && x[2] == '=')
                {
                    parser.state = ParserState.IN_RHS;
                }
                else if (x[0] == '(')
                {
                    parser.state = ParserState.LHS_ALIAS_1;
                }
                else
                {
                    ErrorMsg("Expected to see a \":\" following the LHS symbol \"{0}\".", parser.left.name);
                    parser.errorcnt++;
                    parser.state = ParserState.RESYNC_AFTER_RULE_ERROR;
                }
                break;

            case ParserState.LHS_ALIAS_1: //左非终结符别名开始 Lhs (
                if (char.IsLetter(x[0]))
                {                         // Lhs (xxxxx
                    parser.lhsalias = x;
                    parser.state    = ParserState.LHS_ALIAS_2;
                }
                else
                {
                    ErrorMsg("\"{0}\" is not a valid alias for the LHS \"{1}\"\n", x, parser.left.name);
                    parser.errorcnt++;
                    parser.state = ParserState.RESYNC_AFTER_RULE_ERROR;
                }
                break;

            case ParserState.LHS_ALIAS_2:
                if (x[0] == ')')
                {    //左非终结符别名结束 Lhs (xxxxx)
                    parser.state = ParserState.LHS_ALIAS_3;
                }
                else
                {
                    ErrorMsg("Missing \")\" following LHS alias name \"{0}\".", parser.lhsalias);
                    parser.errorcnt++;
                    parser.state = ParserState.RESYNC_AFTER_RULE_ERROR;
                }
                break;

            case ParserState.LHS_ALIAS_3:
                if (x[0] == ':' && x[1] == ':' && x[2] == '=')
                {
                    parser.state = ParserState.IN_RHS;
                }
                else
                {
                    ErrorMsg("Missing \"->\" following: \"{0}({1})\".", parser.left.name, parser.lhsalias);
                    parser.errorcnt++;
                    parser.state = ParserState.RESYNC_AFTER_RULE_ERROR;
                }
                break;

            //以上已将产生式左边处理完毕
            //以下开始处理产生式右边内容
            case ParserState.IN_RHS:
                if (x[0] == '.')
                {    //一条产生式处理完毕
                }
                break;
            }
        }
Ejemplo n.º 9
0
        public void Parse()
        {
            ErrorMsg("arg0");
            ErrorMsg("arg1 ={0}", 1);
            ErrorMsg("arg1 ={0} arg2 ={1}", 1, "two");
            Parser1 parser = new Parser1();

            parser.state = ParserState.INITIALIZE;

            skip_white_space();
            for (char cur_ch = read_char(); cur_ch != EOF; skip_white_space(), cur_ch = read_char())
            {
                cur_token = new Token(row, col, offset);
                char next_ch = next_char1();
                if (cur_ch == '/' && next_ch == '/')
                {
                    skip_chars(2);
                    skip_line();
                    end_token(TokenType.SingleLineComment);
                    continue;
                }
                else if (cur_ch == '/' && next_ch == '*')
                {
                    skip_chars(2);
                    skip_until("*/");
                    end_token(TokenType.MultiLineComment);
                    continue;
                }

                if (cur_ch == '"')
                {
                    skip_until('"');
                }
                else if (cur_ch == '{')
                {//潜入c#代码块
                    int level = 1;
                    for (char ch = read_char(); ch != EOF; ch = read_char())
                    {
                        next_ch = next_char1();
                        if (ch == '{')
                        {
                            level++;
                        }
                        else if (ch == '}')
                        {
                            if (--level == 0)
                            {
                                break;              // return end_token(TokenType.CodeBlock);
                            }
                        }
                        else if (ch == '/' && next_ch == '/')
                        {
                            skip_until('\n');
                        }
                        else if (ch == '/' && next_ch == '*')
                        {
                            skip_until("*/");
                        }
                        else if (ch == '\'' || ch == '"')
                        {
                            skip_string(ch, true);
                        }
                    }
                    end_token(TokenType.CodeBlock);
                }
                else if (char.IsLetterOrDigit(cur_ch) || cur_ch == '_')
                {
                    id_token();
                }
                else if (cur_ch == ':' && next_ch == ':' && next_char2() == '=')
                {
                    skip_chars(3);
                    end_token(TokenType.ARROW);
                }
                else if ((cur_ch == '/' || cur_ch == '|') && char.IsLetterOrDigit(next_ch))
                {
                }
                else
                {
                    end_token((TokenType)cur_ch);
                }
                ParserToken(parser);
            }
            return;
        }