feat: 正则词法识别器 (#1)

Reviewed-on: https://git.bupt-hpc.cn/jackfiled/CanonSharp/pulls/1
Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Co-committed-by: jackfiled <xcrenchangjun@outlook.com>
This commit is contained in:
2024-07-29 16:59:29 +08:00
committed by 任昌骏
parent 6ff8622906
commit 3c0d51cec5
11 changed files with 587 additions and 6 deletions

View File

@@ -0,0 +1,78 @@
using CanonSharp.Common.Abstractions;
namespace CanonSharp.Common.Reader;
public class SourceReader : ISourceReader
{
private readonly StreamReader _reader;
private char? _lookAhead;
public SourceReader(string filename)
{
FileInfo source = new(filename);
if (!source.Exists)
{
throw new InvalidOperationException();
}
_reader = new StreamReader(filename);
}
public char Read()
{
if (_lookAhead.HasValue)
{
char result = _lookAhead.Value;
_lookAhead = null;
return result;
}
if (!TryFetchChar(out char c))
{
throw new InvalidOperationException();
}
return c;
}
public bool TryPeek(out char c)
{
if (_lookAhead.HasValue)
{
c = _lookAhead.Value;
return true;
}
if (!TryFetchChar(out c))
{
return false;
}
_lookAhead = c;
return true;
}
private readonly char[] _buffer = new char[1024];
private int _length;
private int _count;
private bool TryFetchChar(out char c)
{
if (_length == _count)
{
_length = _reader.Read(_buffer);
_count = 0;
}
if (_length == 0)
{
c = char.MinValue;
return false;
}
c = _buffer[_count];
_count += 1;
return true;
}
}

View File

@@ -0,0 +1,33 @@
using CanonSharp.Common.Abstractions;
namespace CanonSharp.Common.Reader;
public class StringReader(string source) : ISourceReader
{
private int _pos;
public char Read()
{
if (_pos >= source.Length)
{
throw new InvalidOperationException();
}
char result = source[_pos];
_pos += 1;
return result;
}
public bool TryPeek(out char c)
{
if (_pos < source.Length)
{
c = source[_pos];
return true;
}
c = char.MinValue;
return false;
}
}