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
use std::io;
use std::iter::Peekable;
use source_span::{
	Position,
	Span,
	Metrics
};
use crate::Located;
use super::{token, Token, Result, Error};

pub struct Lexer<R: Iterator<Item=io::Result<char>>, M: Metrics> {
	decoder: Peekable<R>,
	location: Span,
	metrics: M
}

fn is_separator(c: char) -> bool {
	c == '.' || c == ';' || c == ':' || c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == ','
}

impl<R: Iterator<Item = io::Result<char>>, M: Metrics> Lexer<R, M> {
	pub fn new(source: R, cursor: Position, metrics: M) -> Lexer<R, M> {
		Lexer {
			decoder: source.peekable(),
			location: cursor.into(),
			//buffer: Buffer::new(cursor),
			metrics
		}
	}

	pub fn location(&self) -> Span {
		self.location
	}

	/**
	 * Update the lexer location.
	 */
	pub fn set_location(&mut self, location: Span) {
		self.location = location
	}

	fn peek_char(&mut self) -> Result<Option<char>> {
		match self.decoder.peek() {
			Some(Ok(c)) => {
				// eprintln!("peeking: {}", c);
				Ok(Some(*c))
			},
			Some(Err(_)) => {
				Ok(Some(self.consume()?)) // this will always fail.
			},
			None => Ok(None)
		}
	}

	fn consume(&mut self) -> Result<char> {
		match self.decoder.next() {
			Some(Ok(c)) => {
				self.location.push(c, &self.metrics);
				Ok(c)
			},
			Some(Err(e)) => {
				self.location.clear();
				Err(Error::IO(e).at(self.location.clone()))
			},
			None => {
				self.location.clear();
				Err(Error::IO(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "unexpected enf of stream")).at(self.location.clone()))
			}
		}
	}

	fn skip_whitespaces(&mut self) -> Result<()> {
		loop {
			match self.peek_char()? {
				Some(';') => self.skip_line()?,
				Some('\n') => {
					self.consume()?;
				}
				Some(c) if c.is_whitespace() => {
					self.consume()?;
				},
				_ => break
			}
		}

		Ok(())
	}

	/**
	 * Skip all chars until the next line break.
	 */
	fn skip_line(&mut self) -> Result<()> {
		loop {
			match self.peek_char()? {
				Some('\n') => {
					self.consume()?;
					break
				}
				_ => {
					self.consume()?;
				}
			}
		}

		Ok(())
	}

	fn read_ident(&mut self) -> Result<Located<Token>> {
		let mut name = String::new();
		name.push(self.consume()?);

		loop {
			match self.peek_char()? {
				Some(c) if !c.is_whitespace() && !is_separator(c) => {
					name.push(self.consume()?);
				},
				_ => break
			}
		}

		let location = self.location;
		self.location.clear();

		Ok(Token::Ident(name.to_string()).at(location))
	}

	fn read_string(&mut self) -> Result<Located<Token>> {
		let mut string = String::new();

		let mut escape = false;
		loop {
			if escape {
				match self.consume()? {
					'n' => string.push('\n'),
					c => string.push(c)
				}
				escape = false;
			} else {
				match self.consume()? {
					'\\' => {
						escape = true;
					},
					'"' => {
						break
					},
					c => {
						string.push(c)
					}
				}
			}
		}

		let location = self.location;
		self.location.clear();

		Ok(Token::Litteral(token::Litteral::String(string)).at(location))
	}

	// fn read_numeric(&mut self, radix: u32, positive: bool) -> Result<Located<Token>> {
	// 	let mut value = 0;
	// 	let f = radix as i64;
	//
	// 	loop {
	// 		match self.peek_char()? {
	// 			Some(c) if c.is_digit(radix) => {
	// 				self.consume()?;
	// 				value = value * f + c.to_digit(radix).unwrap() as i64;
	// 			},
	// 			_ => break
	// 		}
	// 	}
	//
	// 	if !positive {
	// 		value = -value;
	// 	}
	//
	// 	let location = self.location;
	// 	self.location.clear();
	//
	// 	Ok(Token::Litteral(token::Litteral::Int(value)).at(location))
	// }

	fn read_token(&mut self) -> Result<Option<Located<Token>>> {
		self.skip_whitespaces()?;
		self.location.clear();
		match self.peek_char()? {
			Some(c) => {
				match c {
					'(' => {
						self.consume()?;
						let location = self.location;
						self.location.clear();
						Ok(Some(Token::Begin.at(location)))
					},

					')' => {
						self.consume()?;
						let location = self.location;
						self.location.clear();
						Ok(Some(Token::End.at(location)))
					},

					'"' => {
						self.consume()?;
						Ok(Some(self.read_string()?))
					}

					// '-' => {
					// 	self.consume()?;
					// 	match self.peek_char()? {
					// 		Some(c) if c.is_digit(10) => {
					// 			Ok(Some(self.read_numeric(10, false)?))
					// 		},
					// 		_ => { // the ident "-"
					// 			let location = self.location.clone();
					// 			self.location.clear();
					// 			Ok(Some(Token::Ident("-".to_string()).at(location)))
					// 		}
					// 	}
					// },

					// c if c.is_digit(10) => {
					// 	Ok(Some(self.read_numeric(10, true)?))
					// },

					_ => {
						Ok(Some(self.read_ident()?))
					}
				}
			},
			None => Ok(None)
		}
	}
}

impl<R: Iterator<Item = io::Result<char>>, M: Metrics> Iterator for Lexer<R, M> {
	type Item = Result<Located<Token>>;

	fn next(&mut self) -> Option<Result<Located<Token>>> {
		self.read_token().transpose()
	}
}