C#实现LL(1)语法分析器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace LL1Parser
{
public partial class Form1 : Form
{
// ... 其他代码 ...
private void Analyse(string text, Dictionary<string, List<string>> selects)
{
// 初始化分析器
analyse = new Stack<char>();
input = new Stack<char>();
result_analys = new List<string>();
result_input = new List<string>();
result_parse = new List<string>();
analyse.Push('#');
analyse.Push(selects.First().Key[0]);
input.Push('#');
for (int i = text.Length - 1; i >= 0; i--)
{
input.Push(text[i]);
}
result_analys.Add(analyse.GetString());
result_input.Add(input.GetString());
while (true)
{
// 如果分析栈栈顶元素为终结符
if (!char.IsUpper(analyse.Peek()))
{
// 当两个栈都只剩下'#'时,说明匹配成功
if (analyse.Peek() == input.Peek() && analyse.Count == 1 && input.Count == 1)
{
result_parse.Add('成功');
return;
}
if (analyse.Peek() == input.Peek())
{
result_parse.Add("'"+ analyse.Peek() + "'匹配");
analyse.Pop();
input.Pop();
result_analys.Add(analyse.GetString());
result_input.Add(input.GetString());
continue;
}
else
{
result_parse.Add('失败');
return;
}
}
// 如果分析栈栈顶元素为非终结符
string nonterminal = analyse.Peek().ToString();
string terminal = input.Peek().ToString();
if (!table.ContainsKey(nonterminal) || !table[nonterminal].ContainsKey(terminal))
{
result_parse.Add('失败');
return;
}
string production = table[nonterminal][terminal];
result_parse.Add(nonterminal + '->' + production);
analyse.Pop();
if (production != '#')
{
for (int i = production.Length - 1; i >= 0; i--)
{
analyse.Push(production[i]);
}
}
result_analys.Add(analyse.GetString());
result_input.Add(input.GetString());
}
}
// ... 其他代码 ...
}
}
原文地址: https://www.cveoy.top/t/topic/fXMI 著作权归作者所有。请勿转载和采集!