CanonSharp/CanonSharp.Combinator/Parsers/Bases/AlternativeParser.cs
jackfiled 3ed8bf5d36
All checks were successful
Run unit test / Unit-Test (push) Successful in 41s
feat: Parser Combinator库和词法分析器 (#2)
Reviewed-on: https://git.bupt-hpc.cn/jackfiled/CanonSharp/pulls/2
Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Co-committed-by: jackfiled <xcrenchangjun@outlook.com>
2024-08-13 14:46:11 +08:00

22 lines
824 B
C#

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>(Parser<TToken, T> first, Parser<TToken, T> second)
: Parser<TToken, T>
{
internal override ParseResult<TToken, TResult> Run<TState, TResult>(TState state,
Func<ParseResult<TToken, T>, ParseResult<TToken, TResult>> continuation)
{
return first.Run(state, result => result.CaseOf(continuation, _ => second.Run(state, continuation)));
}
}