CanonSharp/CanonSharp.Combinator/Parsers/Modifiers/SuccessfulMapParser.cs

27 lines
1.2 KiB
C#
Raw Normal View History

using CanonSharp.Combinator.Abstractions;
namespace CanonSharp.Combinator.Parsers.Modifiers;
/// <summary>
/// 成功映射的解析器
/// </summary>
/// <param name="parser">上游解析器</param>
/// <param name="successfulHandler">当上游成功时的处理函数</param>
/// <param name="failedHandler">当上游失败时的处理函数</param>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="TIntermediate">上游解析器解析结果类型</typeparam>
/// <typeparam name="T">最终的解析结果类型</typeparam>
internal sealed class SuccessfulMapParser<TToken, TIntermediate, T>(
IParser<TToken, TIntermediate> parser,
Func<TIntermediate, T> successfulHandler,
Func<IFailedResult<TToken, TIntermediate>, T> failedHandler) : ModifiedParser<TToken, TIntermediate, T>(parser)
{
protected override IParseResult<TToken, T> Succeed<TState>(TState state,
ISuccessfulResult<TToken, TIntermediate> successfulResult)
=> successfulResult.Map(successfulHandler);
protected override IParseResult<TToken, T> Fail<TState>(TState state,
IFailedResult<TToken, TIntermediate> failedResult)
=> ParseResultBuilder.Succeed<TToken, TState, T>(failedHandler(failedResult), state);
}