Fix variable generation for nested map gets

This commit is contained in:
imaqtkatt 2024-05-24 08:35:44 -03:00
parent 5036534d9f
commit 4d303ac99c
3 changed files with 18 additions and 3 deletions

View File

@ -1,4 +1,4 @@
use std::collections::HashMap;
use indexmap::IndexMap;
use crate::fun::Name;
@ -116,13 +116,14 @@ impl Stmt {
}
}
type Substitutions = HashMap<Name, (Name, Box<Expr>)>;
type Substitutions = IndexMap<Name, (Name, Box<Expr>)>;
impl Expr {
fn substitute_map_gets(&mut self, id: &mut usize) -> Substitutions {
fn go(e: &mut Expr, substitutions: &mut Substitutions, id: &mut usize) {
match e {
Expr::MapGet { nam, key } => {
go(key, substitutions, id);
let new_var = gen_map_var(id);
substitutions.insert(new_var.clone(), (nam.clone(), key.clone()));
*e = Expr::Var { nam: new_var };
@ -175,7 +176,7 @@ impl Expr {
}
fn gen_get(current: &mut Stmt, substitutions: Substitutions) -> Stmt {
substitutions.into_iter().fold(std::mem::take(current), |acc, next| {
substitutions.into_iter().rfold(std::mem::take(current), |acc, next| {
let (var, (map_var, key)) = next;
let map_get_call = Expr::Var { nam: Name::new("Map/get") };
let map_get_call = Expr::Call {

View File

@ -0,0 +1,5 @@
def x:
return { 0: 1, 1: 42, 2: 0, 3: 2 }
def main():
return x[x[0]] + x[x[x[3]]]

View File

@ -0,0 +1,9 @@
---
source: tests/golden_tests.rs
input_file: tests/golden_tests/run_file/nested_map_get.bend
---
NumScott:
43
Scott:
43