CanonSharp/CanonSharp.Combinator/Parsers/Modifiers/ReverseParser.cs

27 lines
1.1 KiB
C#
Raw Normal View History

using CanonSharp.Combinator.Abstractions;
namespace CanonSharp.Combinator.Parsers.Modifiers;
/// <summary>
/// 翻转结果的解析器
/// 当成功时失败
/// 当失败时返回指定的成功结果
/// </summary>
/// <param name="parser">上游解析器</param>
/// <param name="result">期望中的结果</param>
/// <typeparam name="TToken">输入流的类型</typeparam>
/// <typeparam name="TIntermediate">上游解析器结果类型</typeparam>
/// <typeparam name="T">最终的返回结果</typeparam>
internal sealed class ReverseParser<TToken, TIntermediate, T>(Parser<TToken, TIntermediate> parser, T result)
: ModifiedParser<TToken, TIntermediate, T>(parser)
{
protected override ParseResult<TToken, T> Succeed<TState>(TState state,
SuccessfulResult<TToken, TIntermediate> successfulResult)
=> ParseResultBuilder.Fail<TToken, TState, T>($"Unexpected successful result: {successfulResult.Value}",
state);
protected override ParseResult<TToken, T> Fail<TState>(TState state,
FailedResult<TToken, TIntermediate> failedResult)
=> ParseResultBuilder.Succeed<TToken, TState, T>(result, state);
}