KCL: Fix 'cryptic' error when referencing a variable in its own declaration

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#issuecomment-2923227477
This commit is contained in:
Adam Chalmers
2025-05-30 16:57:15 -05:00
parent 5fccaad0e7
commit cc07400719
15 changed files with 241 additions and 38 deletions

View File

@ -367,10 +367,10 @@ impl ProgramMemory {
let name = var.trim_start_matches(TYPE_PREFIX).trim_start_matches(MODULE_PREFIX);
Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("`{name}` is not defined"),
vec![source_range],
)))
Err(KclError::UndefinedValue {
undefined_name: Some(name.to_owned()),
details: KclErrorDetails::new(format!("`{name}` is not defined"), vec![source_range]),
})
}
/// Iterate over all key/value pairs in the specified environment which satisfy the provided
@ -488,10 +488,10 @@ impl ProgramMemory {
};
}
Err(KclError::UndefinedValue(KclErrorDetails::new(
format!("`{}` is not defined", var),
vec![],
)))
Err(KclError::UndefinedValue {
undefined_name: Some(var.to_owned()),
details: KclErrorDetails::new(format!("`{}` is not defined", var), vec![]),
})
}
}