CanonSharp/CanonSharp.Combinator/Parsers/Bases/AlternativeParser.cs

23 lines
869 B
C#
Raw Permalink Normal View History

using CanonSharp.Combinator.Abstractions;
namespace CanonSharp.Combinator.Parsers.Bases;
/// <summary>
/// 选择解析器
/// 如果第一个不成功则调用第二个
/// </summary>
/// <param name="first">第一个解析器</param>
/// <param name="second">第二个解析器</param>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="T">解析器结果类型</typeparam>
internal sealed class AlternativeParser<TToken, T>(IParser<TToken, T> first, IParser<TToken, T> second)
: IParser<TToken, T>
{
public IParseResult<TToken, TResult> Run<TState, TResult>(TState state,
Func<IParseResult<TToken, T>, IParseResult<TToken, TResult>> continuation)
where TState : IReadState<TToken, TState>
{
return first.Run(state, result => result.CaseOf(continuation, _ => second.Run(state, continuation)));
}
}