CanonSharp/CanonSharp.Pascal/Parser/LexicalTokenReadState.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

54 lines
1.3 KiB
C#

using CanonSharp.Combinator.Abstractions;
using CanonSharp.Pascal.Scanner;
namespace CanonSharp.Pascal.Parser;
public sealed class LexicalTokenReadState : IReadState<LexicalToken, LexicalTokenReadState>
{
private readonly List<LexicalToken> _tokens;
private readonly int _pos;
public LexicalToken Current => _tokens[_pos];
public bool HasValue => _pos < _tokens.Count;
public LexicalTokenReadState Next => new(_tokens, _pos + 1);
private LexicalTokenReadState(List<LexicalToken> tokens, int pos)
{
_tokens = tokens;
_pos = pos;
}
public LexicalTokenReadState(IEnumerable<LexicalToken> tokens)
{
_tokens = tokens.ToList();
_pos = 0;
}
public bool Equals(LexicalTokenReadState? other)
{
if (other is null)
{
return false;
}
if (_tokens.Count != other._tokens.Count)
{
return false;
}
foreach ((LexicalToken first, LexicalToken second) in _tokens.Zip(other._tokens))
{
if (!first.Equals(second))
{
return false;
}
}
return _pos == other._pos;
}
public override string ToString() => HasValue ? Current.ToString() : "End of input stream.";
}