diff --git a/crates/engine/src/cmd/formulas.rs b/crates/engine/src/cmd/formulas.rs index 7b2e2732f..18945310d 100644 --- a/crates/engine/src/cmd/formulas.rs +++ b/crates/engine/src/cmd/formulas.rs @@ -432,20 +432,41 @@ fn rename_name_in_formulas(wb: &mut gridcraft_model::Workbook, old: &str, old_sc Some(s) => s == sheet, None => !shadowed.contains(&sheet), }; - // Set when an occurrence would be captured by a LET or LAMBDA local of the new name. + // A sheet-level name `new` wins over a workbook-level one on its sheet, so a workbook name + // renamed to it would read that sheet's name there instead. + let taken_on: Vec = match old_scope { + None => wb.names.iter().filter(|n| n.name.eq_ignore_ascii_case(new)).filter_map(|n| n.scope).collect(), + Some(_) => Vec::new(), + }; + // Set when an occurrence would be captured by a LET or LAMBDA local of the new name, or by a + // sheet-level name of the new name on the sheet that holds it. let captured = std::cell::Cell::new(false); - let rename = |e: gridcraft_formula::Expr| { - let mut bound = Vec::new(); - rename_free_name(e, old, new, &mut bound, &captured, 0) + let redirected = std::cell::Cell::new(false); + let rename = |sheet: Option, e: gridcraft_formula::Expr| { + if sheet.is_some_and(|i| taken_on.contains(&i)) { + // Every free occurrence here would be read as the sheet's own name `new`. + let mut bound = vec![new.to_string()]; + rename_free_name(e, old, new, &mut bound, &redirected, 0) + } else { + let mut bound = Vec::new(); + rename_free_name(e, old, new, &mut bound, &captured, 0) + } }; // Every reference held where the renamed name is the one meant: on its sheet (or, for a // workbook name, every sheet without one of its own), and in workbook names. - wb.rewrite_references(&|host, e| if host.sheet.is_none_or(applies) { rename(e) } else { e }); + wb.rewrite_references(&|host, e| if host.sheet.is_none_or(applies) { rename(host.sheet, e) } else { e }); // Python cells' `xl("…")` references too. let sheet_of: std::collections::HashMap = wb.sheets.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); crate::cmd::edit::rewrite_python_refs(wb, &|host, e| { - if sheet_of.get(&host.to_ascii_lowercase()).copied().is_none_or(applies) { rename(e) } else { e } + let sheet = sheet_of.get(&host.to_ascii_lowercase()).copied(); + if sheet.is_none_or(applies) { rename(sheet, e) } else { e } })?; + // (The command's edit is dropped on an error, so a refused rename changes nothing.) + if redirected.get() { + return Err(EngineError::Other(format!( + "The name can't be changed to {new}: a sheet already has its own name {new}, which its formulas would read instead." + ))); + } if captured.get() { return Err(EngineError::Other(format!( "The name can't be changed to {new}: a LET or LAMBDA in a formula that uses it already has a local name {new}." @@ -518,7 +539,19 @@ fn rename_free_name( bound.truncate(saved); Expr::Call(name, out) } - Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| walk(a, bound)).collect()), + Expr::Call(name, args) => { + // A call by name to a defined LAMBDA (`Fn(4)`) follows the name, unless a local of that + // name is the one called. + let name = if name.eq_ignore_ascii_case(old) && !is_bound(bound, &name) { + if is_bound(bound, new) { + captured.set(true); + } + new.to_string() + } else { + name + }; + Expr::Call(name, args.into_iter().map(|a| walk(a, bound)).collect()) + } Expr::Invoke(callee, args) => Expr::Invoke(Box::new(walk(*callee, bound)), args.into_iter().map(|a| walk(a, bound)).collect()), Expr::Array(rows) => Expr::Array(rows.into_iter().map(|r| r.into_iter().map(|x| walk(x, bound)).collect()).collect()), Expr::Unary(op, x) => Expr::Unary(op, Box::new(walk(*x, bound))), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ff7c59245..9cd7fbd94 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -196,6 +196,39 @@ fn renaming_a_name_onto_a_let_local_is_refused() { assert_eq!(s.doc().unwrap().wb.sheets[0].validations[0].f1.trim_start_matches('='), "LET(Total, 1, Rate*Total)>0"); } +/// A workbook name renamed to a name a sheet already defines for itself would be read as the +/// sheet's own name there: the rename is refused and changes nothing. +#[test] +fn renaming_a_workbook_name_onto_a_sheet_level_name_is_refused() { + let mut s = s(); + s.execute("formulas.defineName", json!({"name": "Rate", "refersTo": "=2"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "Total", "refersTo": "=9", "scope": "Sheet1"})).unwrap(); + s.execute("cell.set", json!({"cell": "A1", "input": "=Rate"})).unwrap(); + assert!(s.execute("formulas.defineName", json!({"name": "Total", "oldName": "Rate", "refersTo": "=2"})).is_err()); + assert_eq!(v(&s, "A1"), Value::number(2.0)); + assert!(s.doc().unwrap().wb.names.iter().any(|n| n.name == "Rate" && n.scope.is_none())); + // Where no sheet defines the new name, the rename goes ahead. + s.execute("formulas.defineName", json!({"name": "Fee", "oldName": "Rate", "refersTo": "=2"})).unwrap(); + assert_eq!(v(&s, "A1"), Value::number(2.0)); +} + +/// A call to a defined LAMBDA by its name follows a rename of the name; a LAMBDA local of the +/// old name that is called stays as it is. +#[test] +fn renaming_a_lambda_name_renames_calls_to_it() { + let mut s = s(); + s.execute("formulas.defineName", json!({"name": "FnOld", "refersTo": "=LAMBDA(x, x+1)"})).unwrap(); + s.execute("cell.set", json!({"cell": "A1", "input": "=FnOld(4)"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "=LET(FnOld, LAMBDA(y, y*10), FnOld(4))+FnOld(1)"})).unwrap(); + s.execute("formulas.defineName", json!({"name": "FnNew", "oldName": "FnOld", "refersTo": "=LAMBDA(x, x+1)"})).unwrap(); + let formula = + |s: &Session, at: &str| s.doc().unwrap().wb.sheets[0].cell(CellRef::parse(at).unwrap()).and_then(|c| c.formula.clone()).unwrap().text.clone(); + assert_eq!(formula(&s, "A1"), "FnNew(4)"); + assert_eq!(v(&s, "A1"), Value::number(5.0)); + assert_eq!(formula(&s, "A2"), "LET(FnOld,LAMBDA(y,y*10),FnOld(4))+FnNew(1)"); + assert_eq!(v(&s, "A2"), Value::number(42.0)); +} + #[test] fn chart_recommendations_follow_the_data_shape() { // #215: Recommended Charts lists chart types for the data; programmatic insert stays dialog-free.