This commit is contained in:
2026-04-12 17:26:39 -04:00
parent 2582e8c87e
commit f702f47714
9 changed files with 121 additions and 49 deletions
+18 -5
View File
@@ -1,7 +1,8 @@
use super::*;
pub struct Func {
args: Vec<Id<Ident>>,
args: Vec<Id<Param>>,
ret: Option<Id<Type>>,
body: Id<Expr>,
}
@@ -9,21 +10,33 @@ impl Parsable for Func {
fn parse(ctx: &mut ParseCtx) -> Result<Self, CompilerMsg> {
ctx.expect(Token::OpenParen)?;
let args = ctx.list(Token::Comma, Token::CloseParen)?;
let body = ctx.parse()?;
Ok(Self { args, body })
let mut ret = None;
if ctx.next_if(Token::Arrow) {
ret = Some(ctx.parse()?);
}
let body = if ret.is_some() {
ctx.parse_with(Expr::block)
} else {
ctx.parse()
}?;
Ok(Self { args, ret, body })
}
}
impl FmtNode for Func {
fn fmt(&self, f: &mut std::fmt::Formatter, ctx: DisplayCtx) -> std::fmt::Result {
write!(f, "(")?;
write!(f, "fn(")?;
if let Some((last, rest)) = self.args.split_last() {
for arg in rest {
write!(f, "{}, ", arg.dsp(ctx))?;
}
write!(f, "{}", last.dsp(ctx))?;
}
write!(f, ") {}", self.body.dsp(ctx))?;
write!(f, ") ")?;
if let Some(ret) = self.ret {
write!(f, "-> {} ", ret.dsp(ctx))?;
}
self.body.fmt(f, ctx)?;
Ok(())
}
}