2024-08-13 14:46:11 +08:00
|
|
|
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>(
|
2024-08-18 12:01:27 +08:00
|
|
|
IParser<TToken, TIntermediate> parser,
|
2024-08-13 14:46:11 +08:00
|
|
|
Func<TIntermediate, T> successfulHandler,
|
2024-08-18 12:01:27 +08:00
|
|
|
Func<IFailedResult<TToken, TIntermediate>, T> failedHandler) : ModifiedParser<TToken, TIntermediate, T>(parser)
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
2024-08-18 12:01:27 +08:00
|
|
|
protected override IParseResult<TToken, T> Succeed<TState>(TState state,
|
|
|
|
ISuccessfulResult<TToken, TIntermediate> successfulResult)
|
2024-08-13 14:46:11 +08:00
|
|
|
=> successfulResult.Map(successfulHandler);
|
|
|
|
|
2024-08-18 12:01:27 +08:00
|
|
|
protected override IParseResult<TToken, T> Fail<TState>(TState state,
|
|
|
|
IFailedResult<TToken, TIntermediate> failedResult)
|
2024-08-13 14:46:11 +08:00
|
|
|
=> ParseResultBuilder.Succeed<TToken, TState, T>(failedHandler(failedResult), state);
|
|
|
|
}
|