private void button7_Click(object sender, EventArgs e)
{
    // 获取输入的字符串和文法
    string text = textBox1.Text;
    string grammar = textBox2.Text;

    // 解析文法,获取产生式、非终结符、终结符等信息
    Grammar g = new Grammar(grammar);
    g.Parse();

    // 计算 FIRST 集和 FOLLOW 集
    Dictionary<string, List<string>> firsts = new Dictionary<string, List<string>>();
    Dictionary<string, List<string>> follows = new Dictionary<string, List<string>>();
    GetFirst(g.StartSymbol, g.Productions, firsts);
    GetFollow(g.StartSymbol, g.Productions, firsts, follows);

    // 判断是否为 LL(1) 文法
    bool isLL1 = JudgeLL1(g.Productions, firsts, follows);
    if (!isLL1)
    {
        MessageBox.Show("该文法不是 LL(1) 文法!");
        return;
    }

    // 计算预测分析表
    Dictionary<string, Dictionary<string, string>> table = new Dictionary<string, Dictionary<string, string>>();
    foreach (var nonterm in g.NonTerminals)
    {
        table.Add(nonterm, new Dictionary<string, string>());
        foreach (var term in g.Terminals)
        {
            table[nonterm].Add(term, "");
        }
    }
    GetSelect(g.Productions, firsts, follows);

    // 进行语法分析
    analyse_sentence analyse = new analyse_sentence(text, new Select(g.Productions, table));
    listView4.Items.Clear();
    for (int i = 0; i < analyse.result_parse.Count; i++)
    {
        ListViewItem item = new ListViewItem(new string[] { analyse.result_analys[i], analyse.result_input[i], analyse.result_parse[i] });
        listView4.Items.Add(item);
    }
}

private void button8_Click(object sender, EventArgs e)
{
    // 显示下一步分析信息
    if (listView4.Items.Count > 0 && listView4.SelectedIndices.Count == 1 && listView4.SelectedIndices[0] < listView4.Items.Count - 1)
    {
        listView4.Items[listView4.SelectedIndices[0] + 1].Selected = true;
    }
}

private void button9_Click(object sender, EventArgs e)
{
    // 一键显示分析信息
    for (int i = 0; i < listView4.Items.Count; i++)
    {
        listView4.Items[i].Selected = true;
    }
}

代码分析

  1. button7_Click

    • 获取输入的字符串 text 和文法 grammar
    • 解析文法,获取产生式、非终结符、终结符等信息。
    • 计算 FIRST 集和 FOLLOW 集。
    • 判断是否为 LL(1) 文法。
    • 计算预测分析表。
    • 进行语法分析,并将结果显示在 listView4 中。
  2. button8_Click

    • 显示下一步分析信息,即选择下一行分析信息。
  3. button9_Click

    • 一键显示分析信息,即选择所有分析信息。

功能说明

  • 此代码实现了 LL(1) 语法分析器的基本功能。
  • 用户可通过界面输入文法规则和待分析字符串,并观察分析过程。
  • 代码提供了单步展示功能,方便用户理解分析过程。
  • 代码中使用了 analyse_sentence 类来进行语法分析,并保存了分析过程中各个步骤的信息。

使用说明

  1. 在代码中添加一个 textBox1 用于输入待分析字符串,textBox2 用于输入文法规则。
  2. 在代码中添加一个 listView4 用于显示分析结果。
  3. 在界面上添加三个按钮,分别对应 button7_Clickbutton8_Clickbutton9_Click 函数。
  4. 运行代码,输入待分析字符串和文法规则,点击按钮进行分析。

注意

  • 此代码只实现了 LL(1) 语法分析器的基本功能,对于更复杂的语法分析需求,可能需要进行扩展。
  • 代码中使用了 MessageBox.Show() 函数来提示用户文法是否为 LL(1) 文法,实际应用中可以使用更友好的提示方式。
  • 代码中的 Grammar 类需要根据实际需求进行定义,以解析文法规则。
  • 代码中的 Select 类需要根据实际需求进行定义,以存储预测分析表。
  • 代码中的 analyse_sentence 类需要根据实际需求进行定义,以进行语法分析。

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

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