CanonSharp/CanonSharp.Tests/CombinatorsTests/BasicParsersTests.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

85 lines
2.7 KiB
C#

using CanonSharp.Combinator;
using CanonSharp.Combinator.Abstractions;
using CanonSharp.Combinator.Extensions;
using CanonSharp.Tests.Utils;
using static CanonSharp.Combinator.ParserBuilder;
namespace CanonSharp.Tests.CombinatorsTests;
public class BasicParsersTests : ParserTestsBase
{
[Fact]
public void AlternativeTest()
{
Parser<char, char> parser = Token('a') | Token('b');
ValidateSuccessfulResult(parser, 'a', "abc");
ValidateSuccessfulResult(parser, 'b', "bcd");
ValidateFailedResult(parser, "cde");
parser = Token('a').Alternative(_ => Token('b'));
ValidateSuccessfulResult(parser, 'a', "abc");
ValidateSuccessfulResult(parser, 'b', "bcd");
ValidateFailedResult(parser, "cde");
}
[Fact]
public void BindTest()
{
Parser<char, char> parser = Token('a').Bind(_ => Token('b')).Bind(_ => Token('c'));
ValidateSuccessfulResult(parser, 'c', "abc");
ValidateFailedResult(parser, "acd");
ValidateFailedResult(parser, "ab");
}
[Fact]
public void MapTest()
{
Parser<char, string> parser = Token('a').Map(c => $"{c}");
ValidateSuccessfulResult(parser, "a", "abc");
parser = Token('a').Map("test");
ValidateSuccessfulResult(parser, "test", "abc");
}
[Fact]
public void NextTest()
{
Parser<char, char> parser = Token('a').Next(_ => Token('a'), _ => Token('b'));
ValidateSuccessfulResult(parser, 'a', "aaa");
ValidateSuccessfulResult(parser, 'b', "bbb");
parser = Token('a').Next(_ => Token('a'), _ => 'b');
ValidateSuccessfulResult(parser, 'b', "bbb");
parser = Token('a').Next(_ => Pure<char, char>('1'), '2');
ValidateSuccessfulResult(parser, '1', "aaa");
ValidateSuccessfulResult(parser, '2', "bbb");
}
[Fact]
public void NextTest2()
{
Parser<char, string> parser = Token('a').Next(_ => "123", _ => Pure<char, string>("456"));
ValidateSuccessfulResult(parser, "123", "aaa");
ValidateSuccessfulResult(parser, "456", "bbb");
parser = Token('a').Next(_ => "123", _ => "456");
ValidateSuccessfulResult(parser, "123", "aaa");
ValidateSuccessfulResult(parser, "456", "bbb");
parser = Token('a').Next(_ => "123", "456");
ValidateSuccessfulResult(parser, "123", "aaa");
ValidateSuccessfulResult(parser, "456", "bbb");
}
[Fact]
public void FixTest()
{
Parser<char, char> parser = Fix<char, Unit>(self => Token('a').Next(_ => self, Unit.Instance))
.Bind(_ => Token('b'));
ValidateSuccessfulResult(parser, 'b', "aaaaab");
}
}