-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexer.cs
More file actions
97 lines (88 loc) · 2.97 KB
/
Lexer.cs
File metadata and controls
97 lines (88 loc) · 2.97 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
using System;
using System.Collections.Generic;
namespace expr
{
class Lexer
{
private InputStream stream;
public Lexer(string code)
{
this.stream = new InputStream(code);
}
public List<Token> Tokenize()
{
List<Token> tokens = new List<Token>();
while(!this.stream.End()) {
char character = this.stream.Next();
if(Char.IsDigit(character)) {
string value = character.ToString();
// if(!this.stream.End()) {
do {
char next = this.stream.Next();
if(Char.IsDigit(next)) {
value += next;
}
} while (!this.stream.End() && Char.IsDigit(this.stream.Peek()));
// }
tokens.Add(new Token(TokenType.OPERAND, value));
} else {
switch(character) {
case '+':
tokens.Add(new Token(TokenType.OPERATOR, character.ToString(), OperatorsType.PLUS));
break;
case '-':
tokens.Add(new Token(TokenType.OPERATOR, character.ToString(), OperatorsType.MINUS));
break;
case '/':
tokens.Add(new Token(TokenType.OPERATOR, character.ToString(), OperatorsType.DIVIDE));
break;
case '*':
tokens.Add(new Token(TokenType.OPERATOR, character.ToString(), OperatorsType.MULTIPLY));
break;
case ' ':
break;
default:
throw new Exception("Unknown operator: " + character);
}
}
}
return tokens;
}
}
class InputStream
{
private string code;
private int position;
public InputStream(string code)
{
this.code = code;
this.position = 0;
}
public char Next()
{
return this.code[this.position++];
}
public char Peek()
{
return this.code[this.position];
}
public bool End()
{
return this.position == this.code.Length;
}
}
class Token
{
public TokenType Type { get; }
public OperatorsType Operator { get; }
public string Value { get; }
public Token(TokenType type, string value, OperatorsType op = OperatorsType.NONE)
{
this.Type = type;
this.Value = value;
this.Operator = op;
}
}
public enum OperatorsType { NONE, PLUS, MINUS, DIVIDE, MULTIPLY }
public enum TokenType { OPERATOR, OPERAND }
}