C#实现LL(1)文法判断及FIRST、FOLLOW集计算与展示
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace LL1GrammarAnalyzer
{
public partial class Form1 : Form
{
// ... 其他代码 ...
private void button4_Click(object sender, EventArgs e)
{
string text = richTextBox1.Text;
production = new Dictionary<string, List<string>>();
string[] pro = text.Split('
');
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.Columns.Add('', 30);
foreach (var item in terminals)
{
listView1.Columns.Add(item, 30);
}
foreach (var item in nonterminals)
{
ListViewItem lvi = new ListViewItem(item);
lvi.SubItems.Add('');
foreach (var t in terminals)
{
if (firsts[item].Contains(t))
{
lvi.SubItems.Add('1');
}
else
{
lvi.SubItems.Add('0');
}
}
listView1.Items.Add(lvi);
}
}
private void button2_Click(object sender, EventArgs e)
{
listView2.Clear();
listView2.Columns.Add('', 30);
foreach (var item in terminals)
{
listView2.Columns.Add(item, 30);
}
foreach (var item in nonterminals)
{
ListViewItem lvi = new ListViewItem(item);
lvi.SubItems.Add('');
foreach (var t in terminals)
{
if (follows[item].Contains(t))
{
lvi.SubItems.Add('1');
}
else
{
lvi.SubItems.Add('0');
}
}
listView2.Items.Add(lvi);
}
}
// ... 其他代码 ...
}
}
原文地址: https://www.cveoy.top/t/topic/fXCW 著作权归作者所有。请勿转载和采集!