CanonSharp/CanonSharp.Combinator/Parsers/Primitives/FailedParser.cs
jackfiled cf19f8197e feat: Grammar Parser (#3)
Reviewed-on: https://git.bupt-hpc.cn/jackfiled/CanonSharp/pulls/3
Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Co-committed-by: jackfiled <xcrenchangjun@outlook.com>
2024-08-18 12:01:27 +08:00

52 lines
2.0 KiB
C#

using CanonSharp.Combinator.Abstractions;
namespace CanonSharp.Combinator.Parsers.Primitives;
/// <summary>
/// 直接失败的解析器
/// </summary>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="T">解析结果的类型</typeparam>
internal sealed class FailedParser<TToken, T> : PrimitiveParser<TToken, T>
{
protected override IParseResult<TToken, T> Run<TState>(TState state)
=> ParseResultBuilder.Fail<TToken, TState, T>(state);
}
/// <summary>
/// 含有失败信息的失败解析器
/// </summary>
/// <param name="message">失败信息</param>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="T">解析结果的类型</typeparam>
internal sealed class FailedParserWithMessage<TToken, T>(string message) : PrimitiveParser<TToken, T>
{
protected override IParseResult<TToken, T> Run<TState>(TState state)
=> ParseResultBuilder.Fail<TToken, TState, T>(message, state);
}
/// <summary>
/// 按照输入状态产生失败信息的失败解析器
/// </summary>
/// <param name="messageFunc">产生失败信息的函数</param>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="T">解析结果的类型</typeparam>
internal sealed class FailedParserWithDelayedMessage<TToken, T>(Func<IReadState<TToken>, string> messageFunc)
: PrimitiveParser<TToken, T>
{
protected override IParseResult<TToken, T> Run<TState>(TState state)
=> ParseResultBuilder.Fail<TToken, TState, T>(messageFunc(state), state);
}
/// <summary>
/// 含有失败异常的失败解析器
/// </summary>
/// <param name="e">异常</param>
/// <typeparam name="TToken">输入流类型</typeparam>
/// <typeparam name="T">解析结果的类型</typeparam>
internal sealed class FailedParserWithException<TToken, T>(Exception e) : PrimitiveParser<TToken, T>
{
protected override IParseResult<TToken, T> Run<TState>(TState state)
=> ParseResultBuilder.Fail<TToken, TState, T>(e, state);
}