Fix inner definitions as closures

This commit is contained in:
imaqtkatt 2024-06-28 12:26:39 -03:00
parent 0cd4386f32
commit cf6af170b5
3 changed files with 13 additions and 9 deletions

View File

@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use indexmap::IndexMap;
@ -29,7 +29,9 @@ impl Stmt {
nxt.lift_local_defs(parent, defs, gen)?;
*gen += 1;
let (r#use, mut def, fvs) = gen_use(local_name.clone(), *def, nxt)?;
let inner_defs =
defs.keys().filter(|name| name.starts_with(local_name.as_ref())).cloned().collect::<BTreeSet<_>>();
let (r#use, mut def, fvs) = gen_use(local_name.clone(), *def, nxt, inner_defs)?;
*self = r#use;
apply_closure(&mut def, fvs);
@ -100,12 +102,14 @@ fn gen_use(
local_name: Name,
def: Definition,
nxt: Box<Stmt>,
inner_defs: BTreeSet<Name>,
) -> Result<(Stmt, fun::Definition, Vec<Name>), String> {
let params = def.params.clone();
let ignored: BTreeSet<Name> = params.into_iter().chain(inner_defs).collect();
let mut def = def.to_fun(false)?;
let fvs = BTreeMap::from_iter(def.rules[0].body.free_vars());
let fvs = fvs.into_keys().filter(|fv| !params.contains(fv)).collect::<Vec<_>>();
let fvs = fvs.into_keys().filter(|fv| !ignored.contains(fv)).collect::<Vec<_>>();
let val = Expr::Call {
fun: Box::new(Expr::Var { nam: local_name.clone() }),
args: fvs.iter().cloned().map(|nam| Expr::Var { nam }).collect(),

View File

@ -6,8 +6,8 @@ input_file: tests/golden_tests/desugar_file/local_def_shadow.bend
(main__local_1_A__local_1_B) = 1
(main__local_1_A) = λa a
(main__local_1_A) = main__local_1_A__local_1_B
(main__local_0_A) = λa a
(main__local_0_A) = main__local_0_A__local_0_B
(main) = (main__local_1_A main__local_1_A__local_1_B)
(main) = 1

View File

@ -4,8 +4,8 @@ input_file: tests/golden_tests/desugar_file/main_aux.bend
---
(main__local_0_aux__local_0_aux__local_0_aux) = λa λb (+ b a)
(main__local_0_aux__local_0_aux) = λa λb λc (a b c)
(main__local_0_aux__local_0_aux) = λa λb (main__local_0_aux__local_0_aux__local_0_aux a b)
(main__local_0_aux) = λa λb λc λd (a b c d)
(main__local_0_aux) = λa λb (main__local_0_aux__local_0_aux a b)
(main) = (main__local_0_aux main__local_0_aux__local_0_aux main__local_0_aux__local_0_aux__local_0_aux 89 2)
(main) = (main__local_0_aux 89 2)