From 106f5475da10a64414ad2222dfa9230008f9fabf Mon Sep 17 00:00:00 2001 From: Caleb Jones Date: Sat, 24 Dec 2016 22:58:50 -0500 Subject: [PATCH] Add top level parsing functions --- src/lib.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 1665b30..15d0d2b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,7 +137,37 @@ macro_rules! consume_whitespace { } -// Parsers ///////////////////////////////////////////////////////////////////// +// Top Level Parsers /////////////////////////////////////////////////////////// + +pub fn parse_one(input: &str) -> Result<(Sexp, &str), ParseError> { + match parse_sexp(input, 0) { + Done(rest, result) => Ok((result, rest)), + Error(err) => Err(err), + } +} + +pub fn parse(mut input: &str) -> (Vec, Option) { + let mut start_loc = 0; + let mut results = Vec::new(); + loop { + match parse_sexp(input, start_loc) { + Done(rest, result) => { + input = rest; + start_loc = result.get_loc().1; + results.push(result); + if rest.trim() == "" { + return (results, None); + } + } + Error(err) => { + return (results, Some(err)); + } + } + } +} + + +// Core Parsers //////////////////////////////////////////////////////////////// pub fn parse_sexp(input: &str, start_loc: usize) -> ParseResult { let (input, start_loc) = consume_whitespace!(input, start_loc, ParseError::Sexp); @@ -360,6 +390,21 @@ mod test { use super::*; use super::ParseResult::*; + #[test] + fn test_parse() { + assert_eq!(parse("1 2 3"), (vec![ + Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3)), Sexp::Int(3, (4, 5)) + ], None)); + assert_eq!(parse("1 2 )"), (vec![ + Sexp::Int(1, (0, 1)), Sexp::Int(2, (2, 3)) + ], Some(ParseError::Symbol(Box::new(ParseError::Unexpected(')', 4)), (4, 4))))); + } + + #[test] + fn test_parse_one() { + assert_eq!(parse_one("1 2"), Ok((Sexp::Int(1, (0, 1)), " 2"))); + } + #[test] fn test_parse_sexp() { assert_eq!(parse_sexp(" 1", 0), Done("", Sexp::Int(1, (1, 2)))); -- 2.43.2