/* 构造分析表的过程是遍历每个状态,对于每个状态中的每个终结符和非终结符,分别判断是否存在移进项或者归约项,如果存在则在对应的分析表项中填入相应的移进或者归约动作。最终得到的分析表是一个二维字典,其中第一维表示状态编号,第二维表示终结符和非终结符。 已知上述构造SLR分析表原理,请在下列代码环境中实现SLRAnaly函数及相关调用函数实现构建SLR分析表功能。 */ class SLR { //产生式结点类 public class SLRNode { public string Left; public string Right; public SLRNode(string Left, string Right) { this.Left = Left; this.Right = Right; } } //项目集类 public class SLRitemsets { public List Container = new List(100); //记录项目在项目集合中的序号 }

//DFA结点
public struct DFA
{
    public int from;
    public char symbol;
    public int to;
    public DFA(int from, char symbol, int to)
    {
        this.from = from;
        this.symbol = symbol;
        this.to = to;
    }
}

//分析表 结点
public class Table
{
    public bool error;//是否为ERROR
    public char type;//结点类型
    public int id;//数值
    public Table()
    {
        this.error = true;
    }
    public Table(char type, int id)
    {
        this.type = type;
        this.id = id;
        this.error = false;
    }
}

public DFA[] dfa = new DFA[100];
public int Pindex = 0; //dfa数组指针
public Table[][] SLRAna;//分析表
public List<SLRNode> SLRproNum = new List<SLRNode>(50);//产生式 列表
public List<SLRNode> SLRobjNum = new List<SLRNode>(50);//项目 列表
public List<SLRitemsets> proitemset = new List<SLRitemsets>(100);//项目集合
public List<int> Gy_obj = new List<int>(50);//归约项目序号集合
public List<int> Gy_itemset = new List<int>(50);//含有归约项目的集合的序号 的集合
public List<char> Nchar = new List<char>(50);//非终结符集合
public List<char> Echar = new List<char>(50);//终结符集合

public string RStr_obitemset = "";

public void Buildprod(string str)
{

    SLRNode SLr;
    int i = 0;
    string left = "";
    string right = "";
    left += "S'";
    right += str[0];
    SLr = new SLRNode(left, right);//拓广文法开始
    SLRproNum.Add(SLr);
    while (i < str.Length)
    {
        left = right = "";//还原
        int j = i;
        while (i < str.Length && str[i] != '\r' && str[i] != '\n')//换行符‘\r\n’
        {
            if (str[i] == ' ')
            {
                i++;
                continue;
            }
            if (str[i] == '|')                 //  遇到'|'可构造一条产生式
            {
                SLr = new SLRNode(left, right);
                SLRproNum.Add(SLr);
                right = "";                    //产生式左边相同 右边重新积累
                i++;                           //跳过'|'
                continue;
            }
            if ((i - j) == 0)
            {
                if (!exist(Nchar, str[i]))//如果非终结符集合中不存在str[i],加入Nchar  产生式左边 只有非终结符 不必判断终结符
                    Nchar.Add(str[i]);
                left += str[i++];
            }
            else if (i - j <= 2)
                i++;
            else
            {
                if (isFinalsymbol(str[i]) && !exist(Nchar, str[i]))//如果非终结符集合中不存在str[i],加入Nchar  isfinalsymbol 非终结符返回T 终结符返回F
                    Nchar.Add(str[i]);
                else if (!isFinalsymbol(str[i]) && !exist(Echar, str[i]))//产生式右边 需要判断终结符
                    Echar.Add(str[i]);
                right += str[i++];
            }


        }//while

        i++;//跳过换行符
        if (left != "" && right != "")
        {
            SLr = new SLRNode(left, right);//构造每一行最后一个产生式,不存在'|'时就是该行产生式本身
            SLRproNum.Add(SLr);
        }
    }//while
    Echar.Add('#');

    //构造项目 对产生式集合LRproNum中的所有产生式都循环插'.'
    SLRNode Lobj;
    for (i = 0; i < SLRproNum.Count; i++)
    {
        left = "";
        right = "";
        for (int j = 0; j <= SLRproNum[i].Right.Length; j++)//j可以等于length  项目共length+1个
        {
            left = SLRproNum[i].Left;
            right = CreObj(SLRproNum[i].Right, j);//在第j个位置插入'.'
            if (j == SLRproNum[i].Right.Length && SLRobjNum.Count != 1)
            {
                //在产生式最后的位置插入. 即为归约项目   项目集中1号位置为接受项目
                Gy_obj.Add(SLRobjNum.Count);//归约项目在项目集中的序号 不用+1 本身就是从0开始的
            }
            Lobj = new SLRNode(left, right);
            SLRobjNum.Add(Lobj);
            left = "";//还原
            right = "";
        }
    }
    Creteitemsets();//项目集
    RStr_obitemset += "\r\n项目集构建:\r\n";
    for (int j = 0; j < proitemset.Count; j++)
    {
        RStr_obitemset += 'I' + j.ToString() + ':' + "\r\n";
        for (i = 0; i < proitemset[j].Container.Count; i++)
        {
            RStr_obitemset += SLRobjNum[proitemset[j].Container[i]].Left.ToString() + "->" + SLRobjNum[proitemset[j].Container[i]].Right.ToString() + "\r\n";
        }
    }
}

//求项目集
public void Creteitemsets()
{
    List<int> lr_item = new List<int>(100);//记录项目的序号
    lr_item.Add(0);
    lr_item = Closure(lr_item);//构造初始项目集 求闭包

    SLRitemsets LR_C = new SLRitemsets();
    LR_C.Container = lr_item;//集合----项目集序号的集合
    proitemset.Add(LR_C);//集合的集合----存放项目集序号集合 的集合


    for (int i = 0; i < proitemset.Count; i++)//整体集合中 第i个项目集
    {
        proitemset[i].Container.Sort();//排序由小到大 后面用于判断是否存在的比较
        int[] flag = new int[proitemset[i].Container.Count];
        for (int fi = 0; fi < proitemset[i].Container.Count; fi++)//标志位,用来判断该序号是否已经构造
        {
            flag[fi] = 0;
        }

        for (int j = 0; j < proitemset[i].Container.Count; j++)//第i个项目集的第j个项目
        {
            if (flag[j] == 1)//如果已经访问过 就不再构造 找下一个项目
                continue;
            int index = proitemset[i].Container[j];
            for (int pi = 0; pi < SLRobjNum[index].Right.Length - 1; pi++)//length-1是避免匹配到.在最后的规约项目
            {
                if (SLRobjNum[index].Right[pi] == '.')
                {

                    List<int> lr2_club = new List<int>(100);//记录项目的序号
                    char symbol = SLRobjNum[index].Right[pi + 1];//记录.a转移状态a.的符号a
                    lr2_club.Add((index + 1));//如果遇到.a形式的项目序号为index 那么项目a.的序号为index+1
                    for (int m1 = j + 1; m1 < proitemset[i].Container.Count; m1++)
                    {
                        //在第i个项目集中找到了可以移动的.:.a  重新遍历第i个项目集j项目之后的 找到同样可以移动a的项目集
                        int index2 = proitemset[i].Container[m1];
                        for (int m2 = 0; m2 < SLRobjNum[index2].Right.Length - 1; m2++)
                        {
                            if (SLRobjNum[index2].Right[m2] == '.' && SLRobjNum[index2].Right[m2 + 1] == symbol)
                            {
                                flag[m1] = 1;//标记位置为1 已经访问 之后不再访问
                                lr2_club.Add(index2 + 1);
                            }
                        }
                    }
                    lr2_club = Closure(lr2_club);//求闭包
                    int value = isexist(lr2_club);
                    if (value == -1)//-1表示不存在相同的
                    {
                        for (int m3 = 0; m3 < Gy_obj.Count; m3++)
                        {
                            if (isnexist(lr2_club, Gy_obj[m3]))
                            {
                                Gy_itemset.Add(proitemset.Count);
                            }
                        }
                        SLRitemsets LR_C2 = new SLRitemsets();
                        dfa[Pindex++] = new DFA(i, symbol, proitemset.Count);//count不用加1  本身从0开始
                        LR_C2.Container = lr2_club;
                        proitemset.Add(LR_C2);
                    }
                    else
                    {
                        dfa[Pindex++] = new DFA(i, symbol, value);
                    }
                    break;
                }
            }
        }
    }

}

//分析表

public void SLRAnaly()
{

}
//辅助函数
//判断非终结符或终结符是否存在于集合中
bool exist(List<char> list, char c)
{
    foreach (char ch in list)
    {
        if (ch == c)
            return true;
    }
    return false;
}

//判断是否为终结符
bool isFinalsymbol(char c)
{
    if (c >= 'a' && c <= 'z')
        return true;
    if (c >= 'A' && c <= 'Z')
        return false;
    return false;
}

//在字符串中插入'.'
string CreObj(string str, int i)
{
    string newstr = "";
    for (int j = 0; j < str.Length; j++)
    {
        if (j == i)
            newstr += '.';
        newstr += str[j];
    }
    if (i == str.Length)
        newstr += '.';
    return newstr;
}

//求闭包
List<int> Closure(List<int> lr_item)
{
    List<int> lr_club = new List<int>(100);//记录项目的序号
    for (int i = 0; i < lr_item.Count; i++)
    {
        lr_club.Add(lr_item[i]);
    }
    for (int i = 0; i < lr_item.Count; i++)
    {
        int index = lr_item[i];
        for (int j = 0; j < SLRproNum.Count; j++)
        {
            if (SLRproNum[j].Left[0] == SLRobjNum[index].Right[SLRobjNum[index].Right.IndexOf('.') + 1])//A->α.Bβ
            {
                string newright = CreObj(SLRproNum[j].Right, 0);//B->.γ
                SLRNode Lobj = new SLRNode(SLRproNum[j].Left, newright);
                int value = isexist(Lobj);
                if (value == -1)//不存在
                {
                    SLRobjNum.Add(Lobj);
                    lr_club.Add(SLRobjNum.Count - 1);
                }
                else
                {
                    if (isnexist(lr_club, value))
                        lr_club.Add(value);
                }
            }
        }
    }
    return lr_club;
}

//判断是否存在相同的项目集
int isexist(List<int> lr_club)
{
    for (int i = 0; i < proitemset.Count; i++)
    {
        if (lr_club.Count != proitemset[i].Container.Count)
            continue;
        bool flag = true;
        for (int j = 0; j < lr_club.Count; j++)
        {
            if (lr_club[j] != proitemset[i].Container[j])
            {
                flag = false;
                break;
            }
        }
        if (flag == true)
            return i;
    }
    return -1;
}

//判断项目集中是否存在该项目
bool isnexist(List<int> lr_club, int index)
{
    for (int i = 0; i < lr_club.Count; i++)
    {
        if (lr_club[i] == index)
            return false;
    }
    return true;
}

//构造SLR分析表
public void BuildSLRAna()
{
    SLRAna = new Table[proitemset.Count][];
    for (int i = 0; i < proitemset.Count; i++)
    {
        SLRAna[i] = new Table[Echar.Count + Nchar.Count];
        for (int j = 0; j < Echar.Count + Nchar.Count; j++)
        {
            SLRAna[i][j] = new Table();
        }
    }

    for (int i = 0; i < proitemset.Count; i++)
    {
        for (int j = 0; j < proitemset[i].Container.Count; j++)
        {
            int index = proitemset[i].Container[j];
            int dotIndex = SLRobjNum[index].Right.IndexOf('.');
            if (dotIndex == SLRobjNum[index].Right.Length - 1)//规约项
            {
                for (int k = 0; k < Echar.Count; k++)
                {
                    SLRAna[i][k].error = true;
                }
                SLRAna[i][Nchar.IndexOf(SLRobjNum[index].Left[0]) + Echar.Count] = new Table('r', Gy_obj.IndexOf(index));
            }
            else
            {
                char nextSymbol = SLRobjNum[index].Right[dotIndex + 1];
                if (isFinalsymbol(nextSymbol))
                {
                    int toIndex = -1;
                    for (int k = 0; k < Pindex; k++)
                    {
                        if (dfa[k].from == i && dfa[k].symbol == nextSymbol)
                        {
                            toIndex = dfa[k].to;
                            break;
                        }
                    }
                    SLRAna[i][Echar.IndexOf(nextSymbol)] = new Table('s', toIndex);
                }
                else
                {
                    int toIndex = -1;
                    for (int k = 0; k < Pindex; k++)
                    {
                        if (dfa[k].from == i && dfa[k].symbol == nextSymbol)
                        {
                            toIndex = dfa[k].to;
                            break;
                        }
                    }
                    SLRAna[i][Nchar.IndexOf(nextSymbol) + Echar.Count] = new Table('g', toIndex);
                }
            }
        }
    }
}

//SLR分析表的调用函数
public void SLRAnaly(string str)
{
    Buildprod(str);
    BuildSLRAna();
}

}


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

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