Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions crates/lean_compiler/src/a_simplify_lang.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1639,7 +1639,6 @@ fn handle_inlined_functions_helper(
}

fn handle_const_arguments(program: &mut Program) {
// TODO this doesnt suupport const functions calling other const functions
let mut new_functions = BTreeMap::<String, Function>::new();
let constant_functions = program
.functions
Expand All @@ -1648,9 +1647,45 @@ fn handle_const_arguments(program: &mut Program) {
.map(|(name, func)| (name.clone(), func.clone()))
.collect::<BTreeMap<_, _>>();

// First pass: process non-const functions that call const functions
for func in program.functions.values_mut() {
handle_const_arguments_helper(&mut func.body, &constant_functions, &mut new_functions);
if !func.has_const_arguments() {
handle_const_arguments_helper(&mut func.body, &constant_functions, &mut new_functions);
}
}

// Process newly created const functions recursively until no more changes
let mut changed = true;
while changed {
changed = false;
let mut additional_functions = BTreeMap::new();

// Collect all function names to process
let function_names: Vec<String> = new_functions.keys().cloned().collect();

for name in function_names {
if let Some(func) = new_functions.get_mut(&name) {
let initial_count = additional_functions.len();
handle_const_arguments_helper(
&mut func.body,
&constant_functions,
&mut additional_functions,
);
if additional_functions.len() > initial_count {
changed = true;
}
}
}

// Add any newly discovered functions
for (name, func) in additional_functions {
if let std::collections::btree_map::Entry::Vacant(e) = new_functions.entry(name) {
e.insert(func);
changed = true;
}
}
}

for (name, func) in new_functions {
assert!(!program.functions.contains_key(&name),);
program.functions.insert(name, func);
Expand Down
23 changes: 23 additions & 0 deletions crates/lean_compiler/tests/test_compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,26 @@ fn test_match() {
// "#;
// compile_and_run(program, &[], &[]);
// }

#[test]
fn test_const_functions_calling_const_functions() {
// Test that const functions can call other const functions
let program = r#"
fn main() {
y = compute_value(3);
print(y);
return;
}

fn compute_value(const n) -> 1 {
result = complex_computation(n, 5);
return result;
}

fn complex_computation(const a, const b) -> 1 {
return a * a + b * b;
}
"#;

compile_and_run(program, &[], &[], false);
}