SLR1 分析:文法分析表构建错误原因及修正方法

本文将分析 SLR1 分析过程中分析表构建错误的原因,并提供详细的修正方法。

错误分析:

在 SLRAnaly() 函数中,针对含有归约项目的集合,根据其 follow 集合添加归约状态时,只添加了终结符的归约状态,而没有添加非终结符的归约状态。导致在分析表中缺少了归约状态。

改正部分:

需要在添加终结符的归约状态之后,再针对该非终结符的所有 follow 集合添加归约状态。修改后的代码如下:

for (int i = 0; i < Gy_itemset.Count; i++)
{
    SLRNode item = SLRobjNum[proitemset[Gy_itemset[i]].Container[0]];
    char left = item.Left[0];
    List<char> follow = GetFollow(left);
    foreach (char c in follow)
    {
        int CID = FindID(Echar, c);
        SLRAna[Gy_itemset[i]][CID] = new Table('r', Find_pro(item));
        if (c == '#' )
        {
            foreach (char e in Echar)
            {
                int EID = FindID(Echar, e);
                SLRAna[Gy_itemset[i]][EID] = new Table('r', Find_pro(item));
            }
            foreach (char n in Nchar)
            {
                int NID = FindID(Nchar, n);
                SLRAna[Gy_itemset[i]][NID + Echar.Count] = new Table('r', Find_pro(item));
            }
        }
    }
}

需要调整的调用的代码:

在 GET_ANA() 函数中,调用 SLRAnaly() 函数之前,需要先将非终结符集合和终结符集合分别求出来。调整后的代码如下:

public Table[][] GET_ANA()
{
    GetChar();
    SLRAnaly();
    //...
}

在 GetChar() 函数中,需要将非终结符集合和终结符集合分别求出来。修改后的代码如下:

public void GetChar()
{
    foreach (SLRNode node in SLRproNum)
    {
        if (!Nchar.Contains(node.Left[0]))
            Nchar.Add(node.Left[0]);
        for (int i = 0; i < node.Right.Length; i++)
        {
            if (!isFinalsymbol(node.Right[i]) && !Nchar.Contains(node.Right[i]))
                Nchar.Add(node.Right[i]);
            else if (isFinalsymbol(node.Right[i]) && !Echar.Contains(node.Right[i]))
                Echar.Add(node.Right[i]);
        }
    }
    Echar.Add('#');
}

通过这些代码的修改,可以修正 SLR1 分析表构建过程中的错误,并得到正确的分析表,从而实现对文法的准确分析。

SLR1 分析:文法分析表构建错误原因及修正方法

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

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