2024-08-13 14:46:11 +08:00
|
|
|
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>
|
2024-08-18 12:01:27 +08:00
|
|
|
internal sealed class AlternativeParser<TToken, T>(IParser<TToken, T> first, IParser<TToken, T> second)
|
|
|
|
: IParser<TToken, T>
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
2024-08-18 12:01:27 +08:00
|
|
|
public IParseResult<TToken, TResult> Run<TState, TResult>(TState state,
|
|
|
|
Func<IParseResult<TToken, T>, IParseResult<TToken, TResult>> continuation)
|
|
|
|
where TState : IReadState<TToken, TState>
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
|
|
|
return first.Run(state, result => result.CaseOf(continuation, _ => second.Run(state, continuation)));
|
|
|
|
}
|
|
|
|
}
|