CanonSharp/CanonSharp.Tests/LexicalAnalyzerTests/RegularExpressionTests.cs

78 lines
2.6 KiB
C#
Raw Normal View History

2024-07-27 14:56:28 +08:00
using CanonSharp.Common.LexicalAnalyzer;
namespace CanonSharp.Tests.LexicalAnalyzerTests;
public class RegularExpressionTests
{
[Fact]
public void KleeneTest()
{
RegularExpression expression = RegularExpression.Concatenate(
RegularExpression.Kleene(RegularExpression.Single('a')),
RegularExpression.Single('b'));
NondeterministicFiniteAutomation automation = expression.Convert2Nfa();
automation.Start.Transactions.TryGetValue(EmptyChar.Empty, out HashSet<NondeterministicState>? next);
Assert.NotNull(next);
Assert.Contains(next, s => s.Transactions.ContainsKey(new EmptyChar('a')));
Assert.Contains(next, s => s.Transactions.ContainsKey(new EmptyChar('b')));
}
[Fact]
public void AlternateTest()
{
RegularExpression expression = RegularExpression.Alternate(
RegularExpression.Kleene(RegularExpression.Single('a')),
RegularExpression.Single('b'));
NondeterministicFiniteAutomation automation = expression.Convert2Nfa();
automation.Start.Transactions.TryGetValue(EmptyChar.Empty, out HashSet<NondeterministicState>? next);
Assert.NotNull(next);
Assert.Contains(next, s => s.Transactions.ContainsKey(new EmptyChar('b')));
NondeterministicState? state = (from item in next
where item.Transactions[EmptyChar.Empty].Count == 2
select item).FirstOrDefault();
Assert.NotNull(state);
Assert.Contains(state.Transactions[EmptyChar.Empty],
s => s.Transactions.ContainsKey(new EmptyChar('a')));
}
[Fact]
public void ConvertTest()
{
RegularExpression expression = RegularExpression.Alternate(
RegularExpression.Kleene(RegularExpression.Single('a')),
RegularExpression.Single('b'));
NondeterministicFiniteAutomation automation = expression.Convert2Nfa();
DeterministicFiniteAutomation dfa = DeterministicFiniteAutomation.Create(automation);
DeterministicState state2 = dfa.Start.Transaction['a'];
Assert.Equal(state2, state2.Transaction['a']);
DeterministicState state3 = dfa.Start.Transaction['b'];
Assert.Empty(state3.Transaction);
Assert.Equal(3, dfa.FinalStates.Count);
}
[Fact]
public void NondeterministicStateSetTest()
{
Dictionary<NondeterministicStateSet, char> map = [];
NondeterministicState key1 = new();
NondeterministicState key2 = new();
map.Add(new NondeterministicStateSet([key1, key2]), 'a');
Assert.Equal('a', map[new NondeterministicStateSet([key2, key1])]);
}
}