SLR(1) 文法分析器构造中的 ComputeFirst() 和 ComputeFollow() 函数错误及修复

在构造 SLR(1) 文法分析器的过程中,ComputeFirst() 和 ComputeFollow() 函数是至关重要的。这两个函数分别用于计算文法符号的 First 集和 Follow 集。

本文分析的代码中,ComputeFirst() 和 ComputeFollow() 函数存在一个共同的错误:参数 1: 无法从“string”转换为“char”。这个错误是由于在使用 Dictionary<char, HashSet<char>> 类型存储 First 集和 Follow 集时,将字符串作为键使用了,而实际上键应该为字符类型。

以下是 ComputeFirst() 函数改正后的代码:c#public void ComputeFirst(){ //初始化 First 集 foreach (char c in Nchar) { first.Add(c, new HashSet()); } foreach (char c in Echar) { first.Add(c, new HashSet()); first[c].Add(c); } first['ε'].Add('ε'); //计算 First 集 bool flag = true; while (flag) { flag = false; foreach (SLRNode node in SLRproNum) { bool canEpsilon = true; HashSet temp = new HashSet(); for (int i = 0; i < node.Right.Length; i++) { // 修改处:使用 node.Right[i] 获取字符 if (Echar.Contains(node.Right[i])) { temp.UnionWith(first[node.Right[i]]); if (!first[node.Right[i]].Contains('ε')) { canEpsilon = false; break; } } else { canEpsilon = false; // 修改处:使用 node.Right[i] 获取字符 temp.UnionWith(first[node.Right[i]]); break; } } if (canEpsilon) { temp.Add('ε'); } // 修改处:使用 node.Left 获取字符 if (!temp.SetEquals(first[node.Left])) { // 修改处:使用 node.Left 获取字符 first[node.Left].UnionWith(temp); flag = true; } } }}

在上述代码中,我们对原代码中使用字符串作为键的地方进行了修改,将其改为使用字符作为键,从而解决了“无法从'string'转换为'char'”的错误。

需要注意的是,ComputeFollow() 函数也存在同样的错误,需要进行类似的修改才能正常运行。

SLR(1) 文法分析器构造中的 ComputeFirst() 和 ComputeFollow() 函数错误及修复

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

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