-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScanner.cs
143 lines (122 loc) · 3.26 KB
/
Scanner.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace piaine
{
public class Scanner
{
List<Token> tokens;
string source;
int start;
int current;
int line;
public Scanner(string desSource)
{
tokens = new List<Token>();
source = desSource;
start = 0;
current = 0;
line = 0;
}
public void refreshSource(string desSource)
{
tokens = new List<Token>();
source = desSource;
start = 0;
current = 0;
line = 0;
}
public bool isAtEnd()
{
if (current >= source.Length)
{
return true;
}
else
{
return false;
}
}
public List<Token> scanTokens()
{
tokens = new List<Token>();
while(!isAtEnd())
{
start = current;
scanToken();
}
tokens.Add(new Token(TokenType.EndOfFile, "", null, line));
return tokens;
}
private void scanToken()
{
char nextCharacter = Advance();
switch(nextCharacter)
{
case '{': addToken(TokenType.LeftParenthesis); break;
case '}': addToken(TokenType.RightParenthesis); break;
case '!': variable(); break;
default:
if (tokens.Count > 0)
{
if (tokens[tokens.Count - 1].type != TokenType.LeftParenthesis)
{
notInScope();
}
}
else
{
notInScope();
}
break;
}
}
private void addToken(TokenType tokenToAdd)
{
addToken(tokenToAdd, null);
}
private void variable()
{
while (peek() != ' ' && !isAtEnd())
{
Advance();
}
Advance();
string value = subString(start + 1, current - 1);
addToken(TokenType.Variable, value);
}
private void notInScope()
{
while (peek() != '{' && !isAtEnd())
{
Advance();
}
string value = subString(start, current);
addToken(TokenType.Unscoped, value);
}
private void addToken(TokenType tokenToAdd, object desLiteral)
{
string text = subString(start, current);
tokens.Add(new Token(tokenToAdd, text, desLiteral, line));
}
private char Advance()
{
current++;
return source[current - 1];
}
private char peek()
{
if (current >= source.Length)
{
return '\0';
}
return source[current];
}
private string subString(int start, int end)
{
int length = end - start;
return source.Substring(start, length);
}
}
}