27 lines
1.2 KiB
C#
27 lines
1.2 KiB
C#
|
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>(
|
||
|
Parser<TToken, TIntermediate> parser,
|
||
|
Func<TIntermediate, T> successfulHandler,
|
||
|
Func<FailedResult<TToken, TIntermediate>, T> failedHandler) : ModifiedParser<TToken, TIntermediate, T>(parser)
|
||
|
{
|
||
|
protected override ParseResult<TToken, T> Succeed<TState>(TState state,
|
||
|
SuccessfulResult<TToken, TIntermediate> successfulResult)
|
||
|
=> successfulResult.Map(successfulHandler);
|
||
|
|
||
|
protected override ParseResult<TToken, T> Fail<TState>(TState state,
|
||
|
FailedResult<TToken, TIntermediate> failedResult)
|
||
|
=> ParseResultBuilder.Succeed<TToken, TState, T>(failedHandler(failedResult), state);
|
||
|
}
|