-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.rs
304 lines (261 loc) · 9.11 KB
/
scanner.rs
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
use std::str::Chars;
use peekmore::{PeekMore, PeekMoreIterator};
use crate::token::{Token, Type, Location};
use crate::literal::Literal;
use crate::error::{Error, ScanError};
pub struct Scanner<'a> {
source: PeekMoreIterator<Chars<'a>>,
tokens: Vec<Token>,
start: usize,
current: usize,
line: usize,
column_offset: usize,
}
impl<'a> Scanner<'a> {
/// Creates a new scanner.
pub fn new(source: &'a str) -> Scanner<'a> {
Scanner {
source: source.chars().peekmore(),
tokens: vec!(),
start: 0,
current: 0,
line: 0,
column_offset: 0
}
}
/// Scans the source code and returns a vector of tokens.
pub fn scan_tokens(&mut self) -> Vec<Token> {
while !self.is_at_end() {
self.start = self.current;
self.scan_token();
}
self.tokens.push(
Token::new(
Type::EOF,
String::from(""),
None,
Location::new(self.line, 0)
)
);
self.tokens.clone()
}
/// Returns the next character.
fn advance(&mut self) -> char {
match self.source.next() {
Some(char) => {
self.current += 1;
char
},
None => panic!("tried to advance past end of the file."),
}
}
/// Returns the next character without consuming it.
fn peek(&mut self) -> &char {
match self.source.peek() {
Some(char) => char,
None => panic!("tried to peek past end of the file."),
}
}
/// Returns the next next character without consuming it.
fn peek_next(&mut self) -> &char {
match self.source.peek_next() {
Some(char) => char,
None => panic!("tried to peek next past end of the file."),
}
}
/// Returns if the next character is the expected character.
fn match_next(&mut self, expected: char) -> bool {
match self.source.peek_next() {
Some(char) if *char == expected => true,
Some(_) => false,
None => false,
}
}
/// Adds a new token to the list of tokens.
fn add_token(&mut self, r#type: Type, lexeme: String, literal: Option<Literal>) {
self.tokens.push(
Token::new(
r#type,
lexeme,
literal,
Location::new(self.line, self.start - self.column_offset)
)
);
}
/// Adds a new single char token to the list of tokens.
fn add_single_char_token(&mut self, r#type: Type) {
let c = self.advance();
self.add_token(r#type, c.to_string(), None);
}
/// Adds a new double char token to the list of tokens.
fn add_double_char_token(&mut self, r#type: Type) {
let first = self.advance();
let second = self.advance();
self.add_token(r#type, format!("{first}{second}"), None);
}
/// Returns if the scanner has reached the end of the file.
fn is_at_end(&mut self) -> bool {
self.source.peek().is_none()
}
/// Handles a string literal.
fn string(&mut self) {
self.advance(); // Move past the starting double quotes.
let start = (self.line, self.start - self.column_offset);
let mut value = Vec::new();
while !self.is_at_end() {
match self.source.next_if(|&x| x != '"') {
Some(c) => {
self.current += 1;
value.push(c);
if c == '\n' {
self.line += 1;
}
},
None => { break; },
}
}
if self.is_at_end() {
ScanError {
location: Location::new(start.0, start.1),
message: String::from("Unterminated string"),
}.throw();
return;
}
self.advance(); // Move to the closing double quotes.
let value: String = value.into_iter().collect();
// Literal does not include the double quotes unlike the lexeme.
self.add_token(Type::String, value.clone(), Some(Literal::String(value)));
}
/// Handles a number literal.
fn number(&mut self) {
let mut value = Vec::new();
while self.peek().is_ascii_digit() {
value.push(self.advance());
}
if *self.peek() == '.' {
if self.peek_next().is_ascii_digit() {
value.push(self.advance()); // Consume the dot.
while self.peek().is_ascii_digit() {
value.push(self.advance());
}
} else {
ScanError {
location: Location::new(self.line, self.start - self.column_offset),
message: String::from("Unterminated number"),
}.throw();
return;
}
}
let value: String = value.into_iter().collect();
let value_num: f64 = value.parse().unwrap();
self.add_token(Type::Number, value, Some(Literal::Number(value_num)));
}
/// Handles an identifier or a keyword.
fn identifier(&mut self) {
let mut value = Vec::new();
// is_alphanumeric does not include underscores.
while matches!(self.peek(), c if c.is_alphanumeric() || *c == '_') {
value.push(self.advance());
}
let value = String::from_iter(value);
let token_type = match value.as_str() {
"and" => Type::And,
"class" => Type::Class,
"else" => Type::Else,
"false" => Type::False,
"for" => Type::For,
"fun" => Type::Fun,
"if" => Type::If,
"null" => Type::Null,
"or" => Type::Or,
"print" => Type::Print,
"return" => Type::Return,
"break" => Type::Break,
"super" => Type::Super,
"this" => Type::This,
"true" => Type::True,
"var" => Type::Var,
"while" => Type::While,
_ => Type::Identifier,
};
self.add_token(token_type, value, None);
}
/// Scans the next token.
fn scan_token(&mut self) {
let c = *self.peek();
match c {
// One character tokens
'(' => self.add_single_char_token(Type::LeftParen),
')' => self.add_single_char_token(Type::RightParen),
'{' => self.add_single_char_token(Type::LeftBrace),
'}' => self.add_single_char_token(Type::RightBrace),
',' => self.add_single_char_token(Type::Comma),
'.' => self.add_single_char_token(Type::Dot),
'-' => self.add_single_char_token(Type::Minus),
'+' => self.add_single_char_token(Type::Plus),
';' => self.add_single_char_token(Type::Semicolon),
'*' => self.add_single_char_token(Type::Star),
// Two character tokens
'!' => {
if self.match_next('=') {
self.add_double_char_token(Type::BangEqual);
} else {
self.add_single_char_token(Type::Bang)
};
},
'=' => {
if self.match_next('=') {
self.add_double_char_token(Type::EqualEqual);
} else {
self.add_single_char_token(Type::Equal)
};
},
'<' => {
if self.match_next('=') {
self.add_double_char_token(Type::LessEqual);
} else {
self.add_single_char_token(Type::Less)
};
},
'>' => {
if self.match_next('=') {
self.add_double_char_token(Type::GreaterEqual);
} else {
self.add_single_char_token(Type::Greater)
};
},
'/' => {
if self.match_next('/') {
while *self.peek() != '\n' && !self.is_at_end() {
self.advance();
}
} else {
self.add_single_char_token(Type::Slash);
}
},
// Ignore whitespace
' ' | '\r' | '\t' => {
self.advance();
},
// Update line counter
'\n' => {
self.advance();
self.line += 1;
self.column_offset = self.current;
},
// String
'"' => self.string(),
// Numbers
c if c.is_ascii_digit() => self.number(),
// Identifiers
c if c.is_alphabetic() || c == '_' => self.identifier(),
_ => {
self.advance();
ScanError {
location: Location::new(self.line, self.start - self.column_offset),
message: format!("Unexpected character '{c}'"),
}.throw();
},
}
}
}