Variables

This commit is contained in:
Michael Zhang 2022-07-17 21:13:09 -05:00
parent 16cde4377c
commit 221beea478
Signed by: michael
GPG key ID: BDA47A31A3C8EE6B
4 changed files with 26 additions and 8 deletions

View file

@ -19,11 +19,11 @@ impl<W: Write> LlvmIrCodegen<W> {
&mut self, &mut self,
expr: &'a Expr<Type>, expr: &'a Expr<Type>,
) -> Result<ExprLlvm<'a>> { ) -> Result<ExprLlvm<'a>> {
let expr_id = self.gensym("expr"); let ty_str = type_to_llvm(&expr.ty);
let mut expr_id = self.gensym("expr");
match &expr.kind { match &expr.kind {
ExprKind::Int(n) => { ExprKind::Int(n) => {
let ty_str = type_to_llvm(&expr.ty);
writeln!(self.writer, "%{} = alloca {}", expr_id, ty_str)?; writeln!(self.writer, "%{} = alloca {}", expr_id, ty_str)?;
writeln!( writeln!(
self.writer, self.writer,
@ -31,7 +31,12 @@ impl<W: Write> LlvmIrCodegen<W> {
ty_str, n, ty_str, expr_id ty_str, n, ty_str, expr_id
)?; )?;
} }
ExprKind::Var(_) => todo!(), ExprKind::Var(name) => match self.var_env.lookup(name) {
Some((_, name)) => {
expr_id = name.clone();
}
None => bail!("Unbound name {name:?}"),
},
ExprKind::BinOp(_, _, _) => todo!(), ExprKind::BinOp(_, _, _) => todo!(),
ExprKind::Call(_, _) => todo!(), ExprKind::Call(_, _) => todo!(),
} }

View file

@ -13,16 +13,16 @@ use super::CodegenBackend;
pub struct LlvmIrCodegen<W> { pub struct LlvmIrCodegen<W> {
ctr: usize, ctr: usize,
env: LayeredEnv<String, ()>, var_env: LayeredEnv<String, (Type, String)>,
writer: W, writer: W,
} }
impl<W> LlvmIrCodegen<W> { impl<W> LlvmIrCodegen<W> {
pub fn new(writer: W) -> Self { pub fn new(writer: W) -> Self {
let env = LayeredEnv::default(); let env = LayeredEnv::new();
LlvmIrCodegen { LlvmIrCodegen {
ctr: 0, ctr: 0,
env, var_env: env,
writer, writer,
} }
} }

View file

@ -15,7 +15,14 @@ impl<W: Write> LlvmIrCodegen<W> {
for stmt in stmts.iter() { for stmt in stmts.iter() {
match stmt { match stmt {
Stmt::Let(_, _, _) => todo!(), Stmt::Let(name, _, expr) => {
let ty = expr.ty.clone();
let expr = self.convert_expr(&expr)?;
let new_name = expr.name().to_owned();
// TODO:
self.var_env.insert(name.clone(), (ty, new_name));
}
Stmt::Return(expr) => match expr { Stmt::Return(expr) => match expr {
Some(ret_val) => { Some(ret_val) => {
let ret_ty = type_to_llvm(&ret_val.ty); let ret_ty = type_to_llvm(&ret_val.ty);

View file

@ -1,13 +1,19 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::hash::Hash; use std::hash::Hash;
#[derive(Default)]
pub struct LayeredEnv<K, V> { pub struct LayeredEnv<K, V> {
parent: Option<Box<LayeredEnv<K, V>>>, parent: Option<Box<LayeredEnv<K, V>>>,
inner_map: HashMap<K, V>, inner_map: HashMap<K, V>,
} }
impl<K: Hash + Eq, V> LayeredEnv<K, V> { impl<K: Hash + Eq, V> LayeredEnv<K, V> {
pub fn new() -> Self {
LayeredEnv {
parent: None,
inner_map: HashMap::new(),
}
}
pub fn insert(&mut self, key: K, value: V) { pub fn insert(&mut self, key: K, value: V) {
self.inner_map.insert(key, value); self.inner_map.insert(key, value);
} }