Beispiel #1
0
 public Lexer Build(string name)
 {
     CalcEmptyalbe();
     CalcFirstSets();
     BuildItemList(name);
     PureProduction[] pps = new PureProduction[ProdList.Count];
     for (int i = 0; i < ProdList.Count; i++)
     {
         Production p = ProdList[i];
         pps[i] = new PureProduction(p.Name, p.Elems.Length, p.Action);
     }
     return(new Lexer(Table.ToArray(), pps));
 }
Beispiel #2
0
        public bool TryParse(TokenStream ts, out IASTNode result)
        {
            Reset();
            //PrintStatus();
            while (true)
            {
                LexAction action = GetAction(ts.Peek());
                //Console.WriteLine($"Token: {ts.Peek().Type}, Action: {action}");
                switch (action.Type)
                {
                case Accept: result = Symbols.Pop(); return(true);

                case Error: result = null; return(false);

                case Reduce: {
                    PureProduction   production = Productions[action.Target];
                    Stack <IASTNode> tmp        = new Stack <IASTNode>();
                    for (int i = 0; i < production.ElemCount; i++)
                    {
                        Status.Pop();
                        tmp.Push(Symbols.Pop());
                    }
                    IASTNode node = production.Action != null?
                                    production.Action(tmp.ToArray()) :
                                        (tmp.Count == 1 ? tmp.Pop() : new ASTList(tmp.ToArray()));

                    Symbols.Push(node);
                    if (Table[Status.Peek()].TryGetValue(production.Name, out LexAction a))
                    {
                        Status.Push(a.Target);
                    }
                    else
                    {
                        result = null;
                        return(false);
                    }
                    break;
                }

                case Shift: {
                    Token token = ts.Read();
                    Symbols.Push(new ASTLeaf(token));
                    Status.Push(action.Target);
                    break;
                }
                }
                //PrintStatus();
            }
        }