Skip to content
Merged
23 changes: 17 additions & 6 deletions crates/data/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1616,12 +1616,26 @@ pub fn matches(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> bool {

/// Tests a row in a chunk whose first row has `offset` preceding rows in the source.
pub(crate) fn eval_in_chunk(e: &Expr, ds: &Dataset, row: usize, offset: usize) -> bool {
let env = Env::default();
let mut eval = Eval::new(ds, row, &env);
matches_at(e, ds, row, &Env::default(), offset)
}

/// [`matches`] for a row of `ds` that has `offset` rows before `ds`'s first in its layer, so
/// `@row_number` reads its place there: a chunk of a source, or a copy of one row (#2837).
pub fn matches_at(e: &Expr, ds: &Dataset, row: usize, env: &Env, offset: usize) -> bool {
let mut eval = Eval::new(ds, row, env);
eval.row_offset = offset;
eval.cond(e) == Some(true)
}

/// [`value_or_fault`] at `offset`, as [`matches_at`] reads a row.
pub fn value_or_fault_at(e: &Expr, ds: &Dataset, row: usize, env: &Env, offset: usize) -> (Value, Option<Fault>) {
let mut eval = Eval::new(ds, row, env);
eval.row_offset = offset;
let v = eval.value(e).into_owned();
let fault = if v.is_null() { eval.fault.get() } else { None };
(v, fault)
}

/// The expression's value for one row.
pub fn value(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> Value {
Eval::new(ds, row, env).value(e).into_owned()
Expand All @@ -1632,10 +1646,7 @@ pub fn value(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> Value {
/// or `CASE` condition only picks the branch, so it isn't the result's. Where several errors
/// reach the result, the first one met is given.
pub fn value_or_fault(e: &Expr, ds: &Dataset, row: usize, env: &Env) -> (Value, Option<Fault>) {
let eval = Eval::new(ds, row, env);
let v = eval.value(e).into_owned();
let fault = if v.is_null() { eval.fault.get() } else { None };
(v, fault)
value_or_fault_at(e, ds, row, env, 0)
}

/// Whether a value counts as true: a non-zero number, non-empty text; null is unknown.
Expand Down
184 changes: 114 additions & 70 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,6 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
}
}
let rows: Vec<usize> = changes.iter().filter_map(|c| c.row).collect();
// What each calculation rule's whole-number field cut: the rule and the field's name. Each
// rule's cuts are said, even when a later rule writes the same field: it may read them.
// With them, per rule, the results its field couldn't hold and those an error made null
// (`WriteLosses`), and its type.
let mut cuts: Vec<(String, String, super::edit::WriteLosses, FieldType)> = Vec::new();
// Parsing against the fields separates a measurement failure from a stale rule. The latter
// may still be skipped below, but an ambiguous area must never disable a valid rule.
let metadata = rustgis_data::Dataset::new(l.dataset.name.clone(), l.dataset.geometry_type, l.dataset.fields.clone());
Expand All @@ -268,43 +263,14 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
return Err(format!("{}: {message}", l.dataset.name));
}
// Calculation rules, in order. Those that no longer read, by name, said once the edit is kept.
let mut unread: Vec<String> = Vec::new();
let layer = l.dataset.name.clone();
for rule in l.design.rules.iter().filter(|r| r.kind == RuleKind::Calculation) {
let Some(fi) = l.dataset.field_index(&rule.field) else { continue };
let ty = l.dataset.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text);
// A rule that no longer reads (a hand-edited file, one past the length limit from an
// earlier version) is skipped rather than blocking every edit, and said.
let Ok(calc) = super::edit::Calculation::parse(&rule.expression, &metadata) else {
// Said only for an edit with rows: one with none (a deletion) computes nothing anyway.
if !rows.is_empty() {
unread.push(rule.name.clone());
}
continue;
};
// Counted as Calculate Field counts them.
// A change set may repeat a row: its losses are counted once.
let mut losses = super::edit::WriteLosses::once_per_row();
for r in &rows {
let v = losses.write(*r, calc.eval_or_fault(&l.dataset, *r), ty);
if let Some(cell) = l.dataset.features.get_mut(*r).and_then(|f| f.attrs.get_mut(fi)) {
*cell = v;
}
}
let name = l.dataset.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default();
cuts.push((rule.name.clone(), name, losses, ty));
}
// Validation. Domains and contingent values are checked on the fields an edit changed (all
// of a new feature's), so a value set before the domain doesn't block unrelated edits.
let constraints: Vec<(String, String, rustgis_data::query::Expr)> = l
.design
.rules
.iter()
.filter(|r| r.kind == RuleKind::Constraint)
.filter_map(|rule| {
rustgis_data::query::parse(&rule.expression, &metadata).ok().map(|e| (rule.name.clone(), rule.expression.clone(), e))
})
.collect();
// What each calculation rule's whole-number field cut: the rule and the field's name. Each
// rule's cuts are said, even when a later rule writes the same field: it may read them.
// With them, per rule, the results its field couldn't hold and those an error made null
// (`WriteLosses`), and its type.
let (cuts, unread) = calculation_rules(&l.design, &mut l.dataset, &metadata, &rows, 0);
// Validation (`refusal`), against each row's state before the first edit.
let constraints = constraint_rules(&l.design, &metadata);
let mut original = HashMap::new();
if !l.design.domains.is_empty() || !l.design.contingent.is_empty() {
// A row edited more than once still validates against its state before the first edit.
Expand All @@ -315,35 +281,8 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
}
}
for r in &rows {
let before = original.get(r).copied().flatten().zip(l.dataset.features.get(*r));
let touched = |fi: usize| before.is_none_or(|(old, now)| old.attrs.get(fi) != now.attrs.get(fi));
for d in &l.design.domains {
if let Some(fi) = l.dataset.field_index(&d.field).filter(|fi| touched(*fi)) {
let v = l.dataset.value(*r, fi);
if !d.allows(v) {
return Err(format!("{} isn't allowed in {} (its domain)", v, d.field));
}
}
}
for c in &l.design.contingent {
let vals: Vec<&Value> =
c.fields.iter().map(|f| l.dataset.field_index(f).map(|fi| l.dataset.value(*r, fi)).unwrap_or(&Value::Null)).collect();
let any_touched = c.fields.iter().any(|f| l.dataset.field_index(f).is_some_and(touched));
if !any_touched || vals.iter().all(|v| v.is_null()) {
continue;
}
let ok = c.combos.iter().any(|combo| {
combo.iter().zip(&vals).all(|(want, got)| want.is_null() || got.is_null() || want.to_string() == got.to_string())
});
if !ok {
let shown: Vec<String> = vals.iter().map(|v| v.to_string()).collect();
return Err(format!("{} isn't a valid combination of {} ({})", shown.join(", "), c.fields.join(", "), c.name));
}
}
for (name, expr, e) in &constraints {
if !rustgis_data::query::eval(e, &l.dataset, *r) {
return Err(format!("the edit breaks the rule {name} ({expr})"));
}
if let Some(refused) = refusal(&l.design, &l.dataset, &constraints, *r, original.get(r).copied().flatten(), 0) {
return Err(refused);
}
}
// Archive and counts.
Expand Down Expand Up @@ -396,6 +335,111 @@ pub(crate) fn apply_with<B: Borrow<Feature>>(s: &mut Session, id: u32, changes:
Ok(())
}

/// What each calculation rule of `design` cut, by rule: its name, its field's, what writing its
/// results lost (counted once per row, as Calculate Field counts them) and the field's type.
type RuleCuts = Vec<(String, String, super::edit::WriteLosses, FieldType)>;

/// Runs `design`'s calculation rules, in order, on `rows` of `ds`, whose first row has `offset`
/// rows before it in the layer (0 but for the Calculate Field preview's one-row copy, #2837):
/// what each cut, and the names of the rules that no longer read against `metadata` (the
/// layer's fields), skipped rather than blocking every edit.
pub(crate) fn calculation_rules(
design: &rustgis_map::design::Design,
ds: &mut rustgis_data::Dataset,
metadata: &rustgis_data::Dataset,
rows: &[usize],
offset: usize,
) -> (RuleCuts, Vec<String>) {
let (mut cuts, mut unread) = (Vec::new(), Vec::new());
for rule in design.rules.iter().filter(|r| r.kind == RuleKind::Calculation) {
let Some(fi) = ds.field_index(&rule.field) else { continue };
let ty = ds.fields.get(fi).map(|f| f.ty).unwrap_or(FieldType::Text);
// A rule that no longer reads (a hand-edited file, one past the length limit from an
// earlier version) is skipped rather than blocking every edit, and said.
let Ok(calc) = super::edit::Calculation::parse(&rule.expression, metadata) else {
// Said only for an edit with rows: one with none (a deletion) computes nothing anyway.
if !rows.is_empty() {
unread.push(rule.name.clone());
}
continue;
};
// Counted as Calculate Field counts them.
// A change set may repeat a row: its losses are counted once.
let mut losses = super::edit::WriteLosses::once_per_row();
for r in rows {
let v = losses.write(*r, calc.eval_or_fault_at(ds, *r, offset), ty);
if let Some(cell) = ds.features.get_mut(*r).and_then(|f| f.attrs.get_mut(fi)) {
*cell = v;
}
}
let name = ds.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default();
cuts.push((rule.name.clone(), name, losses, ty));
}
(cuts, unread)
}

/// `design`'s constraint rules that read against `metadata` (the layer's fields): name,
/// expression as written, and parsed.
pub(crate) fn constraint_rules(
design: &rustgis_map::design::Design,
metadata: &rustgis_data::Dataset,
) -> Vec<(String, String, rustgis_data::query::Expr)> {
design
.rules
.iter()
.filter(|r| r.kind == RuleKind::Constraint)
.filter_map(|rule| {
rustgis_data::query::parse(&rule.expression, metadata).ok().map(|e| (rule.name.clone(), rule.expression.clone(), e))
})
.collect()
}

/// The error an edit of row `r` of `ds` is refused with, by the first of `design`'s checks it
/// breaks: a domain or an allowed combination of values, on the fields the edit changed from
/// `before` (all of a new feature's), so a value set before the domain doesn't block unrelated
/// edits, then the `constraints` ([`constraint_rules`]). `offset` as [`calculation_rules`] reads
/// it.
pub(crate) fn refusal(
design: &rustgis_map::design::Design,
ds: &rustgis_data::Dataset,
constraints: &[(String, String, rustgis_data::query::Expr)],
r: usize,
before: Option<&Feature>,
offset: usize,
) -> Option<String> {
let before = before.zip(ds.features.get(r));
let touched = |fi: usize| before.is_none_or(|(old, now)| old.attrs.get(fi) != now.attrs.get(fi));
for d in &design.domains {
if let Some(fi) = ds.field_index(&d.field).filter(|fi| touched(*fi)) {
let v = ds.value(r, fi);
if !d.allows(v) {
return Some(format!("{} isn't allowed in {} (its domain)", v, d.field));
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}
}
}
for c in &design.contingent {
let vals: Vec<&Value> = c.fields.iter().map(|f| ds.field_index(f).map(|fi| ds.value(r, fi)).unwrap_or(&Value::Null)).collect();
let any_touched = c.fields.iter().any(|f| ds.field_index(f).is_some_and(touched));
if !any_touched || vals.iter().all(|v| v.is_null()) {
continue;
}
let ok = c
.combos
.iter()
.any(|combo| combo.iter().zip(&vals).all(|(want, got)| want.is_null() || got.is_null() || want.to_string() == got.to_string()));
if !ok {
let shown: Vec<String> = vals.iter().map(|v| v.to_string()).collect();
return Some(format!("{} isn't a valid combination of {} ({})", shown.join(", "), c.fields.join(", "), c.name));
}
}
for (name, expr, e) in constraints {
if !rustgis_data::query::matches_at(e, ds, r, &rustgis_data::query::Env::default(), offset) {
return Some(format!("the edit breaks the rule {name} ({expr})"));
}
}
None
}

/// Registers data-design and editing commands, including opt-in exact-coordinate polygon moves.
/// Feature edits share `apply` for rules, archives and counts inside the session transaction.
pub fn commands() -> Vec<C> {
Expand Down
63 changes: 55 additions & 8 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1645,32 +1645,67 @@ pub fn check_calculation(expr: &str, ds: &rustgis_data::Dataset) -> Result<(), S
Calculation::parse(expr, ds).map(|_| ())
}

/// One row of a Calculate Field preview: the value the field would get, and what writing it
/// loses, the kind the run's notices count.
/// One row of a Calculate Field preview: the value the field would get, what writing it loses,
/// the kind the run's notices count, and the layer's check that would refuse the edit (#2837).
#[derive(Clone, Debug, PartialEq)]
pub struct CalculationPreview {
pub row: usize,
pub value: Value,
pub lost: Option<PreviewLoss>,
/// What the run would refuse the edit with, when the layer's checks refuse this row: its
/// error, word for word, for the checks the preview runs. An edit whose area reads are
/// ambiguous is refused before them, with that error instead, which the preview doesn't give.
pub refused: Option<String>,
}

/// What Calculate Field would write with `expr` into field `field` of `rows` (rows past the end
/// left out), parsed once as [`check_calculation`] reads it: the error is the same.
/// left out), parsed once as [`check_calculation`] reads it: the error is the same. With a
/// layer's `design`, each row also says which of its checks would refuse it: its calculation
/// rules, then its domains, allowed combinations and constraint rules, run as an edit runs them
/// (`apply_with`, in `design`) on a copy of that row alone, its value written, which reads
/// `@row_number` as the layer's row. The copy holds that row alone, with the layer's fields and
/// coordinate system: nothing else of the layer is copied. Not previewed: an edit refused because
/// an area it reads is ambiguous, which needs the whole edit's geometry.
pub fn preview_calculation(
expr: &str,
ds: &rustgis_data::Dataset,
field: usize,
rows: &[usize],
design: Option<&rustgis_map::design::Design>,
) -> Result<Vec<CalculationPreview>, String> {
use rustgis_map::design::RuleKind;
let calc = Calculation::parse(expr, ds)?;
let ty = ds.fields.get(field).map(|f| f.ty).ok_or("no field")?;
// Only these can refuse a row: a layer with calculation rules alone refuses none.
let layer_checks =
design.filter(|d| !d.domains.is_empty() || !d.contingent.is_empty() || d.rules.iter().any(|r| r.kind == RuleKind::Constraint));
// The layer's fields, which its rules are read against, and its constraint rules: only for a
// layer with checks.
let prepared = layer_checks.map(|d| {
let metadata = rustgis_data::Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone());
let constraints = super::design::constraint_rules(d, &metadata);
(d, metadata, constraints)
});
// What the layer's checks would refuse the edit of `row` with, `value` written.
let refusal_of = |row: usize, value: &Value| {
let (d, metadata, constraints) = prepared.as_ref()?;
let before = ds.features.row(row)?.to_feature();
// Shares the layer's rows (an `Arc`) until `one.features` is replaced on the next line, so
// no row of the layer is copied: keep that replacement before any change to `one`.
let mut one = ds.clone();
one.features = vec![before.clone()].into();
one.features.set_value(0, field, value.clone());
let _ = super::design::calculation_rules(d, &mut one, metadata, &[0], row);
super::design::refusal(d, &one, constraints, 0, Some(&before), row)
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
};
Ok(rows
.iter()
.filter(|r| **r < ds.features.len())
.map(|&row| {
let Held { value, cut, other } = held(calc.eval_or_fault(ds, row), ty);
let refusal = refusal_of(row, &value);
// The error is why the value is null; a cut alone says what it took.
CalculationPreview { row, value, lost: other.or(cut).and_then(Loss::previewed) }
CalculationPreview { row, value, lost: other.or(cut).and_then(Loss::previewed), refused: refusal }
})
.collect())
}
Expand Down Expand Up @@ -1730,8 +1765,20 @@ impl Calculation {

/// Row `r`'s result, with the error that made it null, if one did.
pub(crate) fn eval_or_fault(&self, ds: &rustgis_data::Dataset, r: usize) -> (Value, Option<rustgis_data::query::Fault>) {
self.eval_or_fault_at(ds, r, 0)
}

/// [`Calculation::eval_or_fault`] for a row with `offset` rows before `ds`'s first in its
/// layer ([`rustgis_data::query::value_or_fault_at`]). `Calc` reads no row number, so it takes
/// no offset.
pub(crate) fn eval_or_fault_at(
&self,
ds: &rustgis_data::Dataset,
r: usize,
offset: usize,
) -> (Value, Option<rustgis_data::query::Fault>) {
match self {
Calculation::Expr(e) => rustgis_data::query::value_or_fault(e, ds, r, &rustgis_data::query::Env::default()),
Calculation::Expr(e) => rustgis_data::query::value_or_fault_at(e, ds, r, &rustgis_data::query::Env::default(), offset),
Calculation::Calc(c) => c.eval_or_fault(ds, r),
}
}
Expand Down Expand Up @@ -2095,7 +2142,7 @@ mod tests {
}
let (n, whole, day) = (0, 1, 3);
let preview = |e: &str, field: usize, rows: &[usize]| -> Vec<(usize, Value, Option<PreviewLoss>)> {
let previewed = preview_calculation(e, &ds, field, rows).unwrap_or_else(|e| panic!("{e}"));
let previewed = preview_calculation(e, &ds, field, rows, None).unwrap_or_else(|e| panic!("{e}"));
previewed.into_iter().map(|p| (p.row, p.value, p.lost)).collect()
};
// The rows asked for, in their order; a clean result loses nothing.
Expand All @@ -2118,8 +2165,8 @@ mod tests {
assert_eq!(preview("n", n, &[]), vec![]);
assert_eq!(preview("n", n, &[3, 4, 99]), vec![(3, Value::Float(4.0), None)]);
// An expression that doesn't read: the check's error.
assert_eq!(preview_calculation("nosuch * 2", &ds, n, &[0]), Err(check_calculation("nosuch * 2", &ds).unwrap_err()));
assert!(preview_calculation("n", &ds, 9, &[0]).is_err(), "no such field");
assert_eq!(preview_calculation("nosuch * 2", &ds, n, &[0], None), Err(check_calculation("nosuch * 2", &ds).unwrap_err()));
assert!(preview_calculation("n", &ds, 9, &[0], None).is_err(), "no such field");
}

/// The run's notices still count each loss as before the preview shared their reading: a
Expand Down
Loading
Loading