CanonSharp/CanonSharp.Combinator/Text/StringParser.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

23 lines
965 B
C#

using CanonSharp.Combinator.Abstractions;
using CanonSharp.Combinator.Extensions;
using CanonSharp.Combinator.Parsers;
namespace CanonSharp.Combinator.Text;
/// <summary>
/// 字符串解析器
/// </summary>
/// <param name="except">期望的字符串</param>
/// <param name="comparison">字符串比较模式</param>
public class StringParser(string except, StringComparison comparison) : PrimitiveParser<char, string>
{
protected override ParseResult<char, string> Run<TState>(TState state)
{
TState[] states = state.AsEnumerable<char, TState>().Take(except.Length).ToArray();
string actual = new(states.Select(x => x.Current).ToArray());
return string.Equals(except, actual, comparison)
? ParseResultBuilder.Succeed<char, TState, string>(actual, states.Length == 0 ? state : states.Last().Next)
: ParseResultBuilder.Fail<char, TState, string>($"Except '{except}' but found '{actual}.", state);
}
}