noodling on sexp

This commit is contained in:
Greg Shuflin 2024-01-29 17:28:01 -08:00
parent cdbbb8214f
commit a9d08a9213
5 changed files with 21 additions and 2 deletions

View File

@ -2,5 +2,5 @@ _default:
just --list just --list
test: test *args:
cargo nextest run cargo nextest run {{args}}

View File

@ -49,6 +49,7 @@ pub fn identifier(input: &str) -> ParseResult<&str, String, ()> {
} }
pub fn whitespace(input: &str) -> ParseResult<&str, char, ()> { pub fn whitespace(input: &str) -> ParseResult<&str, char, ()> {
println!("whitespace: `{input}`");
match input.chars().next() { match input.chars().next() {
Some(ch) if ch.is_whitespace() => Ok((ch, &input[1..])), Some(ch) if ch.is_whitespace() => Ok((ch, &input[1..])),
_ => Err(((), input)), _ => Err(((), input)),

View File

@ -12,9 +12,13 @@ pub fn surrounded_by<I, O1, O2, E>(
surrounding: impl Parser<I, O2, E>, surrounding: impl Parser<I, O2, E>,
) -> impl Parser<I, O1, E> { ) -> impl Parser<I, O1, E> {
move |input| { move |input| {
println!("surrounded_by");
let (_result1, rest1) = surrounding.parse(input)?; let (_result1, rest1) = surrounding.parse(input)?;
println!("A");
let (result2, rest2) = main.parse(rest1)?; let (result2, rest2) = main.parse(rest1)?;
println!("B");
let (_result3, rest3) = surrounding.parse(rest2)?; let (_result3, rest3) = surrounding.parse(rest2)?;
println!("C");
Ok((result2, rest3)) Ok((result2, rest3))
} }
} }

View File

@ -67,4 +67,9 @@ fn test_repeated() {
let output = parser.parse("bongo bongo bongo bongo"); let output = parser.parse("bongo bongo bongo bongo");
let output = output.unwrap(); let output = output.unwrap();
assert_eq!(output.0, vec!["bongo", "bongo", "bongo", "bongo"]); assert_eq!(output.0, vec!["bongo", "bongo", "bongo", "bongo"]);
let bongos = repeated(literal("bongo"));
let output = bongos.parse("tra la la").unwrap();
assert_eq!(output.0.len(), 0);
assert_eq!(output.1, "tra la la");
} }

View File

@ -48,6 +48,7 @@ fn test_parse_atom() {
} }
fn parse_expr(input: &str) -> ParseResult<&str, Expr, ()> { fn parse_expr(input: &str) -> ParseResult<&str, Expr, ()> {
println!("parse_expr: {input}");
choice((parse_list, parse_atom.map(Expr::Atom))).parse(input) choice((parse_list, parse_atom.map(Expr::Atom))).parse(input)
} }
@ -60,9 +61,17 @@ fn parse_list(input: &str) -> ParseResult<&str, Expr, ()> {
) )
.then_ignore(literal_char(')')) .then_ignore(literal_char(')'))
.map(Expr::List) .map(Expr::List)
.surrounded_by(repeated(whitespace))
.parse(input) .parse(input)
} }
#[test]
fn test_parse_list() {
let output = parse_list.parse("\n(1 2 (1 2) 9999 3)").unwrap();
assert_eq!(output.1, "");
}
#[test] #[test]
fn test_parse_sexp() { fn test_parse_sexp() {
let output = parse_expr("(add 1 2)").unwrap(); let output = parse_expr("(add 1 2)").unwrap();