CanonSharp/CanonSharp.Combinator/Abstractions/Parser.cs

44 lines
1.4 KiB
C#
Raw Normal View History

using CanonSharp.Combinator.Extensions;
namespace CanonSharp.Combinator.Abstractions;
/// <summary>
/// 解析器抽象基类
/// </summary>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="T">解析结果类型</typeparam>
public abstract class Parser<TToken, T>
{
/// <summary>
/// 解析器运行函数
/// </summary>
/// <param name="state">解析的输入流状态</param>
/// <param name="continuation">运行之后的后继函数</param>
/// <typeparam name="TState">输入流状态类型</typeparam>
/// <typeparam name="TResult">后继函数运行之后的解析结果类型</typeparam>
/// <returns></returns>
internal abstract ParseResult<TToken, TResult> Run<TState, TResult>(TState state,
Func<ParseResult<TToken, T>, ParseResult<TToken, TResult>> continuation)
where TState : IReadState<TToken, TState>;
public ParseResult<TToken, T> Parse<TState>(TState state) where TState : IReadState<TToken, TState>
{
return Run(state);
}
private ParseResult<TToken, T> Run<TState>(TState state) where TState : IReadState<TToken, TState>
{
try
{
return Run(state, result => result);
}
catch (Exception e)
{
return ParseResultBuilder.Fail<TToken, TState, T>(e, state);
}
}
public static Parser<TToken, T> operator |(Parser<TToken, T> a, Parser<TToken, T> b)
=> a.Alternative(b);
}