CanonSharp/CanonSharp.Combinator/Parsers/Modifiers/TryParser.cs

24 lines
1011 B
C#
Raw Normal View History

using CanonSharp.Combinator.Abstractions;
namespace CanonSharp.Combinator.Parsers.Modifiers;
/// <summary>
/// 尝试的解析器
/// 当成功时直接返回原结果
/// 当失败时调用resume函数处理失败结果并返回成功结果
/// </summary>
/// <param name="parser">上游解析器</param>
/// <param name="resume">处理失败结果的恢复函数</param>
/// <typeparam name="TToken">输入流令牌</typeparam>
/// <typeparam name="T">解析器返回结果类型</typeparam>
internal sealed class TryParser<TToken, T>(Parser<TToken, T> parser, Func<FailedResult<TToken, T>, T> resume)
: ModifiedParser<TToken, T, T>(parser)
{
protected override ParseResult<TToken, T> Succeed<TState>(TState state,
SuccessfulResult<TToken, T> successfulResult)
=> successfulResult;
protected override ParseResult<TToken, T> Fail<TState>(TState state, FailedResult<TToken, T> failedResult)
=> ParseResultBuilder.Succeed<TToken, TState, T>(resume(failedResult), state);
}