]> Witch of Git - ess/blob - src/lib.rs
Merge pull request #1 from porglezomp/locations
[ess] / src / lib.rs
1 //! A lightweight S-expression parser intended for language implementation.
2
3 // #![warn(missing_docs)]
4 #![deny(unsafe_code)]
5
6 use std::borrow::Cow;
7
8 /// A type representing arbitrary symbolic expressions. `Sexp` carries the
9 /// source code location it came from along with it for later diagnostic
10 /// purposes.
11 #[derive(Debug, PartialEq, Clone, PartialOrd)]
12 pub enum Sexp<'a, Loc=ByteSpan> where Loc: Span {
13 /// A value representing a symbol.
14 Sym(Cow<'a, str>, Loc),
15 /// A value representing a string literal.
16 Str(Cow<'a, str>, Loc),
17 /// A value representing a single character.
18 Char(char, Loc),
19 /// A value representing an integer. Any number containing no decimal point
20 /// will be parsed as an `Int`.
21 Int(i64, Loc),
22 /// A value representing a floating point number. Any number containing a
23 /// decimal point will be parsed as a `Float`.
24 Float(f64, Loc),
25 /// A list of subexpressions.
26 List(Vec<Sexp<'a, Loc>>, Loc),
27 }
28
29 impl<'a, Loc> Sexp<'a, Loc> where Loc: Span {
30 pub fn get_loc(&self) -> &Loc {
31 match *self {
32 Sexp::Sym(.., ref l) | Sexp::Str(.., ref l) |
33 Sexp::Char(.., ref l) | Sexp::Int(.., ref l) |
34 Sexp::Float(.., ref l) | Sexp::List(.., ref l) => l,
35 }
36 }
37
38 pub fn get_loc_mut(&mut self) -> &mut Loc {
39 match *self {
40 Sexp::Sym(.., ref mut l) | Sexp::Str(.., ref mut l) |
41 Sexp::Char(.., ref mut l) | Sexp::Int(.., ref mut l) |
42 Sexp::Float(.., ref mut l) | Sexp::List(.., ref mut l) => l,
43 }
44 }
45 }
46
47 \f
48 // General Parsing Types ///////////////////////////////////////////////////////
49
50 pub trait Span {
51 type Begin;
52
53 fn offset(&self, begin: Self::Begin) -> Self;
54 fn begin(&self) -> Self::Begin;
55 fn union(&self, other: &Self) -> Self;
56 }
57
58 #[derive(Debug, PartialEq, Eq, Clone)]
59 pub enum ParseResult<'a, T, E> {
60 Done(&'a str, T),
61 Error(E),
62 }
63
64 use ParseResult::*;
65
66 \f
67 // Specific Parsing Types (ParseError, ByteSpan) ///////////////////////////////
68
69 /// Indicates how parsing failed.
70 #[derive(Debug, PartialEq, Eq, Clone)]
71 pub enum ParseError<Loc=ByteSpan> where Loc: Span {
72 UnexpectedEof,
73 List(Box<ParseError>, Loc),
74 Sexp(Box<ParseError>, Loc),
75 Char(Box<ParseError>, Loc),
76 String(Box<ParseError>, Loc),
77 Symbol(Box<ParseError>, Loc),
78 Number(Box<ParseError>, Loc),
79 Unexpected(char, Loc::Begin),
80 Unimplemented,
81 }
82
83 type ByteSpan = (usize, usize);
84
85 impl Span for ByteSpan {
86 type Begin = usize;
87
88 fn offset(&self, begin: Self::Begin) -> Self {
89 (self.0 + begin, self.1 + begin)
90 }
91
92 fn begin(&self) -> Self::Begin {
93 self.0
94 }
95
96 fn union(&self, other: &Self) -> Self {
97 use std::cmp::{min, max};
98 (min(self.0, other.0), max(self.1, other.1))
99 }
100 }
101
102
103 \f
104 // Parsing Utilities ///////////////////////////////////////////////////////////
105
106 trait IsDelimeter {
107 fn is_delimiter(&self) -> bool;
108 }
109
110 impl IsDelimeter for char {
111 fn is_delimiter(&self) -> bool {
112 self.is_whitespace() || *self == ';'
113 || *self == '(' || *self == ')'
114 || *self == '[' || *self == ']'
115 || *self == '{' || *self == '}'
116 || *self == '"' || *self == '\''
117 || *self == '`' || *self == ','
118 }
119 }
120
121 macro_rules! consume_whitespace {
122 ($input:expr, $start_loc:expr, $ErrorFn:expr) => {
123 if let Some(pos) = $input.find(|c: char| !c.is_whitespace()) {
124 (&$input[pos..], $start_loc + pos)
125 } else {
126 return Error($ErrorFn(
127 Box::new(ParseError::UnexpectedEof),
128 ($input.len(), $input.len()).offset($start_loc)));
129 }
130 }
131 }
132
133 \f
134 // Top Level Parsers ///////////////////////////////////////////////////////////
135
136 pub fn parse_one(input: &str) -> Result<(Sexp, &str), ParseError> {
137 match parse_sexp(input, 0) {
138 Done(rest, result) => Ok((result, rest)),
139 Error(err) => Err(err),
140 }
141 }
142
143 pub fn parse(mut input: &str) -> (Vec<Sexp>, Option<ParseError>) {
144 let mut start_loc = 0;
145 let mut results = Vec::new();
146 loop {
147 match parse_sexp(input, start_loc) {
148 Done(rest, result) => {
149 input = rest;
150 start_loc = result.get_loc().1;
151 results.push(result);
152 if rest.trim() == "" {
153 return (results, None);
154 }
155 }
156 Error(err) => {
157 return (results, Some(err));
158 }
159 }
160 }
161 }
162
163 \f
164 // Core Parsers ////////////////////////////////////////////////////////////////
165
166 pub fn parse_sexp(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
167 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Sexp);
168
169 match input.chars().next() {
170 Some('0'...'9') => parse_number(input, start_loc),
171 Some('(') => parse_list(input, start_loc),
172 Some('#') => parse_character(input, start_loc),
173 Some('"') => parse_string(input, start_loc),
174 Some(_) => parse_symbol(input, start_loc),
175 None => unreachable!(),
176 }
177 }
178
179 pub fn parse_list(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
180 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::List);
181
182 match input.chars().nth(0) {
183 Some('(') => (),
184 Some(c) =>
185 return Error(ParseError::List(
186 Box::new(ParseError::Unexpected(c, 0)),
187 (0, 0).offset(start_loc))),
188 None => unreachable!(),
189 }
190
191 let mut input = &input[1..];
192 let mut loc = start_loc + 1;
193 let mut members = Vec::new();
194 loop {
195 {
196 let (new_input, new_loc) = consume_whitespace!(input, loc, ParseError::List);
197 input = new_input;
198 loc = new_loc;
199 }
200
201 match input.chars().nth(0) {
202 Some(')') =>
203 return Done(&input[1..],
204 Sexp::List(members, (start_loc, loc+1))),
205 Some(_) => (),
206 None => unreachable!(),
207 }
208
209 match parse_sexp(input, loc) {
210 Done(new_input, member) => {
211 loc = member.get_loc().1;
212 members.push(member);
213 input = new_input;
214 }
215 Error(err) =>
216 return Error(ParseError::List(
217 Box::new(err),
218 (0, 0).offset(loc)))
219 }
220 }
221 }
222
223 pub fn parse_number(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
224 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Number);
225
226 match input.chars().next() {
227 Some(c) if !c.is_digit(10) => {
228 return Error(ParseError::Number(
229 Box::new(ParseError::Unexpected(c, start_loc)),
230 (0, c.len_utf8()).offset(start_loc)));
231 }
232 None => return Error(ParseError::Number(
233 Box::new(ParseError::UnexpectedEof),
234 (0, 0).offset(start_loc))),
235 _ => (),
236 }
237
238 let base = 10;
239
240 let mut end = 0;
241 // Before the decimal point
242 for (i, c) in input.char_indices() {
243 if c == '.' {
244 end = i + 1;
245 break;
246 }
247
248 if c.is_delimiter() {
249 return Done(&input[i..],
250 Sexp::Int(input[..i].parse().expect("Already matched digits"),
251 (0, i).offset(start_loc)));
252 }
253
254 if !c.is_digit(base) {
255 return Error(ParseError::Number(
256 Box::new(ParseError::Unexpected(c, start_loc + i)),
257 (i, i).offset(start_loc)));
258 }
259
260 end = i + c.len_utf8();
261 }
262
263 if input[end..].is_empty() {
264 return Done(&input[end..],
265 Sexp::Int(input.parse().expect("Already matched digits"),
266 (0, end).offset(start_loc)));
267 }
268
269 // After the decimal point
270 for (i, c) in input[end..].char_indices() {
271 if c.is_delimiter() {
272 return Done(&input[i+end..],
273 Sexp::Float(input[..end+i].parse().expect("Already matched digits.digits"),
274 (0, end+i).offset(start_loc)));
275 }
276
277 if !c.is_digit(base) {
278 return Error(ParseError::Number(
279 Box::new(ParseError::Unexpected(c, start_loc + i + end)),
280 (i+end, i+end).offset(start_loc)));
281 }
282 }
283
284 Done(&input[input.len()..],
285 Sexp::Float(input.parse().expect("Already matched digits.digits"),
286 (0, input.len()).offset(start_loc)))
287 }
288
289 pub fn parse_symbol(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
290 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Symbol);
291
292 match input.chars().next() {
293 Some(c@'#') | Some(c@':') | Some(c@'0'...'9') =>
294 return Error(ParseError::Symbol(
295 Box::new(ParseError::Unexpected(c, start_loc)),
296 (0, 0).offset(start_loc))),
297 Some(c) if c.is_delimiter() =>
298 return Error(ParseError::Symbol(
299 Box::new(ParseError::Unexpected(c, start_loc)),
300 (0, 0).offset(start_loc))),
301 Some(_) => (),
302 None => unreachable!(),
303 }
304
305 for (i, c) in input.char_indices() {
306 if c.is_delimiter() {
307 return Done(&input[i..],
308 Sexp::Sym(input[..i].into(), (0, i).offset(start_loc)));
309 }
310 }
311
312 Done(&input[input.len()..],
313 Sexp::Sym(input.into(), (0, input.len()).offset(start_loc)))
314 }
315
316 pub fn parse_string(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
317 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::String);
318
319 match input.chars().next() {
320 Some('"') => (),
321 Some(c) =>
322 return Error(ParseError::String(
323 Box::new(ParseError::Unexpected(c, start_loc)),
324 (0, 0).offset(start_loc))),
325 None => unreachable!(),
326 }
327
328 for (i, c) in input[1..].char_indices() {
329 if c == '"' {
330 return Done(&input[2+i..],
331 Sexp::Str(input[1..i+1].into(), (0, i+2).offset(start_loc)));
332 }
333 }
334
335 Error(ParseError::String(
336 Box::new(ParseError::UnexpectedEof),
337 (0, input.len()).offset(start_loc)))
338 }
339
340 pub fn parse_character(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
341 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Char);
342
343 match input.chars().nth(0) {
344 Some('#') => (),
345 Some(c) =>
346 return Error(ParseError::Char(
347 Box::new(ParseError::Unexpected(c, start_loc)),
348 (0, 0).offset(start_loc))),
349 None =>
350 return Error(ParseError::Char(
351 Box::new(ParseError::UnexpectedEof),
352 (0, 0).offset(start_loc))),
353 }
354
355 match input.chars().nth(1) {
356 Some('\\') => (),
357 Some(c) =>
358 return Error(ParseError::Char(
359 Box::new(ParseError::Unexpected(c, start_loc + 1)),
360 (1, 1).offset(start_loc))),
361 None =>
362 return Error(ParseError::Char(
363 Box::new(ParseError::UnexpectedEof),
364 (1, 1).offset(start_loc)))
365 }
366
367 match input.chars().nth(2) {
368 Some(c) =>
369 Done(&input[3..], Sexp::Char(c, (0, 3).offset(start_loc))),
370 None =>
371 Error(ParseError::Char(
372 Box::new(ParseError::UnexpectedEof),
373 (2, 2).offset(start_loc)))
374 }
375 }
376
377 \f
378 // Tests ///////////////////////////////////////////////////////////////////////
379
380 #[cfg(test)]
381 mod test {
382 use super::*;
383 use super::ParseResult::*;
384
385 #[test]
386 fn test_parse() {
387 assert_eq!(parse("1 2 3"), (vec![
388 Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3)), Sexp::Int(3, (4, 5))
389 ], None));
390 assert_eq!(parse("1 2 )"), (vec![
391 Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3))
392 ], Some(ParseError::Symbol(Box::new(ParseError::Unexpected(')', 4)), (4, 4)))));
393 }
394
395 #[test]
396 fn test_parse_one() {
397 assert_eq!(parse_one("1 2"),
398 Ok((Sexp::Int(1, (0, 1)), " 2")));
399 }
400
401 #[test]
402 fn test_parse_sexp() {
403 assert_eq!(parse_sexp(" 1", 0),
404 Done("", Sexp::Int(1, (1, 2))));
405 assert_eq!(parse_sexp("2.2", 0),
406 Done("", Sexp::Float(2.2, (0, 3))));
407 assert_eq!(parse_sexp(" a", 0),
408 Done("", Sexp::Sym("a".into(), (1, 2))));
409 assert_eq!(parse_sexp("#\\c", 0),
410 Done("", Sexp::Char('c', (0, 3))));
411 assert_eq!(parse_sexp(r#""hi""#, 0),
412 Done("", Sexp::Str("hi".into(), (0, 4))));
413 assert_eq!(parse_sexp("()", 0),
414 Done("", Sexp::List(vec![], (0, 2))));
415 assert_eq!(parse_sexp("( 1 2 3 )", 0),
416 Done("", Sexp::List(vec![
417 Sexp::Int(1, (2, 3)),
418 Sexp::Int(2, (4, 5)),
419 Sexp::Int(3, (6, 7)),
420 ], (0, 9))));
421
422 assert_eq!(parse_sexp("", 0),
423 Error(ParseError::Sexp(Box::new(ParseError::UnexpectedEof), (0, 0))));
424 }
425
426 #[test]
427 fn test_parse_list() {
428 assert_eq!(parse_list("()", 0),
429 Done("", Sexp::List(vec![], (0, 2))));
430 assert_eq!(parse_list("(1)", 0),
431 Done("", Sexp::List(vec![Sexp::Int(1, (1, 2))], (0, 3))));
432 assert_eq!(parse_list(" ( 1 2 3 a )", 0), Done("", Sexp::List(vec![
433 Sexp::Int(1, (4, 5)),
434 Sexp::Int(2, (9, 10)),
435 Sexp::Int(3, (12, 13)),
436 Sexp::Sym("a".into(), (14, 15)),
437 ], (2, 17))));
438 }
439
440 #[test]
441 fn test_parse_number() {
442 assert_eq!(parse_number("1", 0),
443 Done("", Sexp::Int(1, (0, 1))));
444 assert_eq!(parse_number(" 13", 0),
445 Done("", Sexp::Int(13, (1, 3))));
446 assert_eq!(parse_number("1.2", 0),
447 Done("", Sexp::Float(1.2, (0, 3))));
448 assert_eq!(parse_number("\u{3000}4.2", 0),
449 Done("", Sexp::Float(4.2, (0, 3).offset('\u{3000}'.len_utf8()))));
450 assert_eq!(parse_number(" 42 ", 0),
451 Done(" ", Sexp::Int(42, (2, 4))));
452 assert_eq!(parse_number(" 4.2 ", 0),
453 Done(" ", Sexp::Float(4.2, (1, 4))));
454 assert_eq!(parse_number("1()", 0),
455 Done("()", Sexp::Int(1, (0, 1))));
456 assert_eq!(parse_number("3.6()", 0),
457 Done("()", Sexp::Float(3.6, (0, 3))));
458
459 assert_eq!(parse_number("", 0),
460 Error(ParseError::Number(Box::new(ParseError::UnexpectedEof), (0, 0))));
461 assert_eq!(parse_number("123a", 0),
462 Error(ParseError::Number(Box::new(ParseError::Unexpected('a', 3)), (3, 3))));
463 assert_eq!(parse_number("66.6+", 0),
464 Error(ParseError::Number(Box::new(ParseError::Unexpected('+', 4)), (4, 4))));
465 }
466
467 #[test]
468 fn test_parse_ident() {
469 assert_eq!(parse_symbol("+", 0),
470 Done("", Sexp::Sym("+".into(), (0, 1))));
471 assert_eq!(parse_symbol(" nil?", 0),
472 Done("", Sexp::Sym("nil?".into(), (1, 5))));
473 assert_eq!(parse_symbol(" ->socket", 0),
474 Done("", Sexp::Sym("->socket".into(), (1, 9))));
475 assert_eq!(parse_symbol("fib(", 0),
476 Done("(", Sexp::Sym("fib".into(), (0, 3))));
477 assert_eq!(parse_symbol("foo2", 0),
478 Done("", Sexp::Sym("foo2".into(), (0, 4))));
479
480 // We reserve #foo for the implementation to do as it wishes
481 assert_eq!(parse_symbol("#hi", 0),
482 Error(ParseError::Symbol(Box::new(ParseError::Unexpected('#', 0)), (0, 0))));
483 // We reserve :foo for keywords
484 assert_eq!(parse_symbol(":hi", 0),
485 Error(ParseError::Symbol(Box::new(ParseError::Unexpected(':', 0)), (0, 0))));
486
487 assert_eq!(parse_symbol("", 0),
488 Error(ParseError::Symbol(Box::new(ParseError::UnexpectedEof), (0, 0))));
489 assert_eq!(parse_symbol("0", 0),
490 Error(ParseError::Symbol(Box::new(ParseError::Unexpected('0', 0)), (0, 0))));
491 assert_eq!(parse_symbol("()", 0),
492 Error(ParseError::Symbol(Box::new(ParseError::Unexpected('(', 0)), (0, 0))));
493 }
494
495 #[test]
496 fn test_parse_string() {
497 assert_eq!(parse_string(r#""""#, 0),
498 Done("", Sexp::Str("".into(), (0, 2))));
499 assert_eq!(parse_string(r#""hello""#, 0),
500 Done("", Sexp::Str("hello".into(), (0, 7))));
501 assert_eq!(parse_string(r#" "this is a nice string
502 with 0123 things in it""#, 0),
503 Done("", Sexp::Str("this is a nice string\nwith 0123 things in it".into(), (2, 48))));
504
505 assert_eq!(parse_string("", 0),
506 Error(ParseError::String(Box::new(ParseError::UnexpectedEof), (0, 0))));
507 assert_eq!(parse_string(r#""hi"#, 0),
508 Error(ParseError::String(Box::new(ParseError::UnexpectedEof), (0, 3))));
509 }
510
511 #[test]
512 fn test_parse_char() {
513 assert_eq!(parse_character(r#"#\""#, 0), Done("", Sexp::Char('"', (0, 3))));
514 assert_eq!(parse_character(r#"#\ "#, 0), Done("", Sexp::Char(' ', (0, 3))));
515 assert_eq!(parse_character(r#" #\\"#, 0), Done("", Sexp::Char('\\', (2, 5))));
516
517 assert_eq!(parse_character("", 0),
518 Error(ParseError::Char(Box::new(ParseError::UnexpectedEof), (0, 0))));
519 assert_eq!(parse_character("#", 0),
520 Error(ParseError::Char(Box::new(ParseError::UnexpectedEof), (1, 1))));
521 assert_eq!(parse_character("#\\", 0),
522 Error(ParseError::Char(Box::new(ParseError::UnexpectedEof), (2, 2))));
523 assert_eq!(parse_character("a", 0),
524 Error(ParseError::Char(Box::new(ParseError::Unexpected('a', 0)), (0, 0))));
525 }
526 }