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,
y: num = 2,
in
println(if x + y == 3 then 69 else 0);
print("Hello\n");

View File

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

View File

@ -158,9 +158,20 @@ pub fn translate_js_expr(expr: Expr) -> JSExpr {
JSExpr::Method(
Box::new(JSExpr::Sym("console".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(
Box::new(translate_js_expr(*f)),
args.into_iter().map(translate_js_expr).collect(),