void Grammar::CalculateFollowSet() { if(pCanEmptyTable == 0) MakeCanReachEmptyTable(); for(int i = 0; i < nVn; i ++) { Set tempSet; FollowSet.push_back(tempSet); } FollowSet[Vn.FindPos(cStart)].Insert('#'); bool flag = false; do { flag = false; for(int i = 0; i < nP; i ++) { string strLeft, strRight; strLeft = P[i].GetLeft(); strRight = P[i].GetRight(); for ( unsigned int j = 0; j < strRight.length() - 1; j++) { char cChar = strRight[j]; if (Vn.Find(cChar)) { string temp; for(unsigned int k = j + 1; k < strRight.length(); k++) //temp.push_back(strRight[k]); temp += strRight[k]; Set firstset = GetFirstSet(temp); flag |= (FollowSet[Vn.FindPos(cChar)].Add(firstset - Set('@')) != 0); if (CanReachEmpty(temp)) { flag |= (FollowSet[Vn.FindPos(cChar)].Add(GetFollowSet(strLeft[0])) != 0); } } } if (Vn.Find(strRight[strRight.length() -1])) flag |= (FollowSet[Vn.FindPos(strRight[strRight.length() -1])].Add(GetFollowSet(strLeft[0])) != 0); } }while(flag); } 代码超级详细解释
时间: 2024-03-30 07:38:59 浏览: 9
这是一个计算文法的Follow集的函数,主要实现以下功能:
1. 先判断是否已经计算出能够推出空串的非终结符集合,如果没有则调用MakeCanReachEmptyTable()函数计算。
2. 对于每个非终结符,都创建一个空的Follow集合。
3. 将起始符号的Follow集合设置为“#”。
4. 循环计算每个产生式的Follow集合,直到没有新元素加入集合为止。
5. 对于每个产生式A -> B1B2...Bn,将B1的Follow集合加入B2的Follow集合,B2的Follow集合加入B3的Follow集合,以此类推。
6. 如果Bn能够推出空串,则将A的Follow集合加入Bn-1的Follow集合。
7. 如果Bn是非终结符,则将A的Follow集合加入Bn的Follow集合。
现在我们来详细解释一下函数的具体实现:
首先,我们创建一个空的Follow集合,用于存储每个非终结符的Follow集合。
然后,我们将起始符号的Follow集合设置为“#”。
进入主循环,我们对于每个产生式A -> B1B2...Bn,从左到右扫描B1到Bn-1,进行如下操作:
1. 如果B1是非终结符,则将A的Follow集合加入B1的Follow集合。
2. 如果Bn能够推出空串,则将A的Follow集合加入Bn-1的Follow集合。
3. 对于B1到Bn-1中的每个非终结符B,将B的Follow集合加入B+1的Follow集合。
接下来,我们处理Bn,如果Bn是非终结符,则将A的Follow集合加入Bn的Follow集合。
最后,我们判断是否有新元素加入Follow集合,如果有则继续循环,否则跳出循环。
其中,Set是一个自定义的集合类型,Vn表示非终结符集合,P是产生式集合,cStart表示文法的起始符号。