allow js method chaining

pull/5/head
azur 2023-03-07 04:27:24 +07:00
parent 7ac147de32
commit 35ffd11321
3 changed files with 24 additions and 12 deletions

5
a.hlm
View File

@ -1,4 +1 @@
let x: num = 1, print("Hello\n");
y: num = 2,
in
println(if x + y == 3 then 69 else 0);

View File

@ -14,7 +14,7 @@ pub enum JSExpr {
Op(&'static str, Box<Self>, Option<Box<Self>>), Op(&'static str, Box<Self>, Option<Box<Self>>),
Call(Box<Self>, Vec<Self>), Call(Box<Self>, Vec<Self>),
Method(Box<Self>, String, Vec<Self>), Method(Box<Self>, String, Option<Vec<Self>>),
Lambda { Lambda {
args: Vec<String>, args: Vec<String>,
body: Vec<Self>, body: Vec<Self>,
@ -76,14 +76,18 @@ impl Display for JSExpr {
write!(f, ")") write!(f, ")")
}, },
JSExpr::Method(c, m, args) => { JSExpr::Method(c, m, args) => {
write!(f, "{}.{}(", c, m)?; write!(f, "{}.{}", c, m)?;
for (i, arg) in args.iter().enumerate() { if let Some(args) = args {
if i > 0 { write!(f, "(")?;
write!(f, ", ")?; for (i, arg) in args.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", arg)?;
} }
write!(f, "{}", arg)?; write!(f, ")")?;
} }
write!(f, ")") Ok(())
}, },
JSExpr::Lambda { args, body } => { JSExpr::Lambda { args, body } => {
write!(f, "((")?; write!(f, "((")?;

View File

@ -158,9 +158,20 @@ pub fn translate_js_expr(expr: Expr) -> JSExpr {
JSExpr::Method( JSExpr::Method(
Box::new(JSExpr::Sym("console".to_string())), Box::new(JSExpr::Sym("console".to_string())),
"log".to_string(), "log".to_string(),
args.into_iter().map(translate_js_expr).collect(), Some(args.into_iter().map(translate_js_expr).collect()),
) )
}, },
"print" => {
JSExpr::Method(
Box::new(JSExpr::Method(
Box::new(JSExpr::Sym("process".to_string())),
"stdout".to_string(),
None,
)),
"write".to_string(),
Some(args.into_iter().map(translate_js_expr).collect()),
)
}
_ => JSExpr::Call( _ => JSExpr::Call(
Box::new(translate_js_expr(*f)), Box::new(translate_js_expr(*f)),
args.into_iter().map(translate_js_expr).collect(), args.into_iter().map(translate_js_expr).collect(),