2024-08-13 14:46:11 +08:00
|
|
|
using CanonSharp.Combinator.Abstractions;
|
|
|
|
|
|
|
|
namespace CanonSharp.Combinator.Parsers;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// 修改解析器返回结果的解析器基类
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="parser">需要修改结果的解析器</param>
|
|
|
|
/// <typeparam name="TToken">输入流类型</typeparam>
|
|
|
|
/// <typeparam name="TIntermediate">需要修改结果的解析器</typeparam>
|
|
|
|
/// <typeparam name="T">最终返回的解析结果</typeparam>
|
2024-08-14 19:41:10 +08:00
|
|
|
public abstract class ModifiedParser<TToken, TIntermediate, T>(IParser<TToken, TIntermediate> parser)
|
|
|
|
: IParser<TToken, T>
|
2024-08-13 14:46:11 +08:00
|
|
|
{
|
2024-08-14 19:41:10 +08:00
|
|
|
protected abstract IParseResult<TToken, T> Fail<TState>(TState state,
|
|
|
|
IFailedResult<TToken, TIntermediate> failedResult)
|
2024-08-13 14:46:11 +08:00
|
|
|
where TState : IReadState<TToken, TState>;
|
|
|
|
|
2024-08-14 19:41:10 +08:00
|
|
|
protected abstract IParseResult<TToken, T> Succeed<TState>(TState state,
|
|
|
|
ISuccessfulResult<TToken, TIntermediate> successfulResult)
|
2024-08-13 14:46:11 +08:00
|
|
|
where TState : IReadState<TToken, TState>;
|
|
|
|
|
2024-08-14 19:41:10 +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
|
|
|
=> parser.Run(state, result => result.CaseOf(
|
|
|
|
success => continuation(Succeed(state, success)),
|
|
|
|
failure => continuation(Fail(state, failure))));
|
|
|
|
}
|