feat(grfn/achilles): Implement tuples, and tuple patterns
Implement tuple expressions, types, and patterns, all the way through
the parser down to the typechecker. In LLVM, these are implemented as
anonymous structs, using an `extract` instruction when they're pattern
matched on to get out the individual fields.
Currently the only limitation here is patterns aren't supported in
function argument position, but you can still do something like
fn xy = let (x, y) = xy in x + y
Change-Id: I357f17e9d4052e741eda8605b6662822f331efde
Reviewed-on: https://cl.tvl.fyi/c/depot/+/3027
Reviewed-by: grfn <grfn@gws.fyi>
Tested-by: BuildkiteCI
This commit is contained in:
parent
e1c45be3f5
commit
48098f83c1
12 changed files with 413 additions and 54 deletions
|
|
@ -1,9 +1,12 @@
|
|||
mod error;
|
||||
mod value;
|
||||
|
||||
use itertools::Itertools;
|
||||
use value::Val;
|
||||
|
||||
pub use self::error::{Error, Result};
|
||||
pub use self::value::{Function, Value};
|
||||
use crate::ast::hir::{Binding, Expr};
|
||||
use crate::ast::hir::{Binding, Expr, Pattern};
|
||||
use crate::ast::{BinaryOperator, FunctionType, Ident, Literal, Type, UnaryOperator};
|
||||
use crate::common::env::Env;
|
||||
|
||||
|
|
@ -24,6 +27,17 @@ impl<'a> Interpreter<'a> {
|
|||
.ok_or_else(|| Error::UndefinedVariable(var.to_owned()))
|
||||
}
|
||||
|
||||
fn bind_pattern(&mut self, pattern: &'a Pattern<'a, Type>, value: Value<'a>) {
|
||||
match pattern {
|
||||
Pattern::Id(id, _) => self.env.set(id, value),
|
||||
Pattern::Tuple(pats) => {
|
||||
for (pat, val) in pats.iter().zip(value.as_tuple().unwrap().clone()) {
|
||||
self.bind_pattern(pat, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval(&mut self, expr: &'a Expr<'a, Type>) -> Result<Value<'a>> {
|
||||
let res = match expr {
|
||||
Expr::Ident(id, _) => self.resolve(id),
|
||||
|
|
@ -53,9 +67,9 @@ impl<'a> Interpreter<'a> {
|
|||
}
|
||||
Expr::Let { bindings, body, .. } => {
|
||||
self.env.push();
|
||||
for Binding { ident, body, .. } in bindings {
|
||||
for Binding { pat, body, .. } in bindings {
|
||||
let val = self.eval(body)?;
|
||||
self.env.set(ident, val);
|
||||
self.bind_pattern(pat, val);
|
||||
}
|
||||
let res = self.eval(body)?;
|
||||
self.env.pop();
|
||||
|
|
@ -115,6 +129,13 @@ impl<'a> Interpreter<'a> {
|
|||
body: (**body).to_owned(),
|
||||
}))
|
||||
}
|
||||
Expr::Tuple(members, _) => Ok(Val::Tuple(
|
||||
members
|
||||
.into_iter()
|
||||
.map(|expr| self.eval(expr))
|
||||
.try_collect()?,
|
||||
)
|
||||
.into()),
|
||||
}?;
|
||||
debug_assert_eq!(&res.type_(), expr.type_());
|
||||
Ok(res)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue