add: LrState

This commit is contained in:
jackfiled 2024-03-10 11:22:19 +08:00
parent 410593f326
commit 94622f5796
2 changed files with 80 additions and 2 deletions

View File

@ -1,17 +1,29 @@
namespace Canon.Core.GrammarParser; namespace Canon.Core.GrammarParser;
/// <summary> /// <summary>
/// An expression in the LR, like 'program_struct -> ~program_head ; program_body.' /// LR语法中的一个表达式例如 'program_struct -> ~program_head ; program_body'
/// The '~' is the shift position now. /// 其中'~'标识当前移进到达的位置
/// </summary> /// </summary>
public class Expression : IEquatable<Expression> public class Expression : IEquatable<Expression>
{ {
/// <summary>
/// 表达式的左部
/// </summary>
public required NonTerminator Left { get; init; } public required NonTerminator Left { get; init; }
/// <summary>
/// 表达式的向前看字符串
/// </summary>
public required Terminator LookAhead { get; init; } public required Terminator LookAhead { get; init; }
/// <summary>
/// 表达式的右部
/// </summary>
public required List<TerminatorBase> Right { get; init; } public required List<TerminatorBase> Right { get; init; }
/// <summary>
/// 当前移进的位置
/// </summary>
public int Pos { get; set; } public int Pos { get; set; }
public bool Equals(Expression? other) public bool Equals(Expression? other)

View File

@ -0,0 +1,66 @@
namespace Canon.Core.GrammarParser;
/// <summary>
/// LR语法中的一个项目集规范族
/// 也就是自动机中的一个状态
/// </summary>
public class LrState : IEquatable<LrState>
{
/// <summary>
/// 项目集规范族
/// </summary>
public required HashSet<Expression> Expressions { get; init; }
/// <summary>
/// 自动机的迁移规则
/// </summary>
public Dictionary<TerminatorBase, LrState> Transformer { get; } = [];
public bool Equals(LrState? other)
{
if (other is null)
{
return false;
}
if (Expressions.Count != other.Expressions.Count)
{
return false;
}
// 如果两个集合的大小相等,且一个是另一个的子集,那么两个集合相等。
return Expressions.IsSubsetOf(other.Expressions);
}
public override bool Equals(object? obj)
{
if (obj is not LrState other)
{
return false;
}
return Equals(other);
}
public override int GetHashCode()
{
int hash = 0;
foreach (Expression expression in Expressions)
{
hash ^= expression.GetHashCode();
}
return hash;
}
public static bool operator ==(LrState a, LrState b)
{
return a.Equals(b);
}
public static bool operator !=(LrState a, LrState b)
{
return !a.Equals(b);
}
}