This function builds the parsing table for a given LR(0) automaton.

First, it initializes an empty dictionary called 'table' to store the table entries.

Then, for each state in the automaton, it examines each terminal symbol in the grammar. If there is a transition from the current state on that symbol, it adds the action to shift to the state specified by the transition to the corresponding entry in the table. If there is no transition on that symbol, it adds an empty string to the table entry.

Next, for each nonterminal symbol in the grammar, it examines whether there is a transition from the current state on that symbol. If there is, it adds the state to transition to the corresponding entry in the table. If there is no transition on that symbol, it adds an empty string to the table entry.

Finally, it adds the completed table entry for the current state to the 'table' dictionary using the state index as the key.

The resulting table can be used to parse input strings according to the LR(0) grammar.

private void buildtable()
{
    int flag = 0;
    table = new Dictionary<int, List<string>>();
    for(int i=0;i<states.Count; i++)
    {
        //对每个状态经过终结符的情况进行判断
        List<string> strings = new List<string>();
        foreach(var symbol in terminals)
        {
            flag = 0;
            if (transitions.ContainsKey(i))
            {
                foreach (var item in transitions[i])
                {
                    if (item[0].ToString().Equals(symbol))
                    {
                        strings.Add('S'+item.Substring(1));
                        flag = 1;
                        break;
                    }
                }
                if (flag==0)strings.Add("");
            }
            else
            {
                if (states[i].items.First().LHS.Equals(production.Keys.First() + '))
                {
                    if(symbol.Equals("#")) strings.Add("acc");
                    else strings.Add("");
                }
                else
                {
                    int index = getproconut(states[i]);
                    strings.Add("r" + index);
                }
            }
        }
        //对每个状态经过非终结符的情况进行判断
        foreach(var t in nonterminal)
        {
            flag = 0;
            if (transitions.ContainsKey(i))
            {
                foreach (var item in transitions[i])
                {
                    if (item[0].ToString().Equals(t))
                    {
                        strings.Add(item.Substring(1));
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0) strings.Add("");
            }
            else strings.Add("");
        }
        table.Add(i,strings);
    }
}
LR(0) Parsing Table Construction in C#

原文地址: https://www.cveoy.top/t/topic/oBKT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录