]>
Witch of Git - ess/blob - src/parser.rs
1 //! Functions to parse s-expressions and expression atoms.
3 //! This module contains the core parsing machinery.
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.
10 //! [`parse`]: fn.parse.html
11 //! [`parse_one`]: fn.parse_one.html
12 //! [`ParseResult`]: enum.ParseResult.html
13 //! [`parse_expression`]: fn.parse_expression.html
16 use span
::{Span
, ByteSpan
};
19 // Parsing Types ///////////////////////////////////////////////////////////////
21 /// Represents what to do next in partially completed parsing.
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`.
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.
35 /// The parser failed, the `E` represents the reason for the failure.
39 /// Indicates how parsing failed.
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
51 /// Some problem occurred while parsing a list, along with the cause of that
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
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
),
74 use self::ParseResult
::*;
77 // Parsing Utilities ///////////////////////////////////////////////////////////
80 fn is_delimiter(&self) -> bool
;
83 impl IsDelimeter
for char {
84 fn is_delimiter(&self) -> bool
{
85 self.is
_wh
itespace
() || *self == '
;'
86 || *self == '
('
|| *self == '
)'
87 || *self == '
['
|| *self == '
]'
88 || *self == '
{'
|| *self == '
}'
89 || *self == '
"' || *self == '\''
90 || *self == '`' || *self == ','
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)
99 return Error($ErrorFn(
100 Box::new(ParseError::UnexpectedEof),
101 ($input.len(), $input.len()).offset($start_loc)));
107 // Top Level Parsers ///////////////////////////////////////////////////////////
109 /// Parse a sequence of s-expressions.
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.
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.
124 /// We can get useful partial results
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());
132 pub fn parse(mut input: &str) -> (Vec<Sexp>, Option<ParseError>) {
133 let mut start_loc = 0;
134 let mut results = Vec::new();
136 match parse_expression(input, start_loc) {
137 Done(rest, result) => {
139 start_loc = result.get_loc().1;
140 results.push(result);
141 if rest.trim() == "" {
142 return (results, None);
146 return (results, Some(err));
152 /// Parses a single s-expression, ignoring any trailing text.
154 /// This function returns a pair of the parsed s-expression and the tail of the text.
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.
165 /// # use ess::parser::parse_one;
166 /// let (expr, rest) = parse_one("1 (").unwrap();
167 /// assert_eq!(rest, " (");
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),
177 // Core Parsers ////////////////////////////////////////////////////////////////
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);
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
!(),
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
);
195 match input
.chars().nth(0) {
198 return Error(ParseError
::List(
199 Box
::new(ParseError
::Unexpected(c
, 0)),
200 (0, 0).offset(start_loc
))),
201 None
=> unreachable
!(),
204 let mut input
= &input
[1..];
205 let mut loc
= start_loc
+ 1;
206 let mut members
= Vec
::new();
209 let (new_input
, new_loc
) = consume_whitespace
!(input
, loc
, ParseError
::List
);
214 match input
.chars().nth(0) {
216 return Done(&input
[1..],
217 Sexp
::List(members
, (start_loc
, loc
+1))),
219 None
=> unreachable
!(),
222 match parse_expression(input
, loc
) {
223 Done(new_input
, member
) => {
224 loc
= member
.get_loc().1;
225 members
.push(member
);
229 return Error(ParseError
::List(
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
);
239 match input
.chars().next() {
240 Some(c
) if !c
.is
_d
ig
it
(10) => {
241 return Error(ParseError
::Number(
242 Box
::new(ParseError
::Unexpected(c
, start_loc
)),
243 (0, c
.len_utf8()).offset(start_loc
)));
245 None
=> return Error(ParseError
::Number(
246 Box
::new(ParseError
::UnexpectedEof
),
247 (0, 0).offset(start_loc
))),
254 // Before the decimal point
255 for (i
, c
) in input
.char_indices() {
261 if c
.is
_del
im
iter
() {
262 return Done(&input
[i
..],
263 Sexp
::Int(input
[..i].parse().expect("Already matched digits"),
264 (0, i
).offset(start_loc
)));
267 if !c
.is
_d
ig
it
(base
) {
268 return Error(ParseError
::Number(
269 Box
::new(ParseError
::Unexpected(c
, start_loc
+ i
)),
270 (i
, i
).offset(start_loc
)));
273 end
= i
+ c
.len_utf8();
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
)));
282 // After the decimal point
283 for (i
, c
) in input
[end
..].char_indices() {
284 if c
.is
_del
im
iter
() {
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
)));
290 if !c
.is
_d
ig
it
(base
) {
291 return Error(ParseError
::Number(
292 Box
::new(ParseError
::Unexpected(c
, start_loc
+ i
+ end
)),
293 (i
+end
, i
+end
).offset(start_loc
)));
297 Done(&input
[input
.len()..],
298 Sexp
::Float(input
.parse().expect("Already matched digits.digits"),
299 (0, input
.len()).offset(start_loc
)))
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
);
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
_del
im
iter
() =>
311 return Error(ParseError
::Symbol(
312 Box
::new(ParseError
::Unexpected(c
, start_loc
)),
313 (0, 0).offset(start_loc
))),
315 None
=> unreachable
!(),
318 for (i
, c
) in input
.char_indices() {
319 if c
.is
_del
im
iter
() {
320 return Done(&input
[i
..],
321 Sexp
::Sym(input
[..i].into
(), (0, i
).offset(start_loc
)));
325 Done(&input
[input
.len()..],
326 Sexp
::Sym(input
.into
(), (0, input
.len()).offset(start_loc
)))
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
);
332 match input
.chars().next() {
335 return Error(ParseError::String(
336 Box::new(ParseError::Unexpected(c, start_loc)),
337 (0, 0).offset(start_loc))),
338 None => unreachable!(),
341 for (i, c) in input[1..].char_indices() {
343 return Done(&input
[2+i
..],
344 Sexp
::Str(input
[1..i+1].into
(), (0, i
+2).offset(start_loc
)));
348 Error(ParseError
::String(
349 Box
::new(ParseError
::UnexpectedEof
),
350 (0, input
.len()).offset(start_loc
)))
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
);
356 match input
.chars().nth(0) {
359 return Error(ParseError
::Char(
360 Box
::new(ParseError
::Unexpected(c
, start_loc
)),
361 (0, 0).offset(start_loc
))),
363 return Error(ParseError
::Char(
364 Box
::new(ParseError
::UnexpectedEof
),
365 (0, 0).offset(start_loc
))),
368 match input
.chars().nth(1) {
371 return Error(ParseError
::Char(
372 Box
::new(ParseError
::Unexpected(c
, start_loc
+ 1)),
373 (1, 1).offset(start_loc
))),
375 return Error(ParseError
::Char(
376 Box
::new(ParseError
::UnexpectedEof
),
377 (1, 1).offset(start_loc
)))
380 match input
.chars().nth(2) {
382 Done(&input
[3..], Sexp
::Char(c
, (0, 3).offset(start_loc
))),
384 Error(ParseError
::Char(
385 Box
::new(ParseError
::UnexpectedEof
),
386 (2, 2).offset(start_loc
)))
391 // Tests ///////////////////////////////////////////////////////////////////////
398 use parser
::ParseResult
::*;
402 assert_eq
!(parse("1 2 3"), (vec
![
403 Sexp
::Int(1, (0, 1)), Sexp
::Int(2, (2, 3)), Sexp
::Int(3, (4, 5))
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)))));
411 fn test_parse_one() {
412 assert_eq
!(parse_one("1 2"),
413 Ok((Sexp
::Int(1, (0, 1)), " 2")));
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)),
437 assert_eq
!(parse_expression("", 0),
438 Error(ParseError
::Sexp(Box
::new(ParseError
::UnexpectedEof
), (0, 0))));
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)),
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))));
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))));
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))));
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))));
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))));
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))));
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))));
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))));
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))));