-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexer.cs
More file actions
106 lines (83 loc) · 2.39 KB
/
Lexer.cs
File metadata and controls
106 lines (83 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LexerParser
{
public class Lexer
{
private int _sourceLength;
private bool _hasMore;
private int _currentCursor = 0;
private List<Token> _tokens;
private char[] _chars;
public Lexer(char[] chars)
{
_chars = chars;
_sourceLength = chars.Length;
_currentCursor = 0;
_tokens = new List<Token>();
_hasMore = true;
}
public Token Consume()
{
LookaheadInternal(1);
if (_tokens.Count() == 0)
{
return Utility.EOL;
}
return _tokens.Remove();
}
public Token Lookahead(int i)
{
LookaheadInternal(i + 1);
if (i >= _tokens.Count())
{
return Utility.EOL;
}
return _tokens[i];
}
private void LookaheadInternal(int i)
{
while (_hasMore && _tokens.Count() < i)
{
AddToken();
}
}
private void AddToken()
{
if (_currentCursor >= _sourceLength)
{
_hasMore = false;
return;
}
while (char.IsWhiteSpace(_chars[_currentCursor]))
{
_currentCursor++;
}
Token token = null;
char lookaheadChar = _chars[_currentCursor];
if (Utility.IsDigit(lookaheadChar))
{
StringBuilder sb = new StringBuilder();
while (_currentCursor < _sourceLength && Utility.IsDigit(_chars[_currentCursor]))
{
sb.Append(_chars[_currentCursor++]);
}
token = new Token(sb.ToString(), TokenType.Number);
}
else if (Utility.IsOperator(lookaheadChar))
{
token = new Token(_chars[_currentCursor++], TokenType.Operator);
}
else if (Utility.IsParenthesis(lookaheadChar))
{
token = new Token(_chars[_currentCursor++], TokenType.Operator);
}
else
{
throw new LexerException("unknown token");
}
_tokens.Add(token);
}
}
}