Blocks are a kind of expression now

This commit is contained in:
Dane Johnson 2022-02-01 10:57:04 -06:00
parent 7669be9c59
commit 49badc37a4

View File

@ -9,16 +9,11 @@ pub enum Expr<'a> {
Id(&'a str),
Num(f64),
Funcall(&'a str, Vec<Expr<'a>>),
Funcdef(Option<&'a str>, Fun<'a>),
Funcdef(Option<&'a str>, Box<Expr<'a>>),
Plus(Box<Expr<'a>>, Box<Expr<'a>>),
Minus(Box<Expr<'a>>, Box<Expr<'a>>),
Mult(Box<Expr<'a>>, Box<Expr<'a>>),
Div(Box<Expr<'a>>, Box<Expr<'a>>),
}
#[derive(Debug,PartialEq)]
pub enum Fun<'a> {
Oner(Box<Expr<'a>>),
Block(Vec<Stmt<'a>>),
}
@ -42,6 +37,8 @@ peg::parser! {
i:id() _ { Expr::Id(i) }
n:num() _ { Expr::Num(n) }
}
rule block() -> Expr<'input>
= stop() indent() __* s:stmt()+ dedent() { Expr::Block(s) }
rule id() -> &'input str
= i:$(letter() (letter() / digit() / ['?'|'.'|'-'])*) _ { i }
@ -50,8 +47,8 @@ peg::parser! {
rule funcall() -> Expr<'input>
= i:id() "(" _ e:(expr() ** ("," _)) ")" _ { Expr::Funcall(i, e) }
rule funcdef() -> Expr<'input>
= i:id()? "->" _ e:expr() { Expr::Funcdef(i, Fun::Oner(Box::new(e))) } /
i:id()? "->" _ stop() indent() __* s:stmt()+ dedent() { Expr::Funcdef(i, Fun::Block(s)) }
= i:id()? "->" _ e:expr() { Expr::Funcdef(i, Box::new(e)) } /
i:id()? "->" _ b:block() { Expr::Funcdef(i, Box::new(b)) }
rule letter()
= ['A'..='Z'] / ['a'..='z']
@ -139,7 +136,7 @@ four <- (3 - 1) * 2";
Stmt::Assignment("four",
Expr::Mult(
Box::new(Expr::Minus(
Box::new(Expr::Num(3.0)),
Box::new(Expr::Num(3.0)),
Box::new(Expr::Num(1.0)),
)),
Box::new(Expr::Num(2.0)),
@ -179,36 +176,30 @@ foo <- x -> y -> x * y";
"foo",
Expr::Funcdef(
None,
Fun::Oner(
Box::new(Expr::Funcall("bar", vec![])),
)
Box::new(Expr::Funcall("bar", vec![])),
)
),
Stmt::Assignment(
"foo",
Expr::Funcdef(
None,
Fun::Block(vec![
Box::new(Expr::Block(vec![
Stmt::Funcall(Expr::Funcall("bar", vec![])),
Stmt::Funcall(Expr::Funcall("baz", vec![])),
])
]))
)
),
Stmt::Assignment(
"foo",
Expr::Funcdef(
Some("x"),
Fun::Oner(
Box::new(
Expr::Funcdef(
Some("y"),
Fun::Oner(
Box::new(
Expr::Mult(
Box::new(Expr::Id("x")),
Box::new(Expr::Id("y")),
)
)
Box::new(
Expr::Funcdef(
Some("y"),
Box::new(
Expr::Mult(
Box::new(Expr::Id("x")),
Box::new(Expr::Id("y")),
)
)
)