private void button4_Click(object sender, EventArgs e)
{
    string text = richTextBox1.Text;
    production = new Dictionary<string, List<string>>();
    string[] pro = text.Split('\n');
    foreach (string s in pro)
    {
        if (s == '') continue;

        Regex.Replace(s, ' ', '');
        string[] ga = Regex.Split(s, '->');
        if (ga.Length != 2) return;
        if (ga[0].Length == 0 || ga[1].Length == 0)
            return;
        if (ga[0].Length != 1 || !char.IsUpper(ga[0][0])) return;

        string[] ga2 = Regex.Split(ga[1], '\|');
        if (!production.ContainsKey(ga[0]))
            production.Add(ga[0], new List<string>());
        foreach (string s1 in ga2)
            production[ga[0]].Add(s1);
    }

    firsts = new Dictionary<string, List<string>>();
    foreach (var item in production.Keys)
        GetFirst(item, production, firsts);

    follows = new Dictionary<string, List<string>>();
    foreach (var item in production.Keys)
        GetFollow(item, production, firsts, follows);

    if (JudgeLL1(production, firsts, follows))
    {
        MessageBox.Show('该文法是LL(1)文法\n');
        
    }
    else
    {
        MessageBox.Show('该文法不是LL(1)文法,存在左递归或者存在FIRST集合有交集的情况!\n');
    }
    button1.Enabled = true;
    button2.Enabled = true;
    button3.Enabled = true;
}

// ... 其他函数 ...

private void button1_Click(object sender, EventArgs e)
{
    listView1.Clear();
    listView1.View = View.Details;
    listView1.Columns.Add('', 30);
    foreach (var item in terminals)
    {
        listView1.Columns.Add(item, 50);
    }
    foreach (var item in nonterminals)
    {
        ListViewItem lvi = new ListViewItem(item);
        List<string> first = firsts[item];
        for (int i = 0; i < terminals.Count; i++)
        {
            if (first.Contains(terminals[i]))
            {
                lvi.SubItems.Add('1');
            }
            else
            {
                lvi.SubItems.Add('0');
            }
        }
        listView1.Items.Add(lvi);
    }
}

private void button2_Click(object sender, EventArgs e)
{
    listView2.Clear();
    listView2.View = View.Details;
    listView2.Columns.Add('', 30);
    foreach (var item in terminals)
    {
        listView2.Columns.Add(item, 50);
    }
    foreach (var item in nonterminals)
    {
        ListViewItem lvi = new ListViewItem(item);
        List<string> follow = follows[item];
        for (int i = 0; i < terminals.Count; i++)
        {
            if (follow.Contains(terminals[i]))
            {
                lvi.SubItems.Add('1');
            }
            else
            {
                lvi.SubItems.Add('0');
            }
        }
        listView2.Items.Add(lvi);
    }
}
C#实现LL(1)文法分析器:计算First集和Follow集并判断LL(1)文法

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

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