pipe, return

This commit is contained in:
2025-05-30 22:20:42 +02:00
parent 397f87c242
commit cfe35bcc9d
4 changed files with 61 additions and 11 deletions

View File

@@ -31,6 +31,7 @@ pub enum Stmt {
params: Vec<Param>,
body: Box<Stmt>,
},
Return(Expr),
}
#[derive(Debug, Clone)]
@@ -139,11 +140,17 @@ impl Parser {
self.if_statement()
} else if self.match_token(&[TokenType::KeywordWhile]) {
self.while_statement()
} else if self.match_token(&[TokenType::KeywordReturn]) {
self.return_statement()
} else {
Ok(Stmt::Expression(self.expression()?))
}
}
fn return_statement(&mut self) -> Result<Stmt, Box<dyn Error>> {
Ok(Stmt::Return(self.expression()?))
}
fn if_statement(&mut self) -> Result<Stmt, Box<dyn Error>> {
let condition = self.expression()?;
let then_branch = self.block()?;
@@ -177,7 +184,7 @@ impl Parser {
}
fn assignment(&mut self) -> Result<Expr, Box<dyn Error>> {
let expr = self.logical_or()?;
let expr = self.pipe()?;
if self.match_token(&[TokenType::Equal]) {
let equals = self.previous().clone();
@@ -195,6 +202,36 @@ impl Parser {
Ok(expr)
}
fn pipe(&mut self) -> Result<Expr, Box<dyn Error>> {
let mut expr = self.logical_or()?;
while self.match_token(&[TokenType::Pipe]) {
let pipe = self.previous().clone();
let right = self.equality()?;
match right {
Expr::Call {
callee,
paren,
args,
} => {
let mut new_args = args;
new_args.insert(0, expr);
expr = Expr::Call {
callee,
paren,
args: new_args,
}
}
_ => {
return error!(pipe.loc, "tried to pipe into a non-call expression");
}
};
}
Ok(expr)
}
fn logical_or(&mut self) -> Result<Expr, Box<dyn Error>> {
let mut expr = self.logical_and()?;