-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractLexer.cs
82 lines (80 loc) · 2.38 KB
/
AbstractLexer.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DummyCppCompiler
{
abstract class AbstractLexer
{
protected string Input;
protected int StringBegin;
protected int StringEnd;
protected LexerState State;
protected TokenType AcceptType;
protected string ER = "Error";
public List<Token> TokensList = new List<Token>();
public void initialize(string InputFromInitialization)
{
Input = InputFromInitialization;
StringBegin = StringEnd = 0;
State = LexerState.Ready;
}
public Token NextToken()
{
State = LexerState.Ready;
char c;
while (StringEnd != Input.Length)
{
c = read();
switchState(c);
if (State == LexerState.Accepted)
{
Token T = Accept(AcceptType);
if (T.Type != TokenType.Token_SKIP)
return T;
}
}
if (State == LexerState.Ready)
{
Token T = new Token();
T.Lexeme = "";
return T;
}
else
throw new LexerException("End of file reached");
}
protected abstract LexerState switchState(char c);
protected void Retract()
{
--StringEnd;
}
protected void Reset()
{
StringEnd = StringBegin;
}
protected char read()
{
char c = Input[StringEnd];
StringEnd++;
return c;
}
protected Token Accept(TokenType Type)
{
string Lexeme = Input.Substring(StringBegin, StringEnd - StringBegin);
StringBegin = StringEnd;
Token Temp = new Token();
Temp.Lexeme = Lexeme;
Temp.Type = Type;
State = LexerState.Ready;
if (Temp.Lexeme == "if" || Temp.Lexeme == "while" || Temp.Lexeme == "\r\nif" || Temp.Lexeme == "\r\nwhile")
Temp.Type = TokenType.Token_RESERVEDWORD;
TokensList.Add(Temp);
return Temp;
}
protected void Error(string Message)
{
throw new LexerException(Message);
}
}
}