2024-08-13 14:46:11 +08:00
|
|
|
using CanonSharp.Combinator.Extensions;
|
|
|
|
|
|
|
|
namespace CanonSharp.Combinator.Abstractions;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 解析器抽象基类
|
|
|
|
/// </summary>
|
|
|
|
/// <typeparam name="TToken">输入流类型</typeparam>
|
|
|
|
/// <typeparam name="T">解析结果类型</typeparam>
|
2024-08-14 19:41:10 +08:00
|
|
|
public interface IParser<TToken, out T>
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// 解析器运行函数
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="state">解析的输入流状态</param>
|
|
|
|
/// <param name="continuation">运行之后的后继函数</param>
|
|
|
|
/// <typeparam name="TState">输入流状态类型</typeparam>
|
|
|
|
/// <typeparam name="TResult">后继函数运行之后的解析结果类型</typeparam>
|
|
|
|
/// <returns></returns>
|
2024-08-14 19:41:10 +08:00
|
|
|
internal IParseResult<TToken, TResult> Run<TState, TResult>(TState state,
|
|
|
|
Func<IParseResult<TToken, T>, IParseResult<TToken, TResult>> continuation)
|
2024-08-13 14:46:11 +08:00
|
|
|
where TState : IReadState<TToken, TState>;
|
|
|
|
|
2024-08-14 19:41:10 +08:00
|
|
|
public IParseResult<TToken, T> Parse<TState>(TState state) where TState : IReadState<TToken, TState>
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
|
|
|
return Run(state);
|
|
|
|
}
|
|
|
|
|
2024-08-14 19:41:10 +08:00
|
|
|
private IParseResult<TToken, T> Run<TState>(TState state) where TState : IReadState<TToken, TState>
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
return Run(state, result => result);
|
|
|
|
}
|
|
|
|
catch (Exception e)
|
|
|
|
{
|
|
|
|
return ParseResultBuilder.Fail<TToken, TState, T>(e, state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-14 19:41:10 +08:00
|
|
|
public static IParser<TToken, T> operator |(IParser<TToken, T> a, IParser<TToken, T> b)
|
2024-08-13 14:46:11 +08:00
|
|
|
=> a.Alternative(b);
|
|
|
|
}
|