]> Witch of Git - ess/blob - src/parser.rs
Add documentation for Span
[ess] / src / parser.rs
1 //! Functions to parse s-expressions and expression atoms.
2 //!
3 //! This module contains the core parsing machinery.
4 //!
5 //! * If you're interested in getting a parsed s-expression that you can use,
6 //! then looking at [`parse`] and [`parse_one`] are your best bet.
7 //! * If you want to write your own parsers that contain s-expressions,
8 //! [`ParseResult`] and [`parse_expression`] will be the most useful to you.
9 //!
10 //! [`parse`]: fn.parse.html
11 //! [`parse_one`]: fn.parse_one.html
12 //! [`ParseResult`]: enum.ParseResult.html
13 //! [`parse_expression`]: fn.parse_expression.html
14
15 use sexp::Sexp;
16 use span::{Span, ByteSpan};
17
18 \f
19 // Parsing Types ///////////////////////////////////////////////////////////////
20
21 /// Represents what to do next in partially completed parsing.
22 ///
23 /// `ParseResult` is returned from all intermediate parsers. If you just want to
24 /// get back parsed s-expressions, you won't need to worry about this type since
25 /// the top level parsers just return a `Result`.
26 ///
27 /// If the parser failed to produce a result, it will return `Error`, and if it
28 /// succeeded we'll get the `Done` variant containing the value produced and the
29 /// rest of the text to work on.
30 #[derive(Debug, PartialEq, Eq, Clone)]
31 pub enum ParseResult<'a, T, E> {
32 /// The parser succeeded, this contains first the un-consumed portion of the
33 /// input then the result produced by parsing.
34 Done(&'a str, T),
35 /// The parser failed, the `E` represents the reason for the failure.
36 Error(E),
37 }
38
39 /// Indicates how parsing failed.
40 ///
41 /// Most `ParseError` variants contain a `Box<ParseError>` that represents the
42 /// cause of that error. Using this, `ParseError` variants can be chained to
43 /// produce a more complete picture of what exactly went wrong during parsing.
44 #[derive(Debug, PartialEq, Eq, Clone)]
45 pub enum ParseError<Loc=ByteSpan> where Loc: Span {
46 /// Parsing reached the end of input where not expecting to, usually this
47 /// will be contained inside another `ParseError` like `String(box
48 /// UnexpectedEof, ...)` which indicates that the closing quote was never
49 /// found.
50 UnexpectedEof,
51 /// Some problem occurred while parsing a list, along with the cause of that
52 /// error.
53 List(Box<ParseError>, Loc),
54 /// Some problem occurred while parsing an s-expression. This will only be
55 /// generated if EOF is reached unexpectedly at the beginning of
56 /// `parse_expression`, so it should probably be removed.
57 Sexp(Box<ParseError>, Loc),
58 /// Some problem occurred while parsing a character literal, along with the
59 /// cause of the error.
60 Char(Box<ParseError>, Loc),
61 /// Some problem occurred while parsing a string literal, along with the
62 /// cause of the error.
63 String(Box<ParseError>, Loc),
64 /// Some problem occurred while parsing a symbol, along with the cause of
65 /// the error.
66 Symbol(Box<ParseError>, Loc),
67 /// Some problem occurred while parsing a number literal, along with the
68 /// cause of the error.
69 Number(Box<ParseError>, Loc),
70 /// An unexpected character was found. This will usually be the root cause
71 /// in some chain of `ParseError`s.
72 Unexpected(char, Loc::Begin),
73 }
74 use self::ParseResult::*;
75
76 \f
77 // Parsing Utilities ///////////////////////////////////////////////////////////
78
79 trait IsDelimeter {
80 fn is_delimiter(&self) -> bool;
81 }
82
83 impl IsDelimeter for char {
84 fn is_delimiter(&self) -> bool {
85 self.is_whitespace() || *self == ';'
86 || *self == '(' || *self == ')'
87 || *self == '[' || *self == ']'
88 || *self == '{' || *self == '}'
89 || *self == '"' || *self == '\''
90 || *self == '`' || *self == ','
91 }
92 }
93
94 macro_rules! consume_whitespace {
95 ($input:expr, $start_loc:expr, $ErrorFn:expr) => {
96 if let Some(pos) = $input.find(|c: char| !c.is_whitespace()) {
97 (&$input[pos..], $start_loc + pos)
98 } else {
99 return Error($ErrorFn(
100 Box::new(ParseError::UnexpectedEof),
101 ($input.len(), $input.len()).offset($start_loc)));
102 }
103 }
104 }
105
106 \f
107 // Top Level Parsers ///////////////////////////////////////////////////////////
108
109 /// Parse a sequence of s-expressions.
110 ///
111 /// This function returns `(Vec<Sexp>, Option<ParseError>)` so that it can
112 /// return partial results, for when some component parses successfully and a
113 /// later part fails.
114 ///
115 /// # Errors
116 ///
117 /// If the text contains an invalid s-expression (imbalanced parenthesis,
118 /// quotes, invalid numbers like 123q, etc.) then the parser will stop and
119 /// return an error. Every s-expression before that point that successfully
120 /// parsed will still be returned.
121 ///
122 /// # Examples
123 ///
124 /// We can get useful partial results
125 ///
126 /// ```rust
127 /// # use ess::parser::parse;
128 /// let (exprs, err) = parse("1 2 3 ( 4");
129 /// assert_eq!(exprs.len(), 3);
130 /// assert!(err.is_some());
131 /// ```
132 pub fn parse(mut input: &str) -> (Vec<Sexp>, Option<ParseError>) {
133 let mut start_loc = 0;
134 let mut results = Vec::new();
135 loop {
136 match parse_expression(input, start_loc) {
137 Done(rest, result) => {
138 input = rest;
139 start_loc = result.get_loc().1;
140 results.push(result);
141 if rest.trim() == "" {
142 return (results, None);
143 }
144 }
145 Error(err) => {
146 return (results, Some(err));
147 }
148 }
149 }
150 }
151
152 /// Parses a single s-expression, ignoring any trailing text.
153 ///
154 /// This function returns a pair of the parsed s-expression and the tail of the text.
155 ///
156 /// # Errors
157 ///
158 /// If the text begins with an invalid s-expression (imbalanced parenthesis,
159 /// quotes, invalid numbers like 123q, etc.) then the parser will return an
160 /// error. Any text after the first s-expression doesn't affect the parsing.
161 ///
162 /// # Examples
163 ///
164 /// ```rust
165 /// # use ess::parser::parse_one;
166 /// let (expr, rest) = parse_one("1 (").unwrap();
167 /// assert_eq!(rest, " (");
168 /// ```
169 pub fn parse_one(input: &str) -> Result<(Sexp, &str), ParseError> {
170 match parse_expression(input, 0) {
171 Done(rest, result) => Ok((result, rest)),
172 Error(err) => Err(err),
173 }
174 }
175
176 \f
177 // Core Parsers ////////////////////////////////////////////////////////////////
178
179 pub fn parse_expression(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
180 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Sexp);
181
182 match input.chars().next() {
183 Some('0'...'9') => parse_number(input, start_loc),
184 Some('(') => parse_list(input, start_loc),
185 Some('#') => parse_character(input, start_loc),
186 Some('"') => parse_string(input, start_loc),
187 Some(_) => parse_symbol(input, start_loc),
188 None => unreachable!(),
189 }
190 }
191
192 pub fn parse_list(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
193 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::List);
194
195 match input.chars().nth(0) {
196 Some('(') => (),
197 Some(c) =>
198 return Error(ParseError::List(
199 Box::new(ParseError::Unexpected(c, 0)),
200 (0, 0).offset(start_loc))),
201 None => unreachable!(),
202 }
203
204 let mut input = &input[1..];
205 let mut loc = start_loc + 1;
206 let mut members = Vec::new();
207 loop {
208 {
209 let (new_input, new_loc) = consume_whitespace!(input, loc, ParseError::List);
210 input = new_input;
211 loc = new_loc;
212 }
213
214 match input.chars().nth(0) {
215 Some(')') =>
216 return Done(&input[1..],
217 Sexp::List(members, (start_loc, loc+1))),
218 Some(_) => (),
219 None => unreachable!(),
220 }
221
222 match parse_expression(input, loc) {
223 Done(new_input, member) => {
224 loc = member.get_loc().1;
225 members.push(member);
226 input = new_input;
227 }
228 Error(err) =>
229 return Error(ParseError::List(
230 Box::new(err),
231 (0, 0).offset(loc)))
232 }
233 }
234 }
235
236 pub fn parse_number(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
237 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Number);
238
239 match input.chars().next() {
240 Some(c) if !c.is_digit(10) => {
241 return Error(ParseError::Number(
242 Box::new(ParseError::Unexpected(c, start_loc)),
243 (0, c.len_utf8()).offset(start_loc)));
244 }
245 None => return Error(ParseError::Number(
246 Box::new(ParseError::UnexpectedEof),
247 (0, 0).offset(start_loc))),
248 _ => (),
249 }
250
251 let base = 10;
252
253 let mut end = 0;
254 // Before the decimal point
255 for (i, c) in input.char_indices() {
256 if c == '.' {
257 end = i + 1;
258 break;
259 }
260
261 if c.is_delimiter() {
262 return Done(&input[i..],
263 Sexp::Int(input[..i].parse().expect("Already matched digits"),
264 (0, i).offset(start_loc)));
265 }
266
267 if !c.is_digit(base) {
268 return Error(ParseError::Number(
269 Box::new(ParseError::Unexpected(c, start_loc + i)),
270 (i, i).offset(start_loc)));
271 }
272
273 end = i + c.len_utf8();
274 }
275
276 if input[end..].is_empty() {
277 return Done(&input[end..],
278 Sexp::Int(input.parse().expect("Already matched digits"),
279 (0, end).offset(start_loc)));
280 }
281
282 // After the decimal point
283 for (i, c) in input[end..].char_indices() {
284 if c.is_delimiter() {
285 return Done(&input[i+end..],
286 Sexp::Float(input[..end+i].parse().expect("Already matched digits.digits"),
287 (0, end+i).offset(start_loc)));
288 }
289
290 if !c.is_digit(base) {
291 return Error(ParseError::Number(
292 Box::new(ParseError::Unexpected(c, start_loc + i + end)),
293 (i+end, i+end).offset(start_loc)));
294 }
295 }
296
297 Done(&input[input.len()..],
298 Sexp::Float(input.parse().expect("Already matched digits.digits"),
299 (0, input.len()).offset(start_loc)))
300 }
301
302 pub fn parse_symbol(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
303 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Symbol);
304
305 match input.chars().next() {
306 Some(c@'#') | Some(c@':') | Some(c@'0'...'9') =>
307 return Error(ParseError::Symbol(
308 Box::new(ParseError::Unexpected(c, start_loc)),
309 (0, 0).offset(start_loc))),
310 Some(c) if c.is_delimiter() =>
311 return Error(ParseError::Symbol(
312 Box::new(ParseError::Unexpected(c, start_loc)),
313 (0, 0).offset(start_loc))),
314 Some(_) => (),
315 None => unreachable!(),
316 }
317
318 for (i, c) in input.char_indices() {
319 if c.is_delimiter() {
320 return Done(&input[i..],
321 Sexp::Sym(input[..i].into(), (0, i).offset(start_loc)));
322 }
323 }
324
325 Done(&input[input.len()..],
326 Sexp::Sym(input.into(), (0, input.len()).offset(start_loc)))
327 }
328
329 pub fn parse_string(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
330 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::String);
331
332 match input.chars().next() {
333 Some('"') => (),
334 Some(c) =>
335 return Error(ParseError::String(
336 Box::new(ParseError::Unexpected(c, start_loc)),
337 (0, 0).offset(start_loc))),
338 None => unreachable!(),
339 }
340
341 for (i, c) in input[1..].char_indices() {
342 if c == '"' {
343 return Done(&input[2+i..],
344 Sexp::Str(input[1..i+1].into(), (0, i+2).offset(start_loc)));
345 }
346 }
347
348 Error(ParseError::String(
349 Box::new(ParseError::UnexpectedEof),
350 (0, input.len()).offset(start_loc)))
351 }
352
353 pub fn parse_character(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
354 let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Char);
355
356 match input.chars().nth(0) {
357 Some('#') => (),
358 Some(c) =>
359 return Error(ParseError::Char(
360 Box::new(ParseError::Unexpected(c, start_loc)),
361 (0, 0).offset(start_loc))),
362 None =>
363 return Error(ParseError::Char(
364 Box::new(ParseError::UnexpectedEof),
365 (0, 0).offset(start_loc))),
366 }
367
368 match input.chars().nth(1) {
369 Some('\\') => (),
370 Some(c) =>
371 return Error(ParseError::Char(
372 Box::new(ParseError::Unexpected(c, start_loc + 1)),
373 (1, 1).offset(start_loc))),
374 None =>
375 return Error(ParseError::Char(
376 Box::new(ParseError::UnexpectedEof),
377 (1, 1).offset(start_loc)))
378 }
379
380 match input.chars().nth(2) {
381 Some(c) =>
382 Done(&input[3..], Sexp::Char(c, (0, 3).offset(start_loc))),
383 None =>
384 Error(ParseError::Char(
385 Box::new(ParseError::UnexpectedEof),
386 (2, 2).offset(start_loc)))
387 }
388 }
389
390 \f
391 // Tests ///////////////////////////////////////////////////////////////////////
392
393 #[cfg(test)]
394 mod test {
395 use sexp::Sexp;
396 use span::Span;
397 use parser::*;
398 use parser::ParseResult::*;
399
400 #[test]
401 fn test_parse() {
402 assert_eq!(parse("1 2 3"), (vec![
403 Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3)), Sexp::Int(3, (4, 5))
404 ], None));
405 assert_eq!(parse("1 2 )"), (vec![
406 Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3))
407 ], Some(ParseError::Symbol(Box::new(ParseError::Unexpected(')', 4)), (4, 4)))));
408 }
409
410 #[test]
411 fn test_parse_one() {
412 assert_eq!(parse_one("1 2"),
413 Ok((Sexp::Int(1, (0, 1)), " 2")));
414 }
415
416 #[test]
417 fn test_parse_expression() {
418 assert_eq!(parse_expression(" 1", 0),
419 Done("", Sexp::Int(1, (1, 2))));
420 assert_eq!(parse_expression("2.2", 0),
421 Done("", Sexp::Float(2.2, (0, 3))));
422 assert_eq!(parse_expression(" a", 0),
423 Done("", Sexp::Sym("a".into(), (1, 2))));
424 assert_eq!(parse_expression("#\\c", 0),
425 Done("", Sexp::Char('c', (0, 3))));
426 assert_eq!(parse_expression(r#""hi""#, 0),
427 Done("", Sexp::Str("hi".into(), (0, 4))));
428 assert_eq!(parse_expression("()", 0),
429 Done("", Sexp::List(vec![], (0, 2))));
430 assert_eq!(parse_expression("( 1 2 3 )", 0),
431 Done("", Sexp::List(vec![
432 Sexp::Int(1, (2, 3)),
433 Sexp::Int(2, (4, 5)),
434 Sexp::Int(3, (6, 7)),
435 ], (0, 9))));
436
437 assert_eq!(parse_expression("", 0),
438 Error(ParseError::Sexp(Box::new(ParseError::UnexpectedEof), (0, 0))));
439 }
440
441 #[test]
442 fn test_parse_list() {
443 assert_eq!(parse_list("()", 0),
444 Done("", Sexp::List(vec![], (0, 2))));
445 assert_eq!(parse_list("(1)", 0),
446 Done("", Sexp::List(vec![Sexp::Int(1, (1, 2))], (0, 3))));
447 assert_eq!(parse_list(" ( 1 2 3 a )", 0), Done("", Sexp::List(vec![
448 Sexp::Int(1, (4, 5)),
449 Sexp::Int(2, (9, 10)),
450 Sexp::Int(3, (12, 13)),
451 Sexp::Sym("a".into(), (14, 15)),
452 ], (2, 17))));
453 }
454
455 #[test]
456 fn test_parse_number() {
457 assert_eq!(parse_number("1", 0),
458 Done("", Sexp::Int(1, (0, 1))));
459 assert_eq!(parse_number(" 13", 0),
460 Done("", Sexp::Int(13, (1, 3))));
461 assert_eq!(parse_number("1.2", 0),
462 Done("", Sexp::Float(1.2, (0, 3))));
463 assert_eq!(parse_number("\u{3000}4.2", 0),
464 Done("", Sexp::Float(4.2, (0, 3).offset('\u{3000}'.len_utf8()))));
465 assert_eq!(parse_number(" 42 ", 0),
466 Done(" ", Sexp::Int(42, (2, 4))));
467 assert_eq!(parse_number(" 4.2 ", 0),
468 Done(" ", Sexp::Float(4.2, (1, 4))));
469 assert_eq!(parse_number("1()", 0),
470 Done("()", Sexp::Int(1, (0, 1))));
471 assert_eq!(parse_number("3.6()", 0),
472 Done("()", Sexp::Float(3.6, (0, 3))));
473
474 assert_eq!(parse_number("", 0),
475 Error(ParseError::Number(Box::new(ParseError::UnexpectedEof), (0, 0))));
476 assert_eq!(parse_number("123a", 0),
477 Error(ParseError::Number(Box::new(ParseError::Unexpected('a', 3)), (3, 3))));
478 assert_eq!(parse_number("66.6+", 0),
479 Error(ParseError::Number(Box::new(ParseError::Unexpected('+', 4)), (4, 4))));
480 }
481
482 #[test]
483 fn test_parse_ident() {
484 assert_eq!(parse_symbol("+", 0),
485 Done("", Sexp::Sym("+".into(), (0, 1))));
486 assert_eq!(parse_symbol(" nil?", 0),
487 Done("", Sexp::Sym("nil?".into(), (1, 5))));
488 assert_eq!(parse_symbol(" ->socket", 0),
489 Done("", Sexp::Sym("->socket".into(), (1, 9))));
490 assert_eq!(parse_symbol("fib(", 0),
491 Done("(", Sexp::Sym("fib".into(), (0, 3))));
492 assert_eq!(parse_symbol("foo2", 0),
493 Done("", Sexp::Sym("foo2".into(), (0, 4))));
494
495 // We reserve #foo for the implementation to do as it wishes
496 assert_eq!(parse_symbol("#hi", 0),
497 Error(ParseError::Symbol(Box::new(ParseError::Unexpected('#', 0)), (0, 0))));
498 // We reserve :foo for keywords
499 assert_eq!(parse_symbol(":hi", 0),
500 Error(ParseError::Symbol(Box::new(ParseError::Unexpected(':', 0)), (0, 0))));
501
502 assert_eq!(parse_symbol("", 0),
503 Error(ParseError::Symbol(Box::new(ParseError::UnexpectedEof), (0, 0))));
504 assert_eq!(parse_symbol("0", 0),
505 Error(ParseError::Symbol(Box::new(ParseError::Unexpected('0', 0)), (0, 0))));
506 assert_eq!(parse_symbol("()", 0),
507 Error(ParseError::Symbol(Box::new(ParseError::Unexpected('(', 0)), (0, 0))));
508 }
509
510 #[test]
511 fn test_parse_string() {
512 assert_eq!(parse_string(r#""""#, 0),
513 Done("", Sexp::Str("".into(), (0, 2))));
514 assert_eq!(parse_string(r#""hello""#, 0),
515 Done("", Sexp::Str("hello".into(), (0, 7))));
516 assert_eq!(parse_string(r#" "this is a nice string
517 with 0123 things in it""#, 0),
518 Done("", Sexp::Str("this is a nice string\nwith 0123 things in it".into(), (2, 48))));
519
520 assert_eq!(parse_string("", 0),
521 Error(ParseError::String(Box::new(ParseError::UnexpectedEof), (0, 0))));
522 assert_eq!(parse_string(r#""hi"#, 0),
523 Error(ParseError::String(Box::new(ParseError::UnexpectedEof), (0, 3))));
524 }
525
526 #[test]
527 fn test_parse_char() {
528 assert_eq!(parse_character(r#"#\""#, 0), Done("", Sexp::Char('"', (0, 3))));
529 assert_eq!(parse_character(r#"#\ "#, 0), Done("", Sexp::Char(' ', (0, 3))));
530 assert_eq!(parse_character(r#" #\\"#, 0), Done("", Sexp::Char('\\', (2, 5))));
531
532 assert_eq!(parse_character("", 0),
533 Error(ParseError::Char(Box::new(ParseError::UnexpectedEof), (0, 0))));
534 assert_eq!(parse_character("#", 0),
535 Error(ParseError::Char(Box::new(ParseError::UnexpectedEof), (1, 1))));
536 assert_eq!(parse_character("#\\", 0),
537 Error(ParseError::Char(Box::new(ParseError::UnexpectedEof), (2, 2))));
538 assert_eq!(parse_character("a", 0),
539 Error(ParseError::Char(Box::new(ParseError::Unexpected('a', 0)), (0, 0))));
540 }
541 }