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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
use crate::error::{Error, ErrorType, Located, Position};
use crate::tokens::Token;
#[derive(Debug, Clone, PartialEq)]
pub struct Line {
pub ln: usize,
pub tokens: Vec<Located<Token>>,
pub indent: usize,
}
impl Line {
pub fn len(&self) -> usize {
self.tokens.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn pop(&mut self) -> Option<Located<Token>> {
self.tokens.pop()
}
pub fn remove(&mut self, idx: usize) -> Located<Token> {
self.tokens.remove(idx)
}
}
pub struct Lexer {
pub lines: Vec<String>,
pub symbols: Vec<String>,
pub keywords: Vec<String>,
pub idx: usize,
pub ln: usize,
pub col: usize,
}
impl Lexer {
pub fn new(text: String) -> Self {
Self {
lines: text.split('\n').map(|s| s.to_string()).collect(),
symbols: vec![],
keywords: vec![],
idx: 0,
ln: 0,
col: 0,
}
}
pub fn pos(&self) -> Position {
Position {
idx: self.idx..self.idx + 1,
ln: self.ln..self.ln + 1,
col: self.col..self.col + 1,
}
}
pub fn advance(&mut self) {
self.idx += 1;
self.col += 1;
}
pub fn advance_line(&mut self) {
self.idx += 1;
self.ln += 1;
self.col = 0;
}
pub fn get(&self) -> Option<char> {
self.lines.get(self.ln).and_then(|line| {
line.get(self.col..self.col + 1)
.and_then(|s| s.chars().next())
})
}
pub fn next_char(&mut self) -> Option<char> {
let c = self.get();
self.advance();
c
}
pub fn has_symbols(&self) -> bool {
!self.symbols.is_empty()
}
pub fn symbols(mut self, symbols: &[&str]) -> Self {
self.symbols = symbols.iter().map(|symbol| symbol.to_string()).collect();
self
}
pub fn keywords(mut self, keywords: &[&str]) -> Self {
self.keywords = keywords.iter().map(|symbol| symbol.to_string()).collect();
self
}
pub fn lex(&mut self) -> Result<Vec<Line>, Error> {
let mut lines = vec![];
while self.ln < self.lines.len() {
let mut indent = 0;
while let Some(' ' | '\t') = self.get() {
self.advance();
indent += 1;
}
let mut tokens = vec![];
while let Some(c) = self.get() {
let mut pos = self.pos();
match c {
' ' | '\t' | '\r' => {
self.advance();
}
'0'..='9' => {
let mut num = self.next_char().unwrap().to_string();
while let Some('0'..='9') = self.get() {
pos.extend(&self.pos());
num.push(self.next_char().unwrap());
}
if let Some('.') = self.get() {
pos.extend(&self.pos());
num.push(self.next_char().unwrap());
while let Some('0'..='9') = self.get() {
num.push(self.next_char().unwrap());
pos.extend(&self.pos());
}
tokens.push(Located::new(Token::Float(num.parse().unwrap()), pos));
} else {
tokens.push(Located::new(Token::Int(num.parse().unwrap()), pos));
}
}
'a'..='z' | 'A'..='Z' | '_' => {
let mut ident = self.next_char().unwrap().to_string();
while let Some('a'..='z') | Some('A'..='Z') | Some('_') | Some('0'..='9') =
self.get()
{
pos.extend(&self.pos());
ident.push(self.next_char().unwrap());
}
tokens.push(Located::new(
if self.keywords.contains(&ident) {
Token::Keyword(ident)
} else {
Token::Ident(ident)
},
pos,
));
}
'\'' => {
self.advance();
let mut c = self.next_char().unwrap();
if c == '\\' {
c = match self.next_char().unwrap() {
'n' => '\n',
't' => '\t',
'r' => '\r',
'\\' => '\\',
'\'' => '\'',
_ => return Err(Error::new(ErrorType::BadChar(c), pos)),
}
}
pos.extend(&self.pos());
if self.next_char().unwrap() != '\'' {
return Err(Error::new(ErrorType::BadChar(c), pos));
}
tokens.push(Located::new(Token::Char(c), pos));
}
'"' => {
self.advance();
let mut string = String::new();
while let Some(c) = self.get() {
if c == '"' {
break;
}
let c = self.next_char().unwrap();
if c == '\\' {
let c = match self.next_char().unwrap() {
'n' => '\n',
't' => '\t',
'r' => '\r',
'\\' => '\\',
'"' => '"',
_ => return Err(Error::new(ErrorType::BadChar(c), pos)),
};
string.push(c);
} else {
string.push(c);
}
}
if let Some('"') = self.get() {
pos.extend(&self.pos());
self.advance();
tokens.push(Located::new(Token::String(string), pos));
} else {
return Err(Error::new(ErrorType::UnclosedString, pos));
}
}
_ => {
if self.has_symbols() {
let mut symbol = self.next_char().unwrap().to_string();
while self.get().is_some() {
let matches = self
.symbols
.iter()
.filter(|s| *s == &symbol || s.starts_with(&symbol))
.count();
if matches == 0 {
symbol.pop();
break;
} else if matches == 1 {
break;
} else {
symbol.push(self.next_char().unwrap());
pos.extend(&self.pos());
}
}
if self.symbols.iter().any(|s| s == &symbol) {
if symbol.len() == 1 {
tokens.push(Located::new(
Token::Symbol(symbol.chars().next().unwrap()),
pos,
));
} else {
tokens.push(Located::new(Token::LongSymbol(symbol), pos));
}
} else {
return Err(Error::new(ErrorType::InvalidSymbol(symbol), pos));
}
} else {
let c = self.next_char().unwrap();
tokens.push(Located::new(Token::Symbol(c), pos));
}
}
}
}
lines.push(Line {
ln: self.ln,
tokens,
indent,
});
self.advance_line();
}
Ok(lines)
}
}