using Canon.Core.Exceptions;
namespace Canon.Core.SemanticParser;
///
///符号表类
///
public class SymbolTable
{
public Dictionary Entries;
public TypeTable TypesTable; //当前符号表对应的类型表
public SymbolTable? PreTable; //直接外围符号表
public SymbolTable()
{
Entries = new Dictionary();
TypesTable = new TypeTable();
PreTable = null;
}
public SymbolTable(SymbolTable preTable)
{
Entries = new Dictionary();
TypesTable = new TypeTable();
PreTable = preTable;
}
///
/// 向符号表里插入一个表项
///
public void AddEntry(string idName, IdentifierType type, bool isConst, bool isVarParam)
{
if (Check(idName))
{
throw new SemanticException("failed to insert to SymbolTable! " + idName + " is defined repeatedly");
}
Entries.Add(idName, new SymbolTableEntry(idName, type, isConst, isVarParam));
}
public void AddEntry(string idName, IdentifierType type, SymbolTable subTable)
{
if (Check(idName))
{
throw new SemanticException("failed to insert to SymbolTable! " + idName + " is defined repeatedly");
}
Entries.Add(idName, new SymbolTableEntry(idName, type, subTable));
}
///
///检查符号表,看是否有变量重复声明
///
/// 查询的id名称
/// 如果变量重复声明,返回true
public bool Check(string idName)
{
return Entries.ContainsKey(idName);
}
///
/// 在符号表里查找,看当前引用变量是否声明
///
/// 查询的id名称
/// 如果有定义,返回true
public bool Find(string idName)
{
if (Entries.ContainsKey(idName))
{
return true;
}
if (PreTable is not null && PreTable.Entries.ContainsKey(idName))
{
return true;
}
throw new SemanticException("identifier "+ idName + " is not defined!");
}
///
/// 通过id名获取id的类型
///
/// id名字
/// id在符号表里的类型
public IdentifierType GetIdTypeByName(string idName)
{
if (Entries.ContainsKey(idName))
{
return Entries[idName].Type;
}
if (PreTable is not null && PreTable.Entries.ContainsKey(idName))
{
return PreTable.Entries[idName].Type;
}
throw new SemanticException("identifier "+ idName + " is not defined!");
}
public bool IsConst(string idName)
{
return Find(idName) && Entries[idName].IsConst;
}
}