KCL: Fix 'cryptic' error when referencing a variable in its own declaration (#7325)

Previously, `x = cos(x)` would just say "`x` is undefined". Now it says that `x` cannot be referenced in its own definition, try using a different variable instead.

To do this, I've added a new `Option<String>` field to the mod-local executor context, tracking the current variable declaration. This means cloning some strings, implying a small performance hit. I think it's fine, for the better diagnostics.

In the future we could refactor this to use a &str or store variable labels in stack-allocated strings like docs.rs/compact_str or something.

Closes https://github.com/KittyCAD/modeling-app/issues/6072
This commit is contained in:
Adam Chalmers
2025-06-02 17:25:55 -05:00
committed by GitHub
parent 2bb6c74f42
commit 7680605085
15 changed files with 230 additions and 39 deletions

View File

@ -80,6 +80,11 @@ pub(super) struct ModuleState {
/// The current value of the pipe operator returned from the previous
/// expression. If we're not currently in a pipeline, this will be None.
pub pipe_value: Option<KclValue>,
/// The closest variable declaration being executed in any parent node in the AST.
/// This is used to provide better error messages, e.g. noticing when the user is trying
/// to use the variable `length` inside the RHS of its own definition, like `length = tan(length)`.
/// TODO: Make this a reference.
pub being_declared: Option<String>,
/// Identifiers that have been exported from the current module.
pub module_exports: Vec<String>,
/// Settings specified from annotations.
@ -342,6 +347,7 @@ impl ModuleState {
id_generator: IdGenerator::new(module_id),
stack: memory.new_stack(),
pipe_value: Default::default(),
being_declared: Default::default(),
module_exports: Default::default(),
explicit_length_units: false,
path,