diff --git a/core/engine/src/compiled/graph/plan/run/typed.rs b/core/engine/src/compiled/graph/plan/run/typed.rs index ed3e8b1e..7e1c651f 100644 --- a/core/engine/src/compiled/graph/plan/run/typed.rs +++ b/core/engine/src/compiled/graph/plan/run/typed.rs @@ -105,9 +105,8 @@ impl<'a> Run<'_, 'a> { true if distinct && op.heavy => Some("distinct"), _ => None, }; - let unkeyed = unkeyed.or_else(|| { - (keyed.is_none() && self.doomed(seg, op, positions)).then_some("doomed") - }); + let unkeyed = unkeyed + .or_else(|| (keyed.is_none() && self.doomed(seg, op, positions)).then_some("doomed")); if let Some(why) = unkeyed { match Census::on() { true => self.fell(why, seg, units, positions, local), @@ -421,7 +420,11 @@ impl<'a> Run<'_, 'a> { false => { let outputs = op.present.len(); let writes: Vec> = (0..rules) - .map(|rule| (0..outputs).filter(|&index| table.writes(rule, index)).collect()) + .map(|rule| { + (0..outputs) + .filter(|&index| table.writes(rule, index)) + .collect() + }) .collect(); let mut bits = vec![vec![0u64; count.div_ceil(64)]; outputs]; for (at, &code) in codes.iter().enumerate() { diff --git a/core/engine/src/compiled/lowered.rs b/core/engine/src/compiled/lowered.rs index d0fac786..58af5523 100644 --- a/core/engine/src/compiled/lowered.rs +++ b/core/engine/src/compiled/lowered.rs @@ -155,7 +155,10 @@ impl Exports { }; ends.push(end); } - Store::Text { offsets: ends, data } + Store::Text { + offsets: ends, + data, + } } _ => return Err(offsets), }; @@ -174,7 +177,8 @@ impl Exports { let (offsets, data) = self.dicts.get(usize::from(slot.dict()?))?; let at = usize::try_from(code).ok()?; data.get( - usize::try_from(*offsets.get(at)?).ok()?..usize::try_from(*offsets.get(at + 1)?).ok()?, + usize::try_from(*offsets.get(at)?).ok()? + ..usize::try_from(*offsets.get(at + 1)?).ok()?, ) } diff --git a/core/engine/src/compiled/policy/columnar/evaluate.rs b/core/engine/src/compiled/policy/columnar/evaluate.rs index ea9b3026..d03036d7 100644 --- a/core/engine/src/compiled/policy/columnar/evaluate.rs +++ b/core/engine/src/compiled/policy/columnar/evaluate.rs @@ -35,8 +35,7 @@ impl PolicyPlan { fn safe(&self, artifact: &EvalArtifact) -> &[Iteration] { self.safe.get_or_init(|| { let mut found: Vec = Vec::new(); - for (name, path, owner) in self.flats().filter_map(|plan| plan.iteration.as_ref()) - { + for (name, path, owner) in self.flats().filter_map(|plan| plan.iteration.as_ref()) { if !found.iter().any(|(_, p, _)| p == path) { found.push((name.clone(), path.clone(), owner.clone())); } @@ -48,11 +47,7 @@ impl PolicyPlan { }) } - fn entities<'a>( - &self, - artifact: &EvalArtifact, - sheet: &Sheet<'a>, - ) -> Vec> { + fn entities<'a>(&self, artifact: &EvalArtifact, sheet: &Sheet<'a>) -> Vec> { self.safe(artifact) .iter() .filter_map(|(name, path, owner)| { @@ -150,13 +145,16 @@ impl PolicyPlan { } fn delegating(&self) -> bool { - let refused = - |plan: &&BlockPlan| plan.native().is_none() && plan.table.is_none() && plan.member.is_none(); - let roots = self.flats() + let refused = |plan: &&BlockPlan| { + plan.native().is_none() && plan.table.is_none() && plan.member.is_none() + }; + let roots = self + .flats() .filter(refused) .filter(|plan| plan.iteration.is_none()) .count(); - let members = self.flats() + let members = self + .flats() .filter(refused) .filter_map(|plan| plan.iteration.as_ref().map(|(_, path, _)| path)) .map(|path| { @@ -187,15 +185,11 @@ impl PolicyPlan { return true; } if plan.member.is_none() && plan.table.is_none() { - return self.rule(block) - .kind - .write_sites() - .iter() - .all(|site| { - site.path - .strip_prefix(prefix.as_str()) - .is_some_and(|f| !f.is_empty()) - }); + return self.rule(block).kind.write_sites().iter().all(|site| { + site.path + .strip_prefix(prefix.as_str()) + .is_some_and(|f| !f.is_empty()) + }); } let Some((programs, keys)) = Pass::block(self, block) else { return false; @@ -228,7 +222,8 @@ impl PolicyPlan { pub(super) fn readers_safe(&self, artifact: &EvalArtifact, path: &str) -> bool { (0..self.blocks.rules.len()).all(|block| { let rule = self.rule(block); - if self.flat(block) + if self + .flat(block) .iteration .as_ref() .is_some_and(|(_, own, _)| own.as_ref() == path) @@ -399,7 +394,11 @@ impl PolicyPlan { Ok((store, _)) if shared => { let _ = stores[row].set(store); } - Ok(_) if unresolved.as_ref().is_some_and(|unresolved| unresolved[row]) => { + Ok(_) + if unresolved + .as_ref() + .is_some_and(|unresolved| unresolved[row]) => + { fallback[row] = true; } Ok(_) => {} @@ -444,7 +443,8 @@ impl PolicyPlan { listed: RefCell::new(Vec::new()), casts: RefCell::new(Vec::new()), present: self.gates.iter().map(|_| OnceCell::new()).collect(), - owners: self.flats() + owners: self + .flats() .map(|plan| plan.iteration.as_ref().map(|(_, path, _)| path.clone())) .collect(), }; diff --git a/core/engine/src/compiled/policy/columnar/fuse.rs b/core/engine/src/compiled/policy/columnar/fuse.rs index b95c51fa..d18ab58c 100644 --- a/core/engine/src/compiled/policy/columnar/fuse.rs +++ b/core/engine/src/compiled/policy/columnar/fuse.rs @@ -159,7 +159,11 @@ impl Gather { Cell::Constant(_) => {} Cell::Computed => { if taken { - lists[*target].push(values.get(next).map_or(Variable::Null, |leaf| leaf.get(row))); + lists[*target].push( + values + .get(next) + .map_or(Variable::Null, |leaf| leaf.get(row)), + ); } next += 1; } @@ -177,9 +181,14 @@ impl Gather { Normalizer::cast(&leaf).unwrap_or(leaf) }; if self.computed > 0 { - let mut columns: Vec> = vec![Vec::with_capacity(count); self.fields.len()]; + let mut columns: Vec> = + vec![Vec::with_capacity(count); self.fields.len()]; for (row, mask) in masks.iter().enumerate() { - for ((column, list), scalar) in columns.iter_mut().zip(gather(*mask, row)).zip(&self.scalars) { + for ((column, list), scalar) in columns + .iter_mut() + .zip(gather(*mask, row)) + .zip(&self.scalars) + { column.push(value(*scalar, list)); } } @@ -203,9 +212,11 @@ impl Gather { }) }) .collect(); - let mut dicts: Vec> = vec![Vec::with_capacity(distinct.len()); self.fields.len()]; + let mut dicts: Vec> = + vec![Vec::with_capacity(distinct.len()); self.fields.len()]; for mask in &distinct { - for ((dict, list), scalar) in dicts.iter_mut().zip(gather(*mask, 0)).zip(&self.scalars) { + for ((dict, list), scalar) in dicts.iter_mut().zip(gather(*mask, 0)).zip(&self.scalars) + { dict.push(value(*scalar, list)); } } @@ -213,7 +224,12 @@ impl Gather { .into_iter() .zip(&self.scalars) .map(|(values, scalar)| match scalar { - true => typed(codes.iter().map(|&code| values[code as usize].clone()).collect()), + true => typed( + codes + .iter() + .map(|&code| values[code as usize].clone()) + .collect(), + ), false => Leaf::typed(Array::coded(codes.clone(), Rc::new(Dict::Any(values)))), }) .collect() @@ -796,10 +812,9 @@ impl<'s, 'a> Pass<'s, 'a> { } fn merge(&self, items: &mut [Item], entry: Span, unit: &Unit) -> bool { - let Some(target) = items - .iter() - .rposition(|item| item.domain == Some(unit.entity) && item.gate == self.plan.gate(entry.block)) - else { + let Some(target) = items.iter().rposition(|item| { + item.domain == Some(unit.entity) && item.gate == self.plan.gate(entry.block) + }) else { return false; }; let effects = |block: usize| self.plan.fusions.effects(self.plan, block); @@ -862,70 +877,69 @@ impl<'s, 'a> Pass<'s, 'a> { if self.shared { return Err("shared rows"); } - let (entity, programs, writes) = - match (&plan.flat(block).table, &plan.rule(block).kind) { - (Some(table), BlockKind::DecisionTable(ir)) => { - let entity = match self.owners[block] { - Some(_) if Exports::enabled() => { - let at = self.entity_of(block).ok_or("member table without entity")?; - self.supported(at, block, rows) - .then_some(Some(at)) - .ok_or("member table unsupported")? - } - Some(_) => return Err("member table untyped"), - None => None, - }; - if len != 2 { - return Err("table split select"); + let (entity, programs, writes) = match (&plan.flat(block).table, &plan.rule(block).kind) { + (Some(table), BlockKind::DecisionTable(ir)) => { + let entity = match self.owners[block] { + Some(_) if Exports::enabled() => { + let at = self.entity_of(block).ok_or("member table without entity")?; + self.supported(at, block, rows) + .then_some(Some(at)) + .ok_or("member table unsupported")? } - if !self.quiet(block) { - return Err("table cells read fields"); - } - let readable = match plan.fusions.table(block, ir) { - Some(false) if !Exports::enabled() => return Err("table not typable"), - Some(readable) => readable, - None => return Err("table not typable"), - }; - let writes: Vec<(Arc, bool)> = table - .picked() - .iter() - .map(|o| (o.field.clone(), readable)) - .collect(); - (entity, table.programs(), writes) + Some(_) => return Err("member table untyped"), + None => None, + }; + if len != 2 { + return Err("table split select"); } - (Some(_), _) => return Err("table plan on other block"), - (None, _) => { - let entity = match self.owners[block] { - Some(_) => { - let at = self.entity_of(block).ok_or("member block without entity")?; - self.supported(at, block, rows) - .then_some(Some(at)) - .ok_or("member block unsupported")? - } - None => None, - }; - let native = match entity { - Some(_) => Pass::native(plan, block).ok_or("member block not native")?, - None if plan.flat(block).iterated => return Err("iterated block"), - None => plan.flat(block).native().ok_or("block not native")?, - }; - match (native, len) { - (Native::Expression { key, program }, 1) => { - (entity, vec![program.as_ref()], vec![(key.clone(), true)]) - } - (Native::Match { ir, .. }, 2) if self.quiet(block) => { - (entity, Pass::programs(native), vec![(ir.key.clone(), true)]) - } - (Native::Match { .. }, 2) => return Err("match arm values read fields"), - (Native::Assertion { ir, conditions }, 1) => ( - entity, - conditions.iter().collect(), - vec![(ir.output.clone(), false)], - ), - _ => return Err("split select and commit"), - } + if !self.quiet(block) { + return Err("table cells read fields"); } - }; + let readable = match plan.fusions.table(block, ir) { + Some(false) if !Exports::enabled() => return Err("table not typable"), + Some(readable) => readable, + None => return Err("table not typable"), + }; + let writes: Vec<(Arc, bool)> = table + .picked() + .iter() + .map(|o| (o.field.clone(), readable)) + .collect(); + (entity, table.programs(), writes) + } + (Some(_), _) => return Err("table plan on other block"), + (None, _) => { + let entity = match self.owners[block] { + Some(_) => { + let at = self.entity_of(block).ok_or("member block without entity")?; + self.supported(at, block, rows) + .then_some(Some(at)) + .ok_or("member block unsupported")? + } + None => None, + }; + let native = match entity { + Some(_) => Pass::native(plan, block).ok_or("member block not native")?, + None if plan.flat(block).iterated => return Err("iterated block"), + None => plan.flat(block).native().ok_or("block not native")?, + }; + match (native, len) { + (Native::Expression { key, program }, 1) => { + (entity, vec![program.as_ref()], vec![(key.clone(), true)]) + } + (Native::Match { ir, .. }, 2) if self.quiet(block) => { + (entity, Pass::programs(native), vec![(ir.key.clone(), true)]) + } + (Native::Match { .. }, 2) => return Err("match arm values read fields"), + (Native::Assertion { ir, conditions }, 1) => ( + entity, + conditions.iter().collect(), + vec![(ir.output.clone(), false)], + ), + _ => return Err("split select and commit"), + } + } + }; let plain = programs.iter().all(|program| { let p = program.program(); !(p.writes_env || p.chain || p.opaque() || p.rows) @@ -992,7 +1006,11 @@ impl<'s, 'a> Pass<'s, 'a> { .map(|leaf| leaf.truths(count)) .collect(); let values: Vec> = leaves.by_ref().take(gather.computed).collect(); - for (key, leaf) in gather.fields.iter().zip(gather.leaves(&conds, &values, count)) { + for (key, leaf) in gather + .fields + .iter() + .zip(gather.leaves(&conds, &values, count)) + { match member { None => self.write(key, leaf, rows), Some((at, kids)) => self.member_write(at, key, leaf, kids), diff --git a/core/engine/src/compiled/policy/columnar/host.rs b/core/engine/src/compiled/policy/columnar/host.rs index 9f273287..835aed87 100644 --- a/core/engine/src/compiled/policy/columnar/host.rs +++ b/core/engine/src/compiled/policy/columnar/host.rs @@ -85,7 +85,9 @@ impl<'s, 'a> Pass<'s, 'a> { true => self.plan.commit(block, positions, &mut self.state), } if let Some(began) = began { - let why = self.plan.flat(block) + let why = self + .plan + .flat(block) .refused() .map_or_else(|| "native".to_string(), Refused::to_string); Census::record( diff --git a/core/engine/src/compiled/policy/columnar/refs.rs b/core/engine/src/compiled/policy/columnar/refs.rs index cce1dec0..5b16a68a 100644 --- a/core/engine/src/compiled/policy/columnar/refs.rs +++ b/core/engine/src/compiled/policy/columnar/refs.rs @@ -56,7 +56,8 @@ impl PolicyPlan { !iterated && !written }) }; - let safe = |field: &ReferenceField| !field.array || self.readers_safe(artifact, &field.path); + let safe = + |field: &ReferenceField| !field.array || self.readers_safe(artifact, &field.path); if Census::on() { let why = match (flat, fields.iter().all(free), fields.iter().all(safe)) { (false, _, _) => "nested or dated", @@ -87,9 +88,17 @@ impl PolicyPlan { } } - fn located(pool: Option, items: Option, row: usize, text: &str) -> Option { + fn located( + pool: Option, + items: Option, + row: usize, + text: &str, + ) -> Option { let (pool, (child, fields)) = (pool?, items?); - let ids = fields.iter().find(|(name, _)| *name == "id").map(|(_, c)| *c)?; + let ids = fields + .iter() + .find(|(name, _)| *name == "id") + .map(|(_, c)| *c)?; let (a, b) = pool.range(row)?; (a..b).rev().find(|&item| { child.valid(item) @@ -179,12 +188,19 @@ impl PolicyPlan { return refused("empty pool"); } let fields = sheet.entities[pool].gathered(&index); - return Some(Entity::linked(path, entry, frame, fields, Some((pool, index)))); + return Some(Entity::linked( + path, + entry, + frame, + fields, + Some((pool, index)), + )); } - if self - .flats() - .any(|plan| plan.iteration.as_ref().is_some_and(|(_, own, _)| *own == target)) - { + if self.flats().any(|plan| { + plan.iteration + .as_ref() + .is_some_and(|(_, own, _)| *own == target) + }) { return refused("pool without entity"); } let Some((child, fields)) = items else { diff --git a/core/engine/src/compiled/policy/columnar/sheet.rs b/core/engine/src/compiled/policy/columnar/sheet.rs index a974cd47..5959d337 100644 --- a/core/engine/src/compiled/policy/columnar/sheet.rs +++ b/core/engine/src/compiled/policy/columnar/sheet.rs @@ -112,7 +112,8 @@ impl<'a> Sheet<'a> { let children = entity.frame.children; for field in entity.fields.iter_mut().filter(|field| field.input) { if let Some(at) = schema.dates_at(&format!("{}.{}", entity.path, field.name)) { - field.leaf = Dated::leaf(field.leaf.clone(), children, schema.dating(at, &texts)); + field.leaf = + Dated::leaf(field.leaf.clone(), children, schema.dating(at, &texts)); } } } @@ -227,7 +228,7 @@ impl<'a> Sheet<'a> { Entry { path, leaf, - present, + present, input: true, dead: false, }, diff --git a/core/engine/src/compiled/policy/columnar/typed.rs b/core/engine/src/compiled/policy/columnar/typed.rs index 4b68b6a2..cd8416f1 100644 --- a/core/engine/src/compiled/policy/columnar/typed.rs +++ b/core/engine/src/compiled/policy/columnar/typed.rs @@ -427,13 +427,7 @@ impl<'s, 'a> Pass<'s, 'a> { Typed::Ran(group.units, faulted) } - fn rows( - &self, - group: &TypedGroup, - sources: &[Source<'a>], - rows: &[usize], - full: bool, - ) -> Rows { + fn rows(&self, group: &TypedGroup, sources: &[Source<'a>], rows: &[usize], full: bool) -> Rows { if !group.lists.is_empty() || rows.len() < Dedup::MIN { return Rows::Plain; } @@ -527,7 +521,9 @@ impl<'s, 'a> Pass<'s, 'a> { } Source::Field(field) => Some(self.sheet.entities[entity?].view(*field)), Source::RawField(field) => self.sheet.entities[entity?].raw_view(*field), - Source::CastField(field) => Normalizer::cast(&self.sheet.entities[entity?].view(*field)), + Source::CastField(field) => { + Normalizer::cast(&self.sheet.entities[entity?].view(*field)) + } Source::List(..) | Source::Listed(_) | Source::Spread(_) | Source::Absent => None, } }; diff --git a/core/engine/src/compiled/policy/entity.rs b/core/engine/src/compiled/policy/entity.rs index 8c0fc023..ba3566c6 100644 --- a/core/engine/src/compiled/policy/entity.rs +++ b/core/engine/src/compiled/policy/entity.rs @@ -414,7 +414,7 @@ impl<'a> Entity<'a> { leaf: Leaf::typed(builder.finish()), present: Some(bits.into()), input: false, - }; + }; self.fields[at] = merged; } } diff --git a/core/engine/src/compiled/policy/rooted.rs b/core/engine/src/compiled/policy/rooted.rs index 48a5ecfd..f1594446 100644 --- a/core/engine/src/compiled/policy/rooted.rs +++ b/core/engine/src/compiled/policy/rooted.rs @@ -120,7 +120,9 @@ impl Rooted { key != path && !key.starts_with('$') && !key.contains('[') - && owned.as_deref().is_none_or(|owned| !DotPath::overlaps(key, owned)) + && owned + .as_deref() + .is_none_or(|owned| !DotPath::overlaps(key, owned)) }) } @@ -206,7 +208,10 @@ impl Rooted { .iter() .zip(plans) .map(|(rule, plan)| { - let iteration = plan.iteration.as_ref().filter(|(_, path, _)| single(path))?; + let iteration = plan + .iteration + .as_ref() + .filter(|(_, path, _)| single(path))?; let (rule, plan) = Self::block(rule, iteration)?; let gate = match gates.iter().position(|gate| *gate == iteration.1) { Some(gate) => gate, @@ -219,21 +224,25 @@ impl Rooted { }) .collect(); let foreign = |gate: usize, path: &str| { - rules.iter().zip(plans).enumerate().any(|(block, (rule, plan))| { - let own = rooted[block].as_ref().is_some_and(|r| r.gate == gate); - let listed = plan - .iteration - .as_ref() - .is_some_and(|(_, list, _)| !own && related(list, path)); - let writes = !own - && plan.iteration.is_none() - && rule - .kind - .write_sites() - .iter() - .any(|site| related(&site.path, path)); - listed || writes - }) + rules + .iter() + .zip(plans) + .enumerate() + .any(|(block, (rule, plan))| { + let own = rooted[block].as_ref().is_some_and(|r| r.gate == gate); + let listed = plan + .iteration + .as_ref() + .is_some_and(|(_, list, _)| !own && related(list, path)); + let writes = !own + && plan.iteration.is_none() + && rule + .kind + .write_sites() + .iter() + .any(|site| related(&site.path, path)); + listed || writes + }) }; let clashing: Vec = gates .iter() diff --git a/core/engine/src/compiled/policy/validator.rs b/core/engine/src/compiled/policy/validator.rs index f3f91af4..dd655528 100644 --- a/core/engine/src/compiled/policy/validator.rs +++ b/core/engine/src/compiled/policy/validator.rs @@ -169,7 +169,9 @@ impl InputSchema { let dates = self.dates(); DeclaredDates::rewrite_fields(input, |key, value| { if self.ref_targets.contains(key) { - DeclaredDates::rewrite_items(value, |item| dates.convert_entity(item, key, 0, texts)) + DeclaredDates::rewrite_items(value, |item| { + dates.convert_entity(item, key, 0, texts) + }) } else if self.roots.contains(key) { dates.convert_entity(value, key, 0, texts) } else { @@ -742,11 +744,12 @@ impl Sureness<'_> { || matches!(column.variable(at), Variable::Bool(_) | Variable::Null) } PropertyTypeIr::Enum(values) if Self::string(column) => { - column.bytes(at).is_some_and(|bytes| { - values.iter().any(|v| v.as_bytes() == bytes) - }) || column - .text(at) - .is_none_or(|text| values.iter().any(|v| v.as_ref() == text)) + column + .bytes(at) + .is_some_and(|bytes| values.iter().any(|v| v.as_bytes() == bytes)) + || column + .text(at) + .is_none_or(|text| values.iter().any(|v| v.as_ref() == text)) } PropertyTypeIr::Enum(values) => match column.variable(at) { Variable::Null => true, @@ -765,8 +768,7 @@ impl Sureness<'_> { other => zen_expression::DateValue::is(&other), }, PropertyTypeIr::Reference { .. } => { - self.resolved - && matches!(column.variable(at), Variable::String(_) | Variable::Null) + self.resolved && matches!(column.variable(at), Variable::String(_) | Variable::Null) } } } @@ -861,19 +863,25 @@ impl Sureness<'_> { } fn fits(&self, kind: &PropertyTypeIr, value: &Variable, depth: usize) -> Option { - let named = |known: &dyn Fn(&str) -> bool| value.as_rc_str().is_some_and(|text| known(&text)); + let named = + |known: &dyn Fn(&str) -> bool| value.as_rc_str().is_some_and(|text| known(&text)); Some(match kind { PropertyTypeIr::String => matches!(value, Variable::String(_)), PropertyTypeIr::Number => matches!(value, Variable::Number(_)), PropertyTypeIr::Boolean => matches!(value, Variable::Bool(_)), - PropertyTypeIr::Enum(values) => named(&|text| values.iter().any(|v| v.as_ref() == text)), + PropertyTypeIr::Enum(values) => { + named(&|text| values.iter().any(|v| v.as_ref() == text)) + } PropertyTypeIr::Date => match value { Variable::String(text) => text.is_empty() || self.date_fits(text), other => zen_expression::DateValue::is(other), }, PropertyTypeIr::Reference { .. } => return None, PropertyTypeIr::Relationship { target } => { - match (self.schema.entities.contains_key(target), self.schema.dictionaries.get(target)) { + match ( + self.schema.entities.contains_key(target), + self.schema.dictionaries.get(target), + ) { (false, Some(dict)) => named(&|text| dict.values().any(|v| v.as_ref() == text)), _ => self.entity_fits(target, value, depth)?, } @@ -1049,8 +1057,7 @@ impl Sureness<'_> { let model = self.schema.entities.get(target)?; let mut bad: Option> = None; for (name, field) in fields { - if let Some(prop) = model.properties.iter().find(|p| p.name.as_ref() == *name) - { + if let Some(prop) = model.properties.iter().find(|p| p.name.as_ref() == *name) { Self::merged(&mut bad, self.doubts(prop, field, len)); } } @@ -1118,9 +1125,11 @@ impl Sureness<'_> { .collect(), ) } - (true, _) => { - Self::kept((0..len).map(|at| !self.property(prop, column, at)).collect()) - } + (true, _) => Self::kept( + (0..len) + .map(|at| !self.property(prop, column, at)) + .collect(), + ), } } diff --git a/core/engine/src/compiled/shred.rs b/core/engine/src/compiled/shred.rs index ef03e623..f3ec9c1a 100644 --- a/core/engine/src/compiled/shred.rs +++ b/core/engine/src/compiled/shred.rs @@ -341,7 +341,11 @@ impl Normalizer { } } - fn coded_lists(column: &zen_expression::lane::Column, values: &[Variable], rows: usize) -> Seen { + fn coded_lists( + column: &zen_expression::lane::Column, + values: &[Variable], + rows: usize, + ) -> Seen { let Values::Dict { keys, .. } = column.values else { return Seen::Mixed; }; @@ -1520,7 +1524,9 @@ impl<'a> Listing<'a> { for (name, leaf) in listing.fields.iter_mut() { let Some(dating) = name .split('.') - .try_fold(dated.dating().clone(), |dating, segment| dating.field(segment)) + .try_fold(dated.dating().clone(), |dating, segment| { + dating.field(segment) + }) else { continue; }; @@ -1561,7 +1567,12 @@ impl<'a> Listing<'a> { }) } - fn coded(column: &Column<'_>, keys: &[i32], values: &[Variable], owners: usize) -> Option> { + fn coded( + column: &Column<'_>, + keys: &[i32], + values: &[Variable], + owners: usize, + ) -> Option> { let distinct = Self::shredded(&Column::new(Values::Any(values)), values.len())?; let mut offsets: Vec = Vec::with_capacity(owners + 1); offsets.push(0); @@ -1573,8 +1584,16 @@ impl<'a> Listing<'a> { let code = keys.get(row).and_then(|key| usize::try_from(*key).ok()); match code.filter(|_| column.valid(row)) { Some(code) => { - if distinct.hosted.as_ref().is_some_and(|bits| Bits::get(bits, code)) { - Bits::set(hosted.get_or_insert_with(|| vec![0u64; owners.div_ceil(64)]), row, true); + if distinct + .hosted + .as_ref() + .is_some_and(|bits| Bits::get(bits, code)) + { + Bits::set( + hosted.get_or_insert_with(|| vec![0u64; owners.div_ceil(64)]), + row, + true, + ); } match distinct.frame.range(code) { Some((a, b)) => picks.extend(a..b), @@ -1912,10 +1931,14 @@ impl Normalizer { pub(crate) fn castable(leaf: &Leaf) -> Option { let (_, values) = Self::scalars(leaf)?; - let first = values.iter().find(|value| !matches!(value, Variable::Null))?; + let first = values + .iter() + .find(|value| !matches!(value, Variable::Null))?; let fits = |value: &Variable| match (first, value) { (_, Variable::Null) => true, - (Variable::Bool(_), Variable::Bool(_)) | (Variable::String(_), Variable::String(_)) => true, + (Variable::Bool(_), Variable::Bool(_)) | (Variable::String(_), Variable::String(_)) => { + true + } (Variable::Number(_), Variable::Number(n)) => Scaled::parts(n).is_some(), _ => false, }; diff --git a/core/engine/src/compiled/table/profile.rs b/core/engine/src/compiled/table/profile.rs index 1a5da5c9..abd40d29 100644 --- a/core/engine/src/compiled/table/profile.rs +++ b/core/engine/src/compiled/table/profile.rs @@ -222,7 +222,11 @@ impl<'t> TableIr<'t> { if !self.gathers() { return None; } - let inputs: Vec<&InputIr> = self.inputs.iter().filter(|input| self.used(input.id)).collect(); + let inputs: Vec<&InputIr> = self + .inputs + .iter() + .filter(|input| self.used(input.id)) + .collect(); let rules = self .rules .iter() @@ -244,7 +248,10 @@ impl<'t> TableIr<'t> { }) .collect(); Some(TableSpec { - inputs: inputs.iter().map(|input| input.field.map(str::to_string)).collect(), + inputs: inputs + .iter() + .map(|input| input.field.map(str::to_string)) + .collect(), outputs: Vec::new(), rules, hit: Typed::Strict, diff --git a/core/engine/tests/date_kernels.rs b/core/engine/tests/date_kernels.rs index f575741c..1061ee81 100644 --- a/core/engine/tests/date_kernels.rs +++ b/core/engine/tests/date_kernels.rs @@ -9,7 +9,9 @@ use zen_engine::policy::{EvaluateRequest, PolicyWorkspace}; use zen_engine::{diagnostics, EngineVersion, EvaluationOptions}; const PATH: &str = "main"; -const UNITS: [&str; 8] = ["year", "quarter", "month", "week", "day", "hour", "minute", "second"]; +const UNITS: [&str; 8] = [ + "year", "quarter", "month", "week", "day", "hour", "minute", "second", +]; const ZONES: [&str; 8] = [ "UTC", "America/New_York", @@ -40,17 +42,33 @@ fn policy() -> String { add(format!("d().diff(c.a, '{unit}')")); add(format!("c.b.diff(c.t, '{unit}')")); add(format!("c.a.diff('2024-02-29T12:00:00', '{unit}')")); - for method in ["isSame", "isBefore", "isAfter", "isSameOrBefore", "isSameOrAfter"] { + for method in [ + "isSame", + "isBefore", + "isAfter", + "isSameOrBefore", + "isSameOrAfter", + ] { add(format!("c.a.{method}(c.b, '{unit}')")); } - add(format!("c.a.startOf('{unit}').diff(c.b.endOf('{unit}'), 'minute')")); - add(format!("c.a.add(3, '{unit}').diff(c.a.sub(1, '{unit}'), 'hour')")); + add(format!( + "c.a.startOf('{unit}').diff(c.b.endOf('{unit}'), 'minute')" + )); + add(format!( + "c.a.add(3, '{unit}').diff(c.a.sub(1, '{unit}'), 'hour')" + )); } add("d().add(-24, 'hour').diff(c.a, 'minute')".into()); add("c.a.add(1, 'day').diff(c.b, 'hour')".into()); add("c.a.diff(c.b)".into()); add("c.a.diff(c.n)".into()); - for method in ["isSame", "isBefore", "isAfter", "isSameOrBefore", "isSameOrAfter"] { + for method in [ + "isSame", + "isBefore", + "isAfter", + "isSameOrBefore", + "isSameOrAfter", + ] { add(format!("c.a.{method}(c.b)")); add(format!("c.b.{method}(c.t)")); add(format!("d().{method}(c.a, 'day')")); @@ -59,15 +77,40 @@ fn policy() -> String { add(format!("c.a.format('{pattern}')")); } add("c.b.format()".into()); - for method in ["isValid", "isLeapYear", "isToday", "isYesterday", "isTomorrow"] { + for method in [ + "isValid", + "isLeapYear", + "isToday", + "isYesterday", + "isTomorrow", + ] { add(format!("c.a.{method}()")); add(format!("d(c.t).{method}()")); } - for method in ["second", "minute", "hour", "day", "dayOfYear", "week", "weekday", "month", "quarter", "year", "timestamp"] { + for method in [ + "second", + "minute", + "hour", + "day", + "dayOfYear", + "week", + "weekday", + "month", + "quarter", + "year", + "timestamp", + ] { add(format!("c.a.{method}() + c.b.{method}()")); } - for zone in ["America/New_York", "Asia/Kolkata", "UTC", "Australia/Lord_Howe"] { - add(format!("c.a.tz('{zone}').hour() * 100 + c.a.tz('{zone}').minute()")); + for zone in [ + "America/New_York", + "Asia/Kolkata", + "UTC", + "Australia/Lord_Howe", + ] { + add(format!( + "c.a.tz('{zone}').hour() * 100 + c.a.tz('{zone}').minute()" + )); add(format!("c.b.tz('{zone}').format('%Y-%m-%d %H:%M')")); add(format!("c.a.tz('{zone}').diff(c.b, 'month')")); } @@ -124,7 +167,9 @@ fn rows() -> Vec { } } let distinct = rows.len(); - (0..distinct * 24).map(|at| rows[(at / 3) % distinct].clone()).collect() + (0..distinct * 24) + .map(|at| rows[(at / 3) % distinct].clone()) + .collect() } #[test] @@ -159,7 +204,10 @@ fn typed_date_methods_match_the_general_functions_in_every_zone() { let (typed_paths, typed) = run(true); let (_, general) = run(false); diagnostics::set_typed(true); - assert!(typed_paths.typed > 0 && typed_paths.hosted == 0, "{zone}: {typed_paths:?}"); + assert!( + typed_paths.typed > 0 && typed_paths.hosted == 0, + "{zone}: {typed_paths:?}" + ); for (at, (got, want)) in typed.iter().zip(&general).enumerate() { assert_eq!(got, want, "zone {zone} row {at}: input {}", rows[at]); } diff --git a/core/engine/tests/policy_parity.rs b/core/engine/tests/policy_parity.rs index 566d0b21..0870cf74 100644 --- a/core/engine/tests/policy_parity.rs +++ b/core/engine/tests/policy_parity.rs @@ -114,7 +114,10 @@ fn goals_match( fn columns_match_document(document: Value, rows: Vec) -> Paths { let workspace = |version| { let mut ws = PolicyWorkspace::new().with_version(version); - ws.set_policy(PATH, serde_json::from_value(document.clone()).expect("policy json")); + ws.set_policy( + PATH, + serde_json::from_value(document.clone()).expect("policy json"), + ); ws }; let (old, new) = (workspace(EngineVersion::V1), workspace(EngineVersion::V2)); @@ -571,11 +574,31 @@ const CHECKED_LISTS: &str = r#"{ #[test] fn values_a_model_refuses_inside_lists_report_what_version_one_reports() { - let kinds = [json!("goods"), json!("service"), json!("rental"), json!(3), Value::Null]; - let dates = [json!("2024-02-29"), json!("soon"), json!("2023-02-30"), Value::Null, json!(""), json!(20240101)]; + let kinds = [ + json!("goods"), + json!("service"), + json!("rental"), + json!(3), + Value::Null, + ]; + let dates = [ + json!("2024-02-29"), + json!("soon"), + json!("2023-02-30"), + Value::Null, + json!(""), + json!(20240101), + ]; let grades = [json!("new"), json!("used"), json!("broken"), json!(false)]; let tags = [json!("a"), json!("b"), json!("c"), json!(1)]; - for (bad_kind, bad_date, bad_grade, bad_tag) in [(0, 0, 0, 0), (7, 0, 0, 0), (0, 5, 0, 0), (0, 0, 9, 0), (0, 0, 0, 11), (13, 17, 19, 23)] { + for (bad_kind, bad_date, bad_grade, bad_tag) in [ + (0, 0, 0, 0), + (7, 0, 0, 0), + (0, 5, 0, 0), + (0, 0, 9, 0), + (0, 0, 0, 11), + (13, 17, 19, 23), + ] { let odd = |every: usize, n: usize| every > 0 && n % every == every - 1; let pick = |pool: &[Value], bad: bool, n: usize| match bad { true => pool[2 + n % (pool.len() - 2)].clone(), @@ -626,10 +649,26 @@ fn dictionary_columns_inside_lists_are_checked_like_plain_ones() { let old = workspace(&policies, EngineVersion::V1); let new = workspace(&policies, EngineVersion::V2); for (kind_pool, date_pool, root_pool) in [ - (vec!["goods", "service"], vec!["2024-02-29", "2025-03-20T10:15:30Z", ""], vec!["web", "store"]), - (vec!["goods", "service", "rental"], vec!["2024-02-29", ""], vec!["web", "store"]), - (vec!["goods", "service"], vec!["2024-02-29", "soon", "2023-02-30"], vec!["web", "store"]), - (vec!["goods", "service"], vec!["2024-02-29"], vec!["web", "phone", "store"]), + ( + vec!["goods", "service"], + vec!["2024-02-29", "2025-03-20T10:15:30Z", ""], + vec!["web", "store"], + ), + ( + vec!["goods", "service", "rental"], + vec!["2024-02-29", ""], + vec!["web", "store"], + ), + ( + vec!["goods", "service"], + vec!["2024-02-29", "soon", "2023-02-30"], + vec!["web", "store"], + ), + ( + vec!["goods", "service"], + vec!["2024-02-29"], + vec!["web", "phone", "store"], + ), ] { let rows = 80usize; let mut offsets = vec![0i32]; @@ -639,10 +678,20 @@ fn dictionary_columns_inside_lists_are_checked_like_plain_ones() { let (date_offsets, date_data) = text(&date_pool); let (root_offsets, root_data) = text(&root_pool); let kind_keys: Vec = (0..items) - .map(|n| if n % 11 == 5 { -1 } else { ((n * 7 + n / 5) % kind_pool.len()) as i32 }) + .map(|n| { + if n % 11 == 5 { + -1 + } else { + ((n * 7 + n / 5) % kind_pool.len()) as i32 + } + }) + .collect(); + let date_keys: Vec = (0..items) + .map(|n| ((n * 3 + n / 7) % date_pool.len()) as i32) + .collect(); + let root_keys: Vec = (0..rows) + .map(|i| ((i * 5 + i / 9) % root_pool.len()) as i32) .collect(); - let date_keys: Vec = (0..items).map(|n| ((n * 3 + n / 7) % date_pool.len()) as i32).collect(); - let root_keys: Vec = (0..rows).map(|i| ((i * 5 + i / 9) % root_pool.len()) as i32).collect(); let mut date_valid = vec![u64::MAX; items.div_ceil(64)]; (0..items) .filter(|n| n % 6 == 1) @@ -653,7 +702,10 @@ fn dictionary_columns_inside_lists_are_checked_like_plain_ones() { "kind", Column::new(Values::Dict { keys: &kind_keys, - values: Dictionary::Text { offsets: &kind_offsets, data: &kind_data }, + values: Dictionary::Text { + offsets: &kind_offsets, + data: &kind_data, + }, }), ), ( @@ -661,7 +713,10 @@ fn dictionary_columns_inside_lists_are_checked_like_plain_ones() { Column::with_validity( Values::Dict { keys: &date_keys, - values: Dictionary::Text { offsets: &date_offsets, data: &date_data }, + values: Dictionary::Text { + offsets: &date_offsets, + data: &date_data, + }, }, &date_valid, 0, @@ -669,15 +724,27 @@ fn dictionary_columns_inside_lists_are_checked_like_plain_ones() { ), ("qty", Column::new(Values::I64(&qty))), ]; - let item = Column::new(Values::Struct { fields: &fields, len: items }); - let lines = Column::new(Values::List { offsets: &offsets, child: Dictionary::Column(&item) }); + let item = Column::new(Values::Struct { + fields: &fields, + len: items, + }); + let lines = Column::new(Values::List { + offsets: &offsets, + child: Dictionary::Column(&item), + }); let root = Column::new(Values::Dict { keys: &root_keys, - values: Dictionary::Text { offsets: &root_offsets, data: &root_data }, + values: Dictionary::Text { + offsets: &root_offsets, + data: &root_data, + }, }); let placed = Column::new(Values::Dict { keys: &date_keys[..rows], - values: Dictionary::Text { offsets: &date_offsets, data: &date_data }, + values: Dictionary::Text { + offsets: &date_offsets, + data: &date_data, + }, }); let columns = Columns::new(rows) .column("order.kind", root) @@ -717,7 +784,10 @@ fn declared_dates_of_objects_inside_list_items_match_version_one() { json!("2025-02-01"), ]; for (bad, empty) in [(0, 0), (0, 5), (17, 0)] { - let date = |n: usize| match (bad > 0 && n % bad == bad - 1, empty > 0 && n % empty == empty - 1) { + let date = |n: usize| match ( + bad > 0 && n % bad == bad - 1, + empty > 0 && n % empty == empty - 1, + ) { (true, _) => json!("soon"), (_, true) => json!(""), _ => dates[n % dates.len()].clone(), @@ -773,7 +843,13 @@ fn declared_dates_in_lists_without_member_blocks_stay_dates() { {expression: "trip.years", value: "map(filter(trip.stops, #.at != null), #.at.year())"}, ], }"#; - let dates = [json!("2024-02-29"), json!("2024/01/05"), json!("2025-03-20T23:30:00+05:00"), Value::Null, json!("2023")]; + let dates = [ + json!("2024-02-29"), + json!("2024/01/05"), + json!("2025-03-20T23:30:00+05:00"), + Value::Null, + json!("2023"), + ]; let rows: Vec = (0..80) .map(|i| { let stops: Vec = (0..1 + i % 3) @@ -935,7 +1011,9 @@ fn referenced_rows(count: usize, keys: &[Value]) -> Vec { (0..count) .map(|i| { let lines: Vec = (0..i % 3) - .map(|j| json!({"amount": 20 * (i + j) % 300, "code": (["food", "general"])[j % 2]})) + .map( + |j| json!({"amount": 20 * (i + j) % 300, "code": (["food", "general"])[j % 2]}), + ) .collect(); let mut order = json!({"fee": 5 + i % 7, "exempt": i % 5 == 0, "lines": lines}); if !keys[i % keys.len()].is_null() { @@ -955,7 +1033,14 @@ fn references_to_a_pool_resolve_by_columns_and_run_typed() { #[test] fn references_that_are_missing_unknown_or_not_text_match_version_one() { - let keys = [json!("NY"), json!("XX"), Value::Null, json!(7), json!("CA"), json!("")]; + let keys = [ + json!("NY"), + json!("XX"), + Value::Null, + json!(7), + json!("CA"), + json!(""), + ]; columns_match_version_one(&[(PATH, REFERENCED)], referenced_rows(72, &keys)); let rows: Vec = (0..24) .map(|i| match i % 3 { @@ -1089,7 +1174,11 @@ const SETTLEMENT: &str = r#"{ ], }"#; -fn settlement_rows(count: usize, lines: impl Fn(usize) -> Option, sellers: impl Fn(usize) -> Option) -> Vec { +fn settlement_rows( + count: usize, + lines: impl Fn(usize) -> Option, + sellers: impl Fn(usize) -> Option, +) -> Vec { let ids = ["s1", "s2", "s3", "s4"]; let dates = ["2024-02-29", "2025-01-15", "2023-07-01"]; (0..count) @@ -1144,8 +1233,14 @@ fn member_blocks_reading_lists_that_are_empty_null_or_missing_match_version_one( columns_match_version_one(&policies, settlement_rows(60, |_| Some(0), |i| Some(i % 3))); columns_match_version_one(&policies, settlement_rows(60, |i| Some(i % 4), |_| Some(0))); columns_match_version_one(&policies, settlement_rows(60, |i| Some(i % 4), |_| Some(1))); - columns_match_version_one(&policies, settlement_rows(60, |i| (i % 3 != 0).then_some(i % 4), |i| Some(1 + i % 3))); - columns_match_version_one(&policies, settlement_rows(60, |i| Some(1 + i % 4), |i| (i % 4 != 1).then_some(i % 3))); + columns_match_version_one( + &policies, + settlement_rows(60, |i| (i % 3 != 0).then_some(i % 4), |i| Some(1 + i % 3)), + ); + columns_match_version_one( + &policies, + settlement_rows(60, |i| Some(1 + i % 4), |i| (i % 4 != 1).then_some(i % 3)), + ); columns_match_version_one(&policies, settlement_rows(40, |_| Some(7), |_| Some(9))); let mut rows = settlement_rows(40, |i| Some(i % 4), |i| Some(1 + i % 3)); rows.push(json!({"order": {"country": "DE", "lines": null, "sellers": [{"id": "s1", "country": "DE"}]}})); @@ -1224,7 +1319,9 @@ const TENANT: &str = r#"{ }"#; fn tenant_rows(address: impl Fn(usize) -> Option) -> Vec { - let labels = ["a-b-c", "O'Neil", "12", "retail", "A1", "ok", "none", "x", "high"]; + let labels = [ + "a-b-c", "O'Neil", "12", "retail", "A1", "ok", "none", "x", "high", + ]; let plans = ["basic", "trial", "plus", "premium"]; (0..54) .map(|i| { @@ -1261,7 +1358,10 @@ fn blocks_on_a_single_relationship_beside_a_list_match_version_one_for_every_goa let mut broken = tenant_rows(present); broken[4]["tenant"]["limit"] = Value::Null; broken[9]["tenant"]["loans"][0]["plan"] = json!("gold"); - broken[11]["tenant"].as_object_mut().expect("tenant").remove("income"); + broken[11]["tenant"] + .as_object_mut() + .expect("tenant") + .remove("income"); let goal_sets: [&[&str]; 9] = [ &[], &["loan.flag"], @@ -1273,7 +1373,13 @@ fn blocks_on_a_single_relationship_beside_a_list_match_version_one_for_every_goa &["address.eligible", "loan.adjusted"], &["tenant.risk", "loan.meta.review"], ]; - for rows in [tenant_rows(present), tenant_rows(sparse), tenant_rows(nulled), tenant_rows(|_| None), broken] { + for rows in [ + tenant_rows(present), + tenant_rows(sparse), + tenant_rows(nulled), + tenant_rows(|_| None), + broken, + ] { let built = Built::nested(&rows) .or_else(|| Built::lists(&rows)) .or_else(|| Built::new(&rows)) @@ -1331,7 +1437,10 @@ const REPORTED: &str = r#"{ ], }"#; -fn reported_rows(report: impl Fn(usize) -> Option, contact: impl Fn(usize) -> Option) -> Vec { +fn reported_rows( + report: impl Fn(usize) -> Option, + contact: impl Fn(usize) -> Option, +) -> Vec { let tiers = ["gold", "silver", "basic"]; (0..48) .map(|i| { @@ -1432,7 +1541,10 @@ fn single_relationships_that_are_missing_null_or_empty_match_version_one_for_eve reported_rows(partial, |i| Some(full_contact(i))), reported_rows(partial, sparse), reported_rows(|_| None, |_| None), - reported_rows(|i| (i % 2 == 0).then(|| full_report(i)), |i| (i % 3 == 0).then(|| full_contact(i))), + reported_rows( + |i| (i % 2 == 0).then(|| full_report(i)), + |i| (i % 3 == 0).then(|| full_contact(i)), + ), ]; for rows in &sets { each_goal(REPORTED, rows, &REPORTED_GOALS); @@ -1448,13 +1560,19 @@ fn single_relationships_holding_what_the_model_refuses_match_version_one() { rows[7]["customer"]["contact"]["email"] = json!(false); rows[9]["customer"]["limit"] = Value::Null; rows[11]["customer"]["report"]["score"] = Value::Null; - rows[13]["customer"].as_object_mut().expect("customer").remove("tier"); + rows[13]["customer"] + .as_object_mut() + .expect("customer") + .remove("tier"); each_goal(REPORTED, &rows, &REPORTED_GOALS); } #[test] fn a_relationship_given_under_its_entity_name_does_not_stand_in_for_the_related_object() { - let mut rows = reported_rows(|i| (i % 2 == 0).then(|| full_report(i)), |i| Some(full_contact(i))); + let mut rows = reported_rows( + |i| (i % 2 == 0).then(|| full_report(i)), + |i| Some(full_contact(i)), + ); for (i, row) in rows.iter_mut().enumerate() { if i % 4 == 1 { row["creditReport"] = full_report(i); @@ -1479,10 +1597,15 @@ const CONFIGURED: &str = r#"{ ], }"#; -fn configured_rows(cfg: impl Fn(usize) -> Option, extra: impl Fn(usize) -> Option) -> Vec { +fn configured_rows( + cfg: impl Fn(usize) -> Option, + extra: impl Fn(usize) -> Option, +) -> Vec { (0..40) .map(|i| { - let items: Vec = (0..i % 4).map(|j| json!({"v": (i * 3 + j * 5) % 23})).collect(); + let items: Vec = (0..i % 4) + .map(|j| json!({"v": (i * 3 + j * 5) % 23})) + .collect(); let mut row = json!({"cap": i % 5, "o": {"items": items}}); if let Some(cfg) = cfg(i) { row["cfg"] = cfg; @@ -1528,7 +1651,12 @@ fn global_single_relationships_that_are_missing_null_or_partial_match_version_on 2 => Some(json!({"bonus": null})), _ => Some(json!({"bonus": i % 3})), }; - for rows in [configured_rows(cfg, extra), configured_rows(full, extra), configured_rows(cfg, |_| None), configured_rows(full, |_| None)] { + for rows in [ + configured_rows(cfg, extra), + configured_rows(full, extra), + configured_rows(cfg, |_| None), + configured_rows(full, |_| None), + ] { each_goal(CONFIGURED, &rows, &CONFIGURED_GOALS); } } @@ -1550,14 +1678,17 @@ fn single_relationship_blocks_the_columns_cannot_alias_match_version_one() { {expression: "customer.flag", value: "customer.report.above > 3"}, ], }"#; - let rows: Vec = reported_rows(|i| (i % 5 != 0).then(|| json!({"score": i % 9, "bankrupt": i % 2 == 0})), |_| None) - .into_iter() - .enumerate() - .map(|(i, mut row)| { - row["customer"]["scores"] = json!([i % 4, 7, i % 11]); - row - }) - .collect(); + let rows: Vec = reported_rows( + |i| (i % 5 != 0).then(|| json!({"score": i % 9, "bankrupt": i % 2 == 0})), + |_| None, + ) + .into_iter() + .enumerate() + .map(|(i, mut row)| { + row["customer"]["scores"] = json!([i % 4, 7, i % 11]); + row + }) + .collect(); let table = r#"{ models: {customer: {tier: "string", limit: "number", report: "creditReport"}, creditReport: {score: "number", bankrupt: "boolean"}}, blocks: [ @@ -1587,7 +1718,11 @@ const CARTED: &str = r#"{ ], }"#; -fn carted_rows(count: usize, items: impl Fn(usize) -> Option, pool: impl Fn(usize) -> Option) -> Vec { +fn carted_rows( + count: usize, + items: impl Fn(usize) -> Option, + pool: impl Fn(usize) -> Option, +) -> Vec { (0..count) .map(|i| { let mut cart = json!({}); @@ -1658,8 +1793,12 @@ fn lists_of_references_that_are_missing_null_unknown_or_repeated_match_version_o 0 => None, 1 => Some(Value::Null), 2 => Some(json!([])), - 3 => Some(json!([{"id": "p1", "price": 2}, {"id": "p1", "price": 9}, {"id": "p2", "price": 4}, {"id": "p3", "price": 1}])), - 4 => Some(json!([{"price": 2}, {"id": "p1", "price": 9}, {"id": "p2", "price": 4}, {"id": "p3", "price": 1}])), + 3 => Some( + json!([{"id": "p1", "price": 2}, {"id": "p1", "price": 9}, {"id": "p2", "price": 4}, {"id": "p3", "price": 1}]), + ), + 4 => Some( + json!([{"price": 2}, {"id": "p1", "price": 9}, {"id": "p2", "price": 4}, {"id": "p3", "price": 1}]), + ), 5 => Some(json!([{"id": "p1"}, {"id": "p2", "price": 4}, {"id": "p3", "price": 1}])), _ => Some(product_pool(i)), }; @@ -1819,13 +1958,22 @@ fn cells_reading_already_demanded_and_other_computed_fields_match_version_one() each_goal( DEMANDED_CELLS, &rows, - &[&[], &["household.benefit"], &["household.extra"], &["household.band", "member.band"], &["household.tier"]], + &[ + &[], + &["household.benefit"], + &["household.extra"], + &["household.band", "member.band"], + &["household.tier"], + ], ); let mut broken = rows; broken[3]["household"]["income"] = Value::Null; broken[4]["household"]["size"] = json!(3); broken[9]["household"]["size"] = json!(3); - broken[7]["household"].as_object_mut().expect("household").remove("size"); + broken[7]["household"] + .as_object_mut() + .expect("household") + .remove("size"); columns_match_version_one(&[(PATH, DEMANDED_CELLS)], broken); } @@ -1914,13 +2062,22 @@ fn collect_tables_with_several_outputs_members_and_failures_match_version_one() each_goal( GATHERED, &rows, - &[&[], &["account.alerts"], &["account.decision"], &["account.flagged"], &["account.notes", "account.marks"]], + &[ + &[], + &["account.alerts"], + &["account.decision"], + &["account.flagged"], + &["account.notes", "account.marks"], + ], ); let mut broken = rows; broken[2]["account"]["volume"] = Value::Null; broken[5]["account"]["kind"] = json!(4); broken[9]["account"]["items"][0]["price"] = json!("x"); - broken[11]["account"].as_object_mut().expect("account").remove("structuring"); + broken[11]["account"] + .as_object_mut() + .expect("account") + .remove("structuring"); broken[13]["account"]["corridors"] = json!("many"); columns_match_version_one(&[(PATH, GATHERED)], broken); } @@ -2021,7 +2178,16 @@ fn optional_fields_given_as_null_left_out_or_wrongly_typed_match_version_one() { rows[6]["employer"]["bonus"] = json!("big"); rows[9]["employer"]["employees"][0]["extra"] = json!(true); columns_match_version_one(&[(PATH, SPARSE_FIELDS)], rows.clone()); - each_goal(SPARSE_FIELDS, &rows, &[&[], &["employee.rate"], &["employer.where"], &["employer.total"]]); + each_goal( + SPARSE_FIELDS, + &rows, + &[ + &[], + &["employee.rate"], + &["employer.where"], + &["employer.total"], + ], + ); } const TRANSITIVE_CELLS: &str = r#"{ @@ -2086,7 +2252,13 @@ fn cells_reading_fields_demanded_through_other_blocks_match_version_one() { each_goal( TRANSITIVE_CELLS, &rows, - &[&[], &["invoice.fee"], &["invoice.payment"], &["line.charge"], &["invoice.stage", "invoice.ok"]], + &[ + &[], + &["invoice.fee"], + &["invoice.payment"], + &["line.charge"], + &["invoice.stage", "invoice.ok"], + ], ); } @@ -2138,7 +2310,14 @@ fn collect_tables_with_first_hit_outputs_match_version_one() { each_goal( MIXED_GATHER, &rows, - &[&[], &["customer.outcome"], &["customer.level", "account.tier"], &["customer.summary"], &["customer.first"], &["account.label", "customer.levelText"]], + &[ + &[], + &["customer.outcome"], + &["customer.level", "account.tier"], + &["customer.summary"], + &["customer.first"], + &["account.label", "customer.levelText"], + ], ); } @@ -2184,7 +2363,8 @@ fn powers_with_computed_exponents_run_typed() { fn powers_with_fractional_missing_or_huge_exponents_match_version_one() { let rows: Vec = (0..80) .map(|i| { - let mut loan = json!({"amount": 10000 + 997 * i, "rate": 1 + (i % 9), "years": 5 + (i % 26)}); + let mut loan = + json!({"amount": 10000 + 997 * i, "rate": 1 + (i % 9), "years": 5 + (i % 26)}); match i % 6 { 0 => {} 1 => loan["step"] = Value::Null, @@ -2264,7 +2444,8 @@ fn nested_member_objects_validate_like_version_one() { }) .collect(); let deps = |rows: &mut Vec, at: usize| -> Value { - rows[at]["employer"]["employees"][0]["dependents"] = json!([{"relation": "child", "dob": "2010-01-01"}]); + rows[at]["employer"]["employees"][0]["dependents"] = + json!([{"relation": "child", "dob": "2010-01-01"}]); rows[at]["employer"]["employees"][0]["dependents"][0].clone() }; for (at, field, value) in [ @@ -2340,7 +2521,16 @@ fn membership_in_another_list_runs_typed() { fn membership_in_another_list_or_a_global_list_matches_version_one() { let mut rows = other_list_rows(); columns_match_version_one(&[(PATH, OTHER_LISTS)], rows.clone()); - each_goal(OTHER_LISTS, &rows, &[&[], &["claim.missing"], &["traveller.hazard"], &["claim.count", "claim.hazards"]]); + each_goal( + OTHER_LISTS, + &rows, + &[ + &[], + &["claim.missing"], + &["traveller.hazard"], + &["claim.count", "claim.hazards"], + ], + ); rows[3]["claim"]["received"] = Value::Null; rows[5]["hazardous"] = Value::Null; rows[7]["claim"]["received"] = json!(["police", null]); @@ -2376,7 +2566,14 @@ fn member_blocks_reading_root_dates_run_typed() { #[test] fn member_blocks_reading_root_dates_in_any_form_match_version_one() { - let starts = ["2025-03-20", "2025-03-20T23:30:00-05:00", "2024-02-29T12:00:00Z", "2025-01-01 10:00", "2025-13-01", ""]; + let starts = [ + "2025-03-20", + "2025-03-20T23:30:00-05:00", + "2024-02-29T12:00:00Z", + "2025-01-01 10:00", + "2025-13-01", + "", + ]; let rows: Vec = (0..72) .map(|i| { let travellers: Vec = (0..i % 3) diff --git a/core/engine/tests/typed_parity.rs b/core/engine/tests/typed_parity.rs index ebd274e8..338fa126 100644 --- a/core/engine/tests/typed_parity.rs +++ b/core/engine/tests/typed_parity.rs @@ -1071,7 +1071,11 @@ fn an_object_read_by_later_entries_runs_typed() { ("deep", "$.o.inner.deeper.t"), ], )]); - typed_and_kept(graph, composite_rows(), &["/o", "/count", "/first", "/label", "/deep"]); + typed_and_kept( + graph, + composite_rows(), + &["/o", "/count", "/first", "/label", "/deep"], + ); } #[test] @@ -1179,7 +1183,11 @@ fn an_object_of_flags_counted_by_a_later_entry_runs_typed() { typed_and_kept( graph, composite_rows(), - &["/eligibility/offers", "/eligibility/count", "/eligibility/any"], + &[ + "/eligibility/offers", + "/eligibility/count", + "/eligibility/any", + ], ); } @@ -1227,7 +1235,11 @@ fn member_chains_on_computed_objects_run_typed() { ("u", "$.o.a.zzz"), ], )]); - typed_and_kept(graph, composite_rows(), &["/o", "/p", "/q", "/r", "/t", "/u"]); + typed_and_kept( + graph, + composite_rows(), + &["/o", "/p", "/q", "/r", "/t", "/u"], + ); } #[test] @@ -1271,7 +1283,9 @@ fn closures_and_folds_over_an_array_literal_run_typed() { typed_and_kept( graph, composite_rows(), - &["/flags", "/count", "/doubled", "/kept", "/some", "/sum", "/in"], + &[ + "/flags", "/count", "/doubled", "/kept", "/some", "/sum", "/in", + ], ); } @@ -1291,7 +1305,11 @@ fn flatten_runs_typed() { let mut rows = composite_rows(); rows.push(json!({"x": 1, "y": 2, "s": "n", "flag": true, "items": null, "tags": null})); columns_keep_version_one( - chain(vec![entries("e", false, &[("a", "flatten([tags, items])")])]), + chain(vec![entries( + "e", + false, + &[("a", "flatten([tags, items])")], + )]), rows, &["/a"], ); @@ -1304,7 +1322,10 @@ fn an_array_feeds_a_later_node_like_version_1() { "n1", false, &[ - ("reasons", "filter([s, 'fixed', x > 1 ? 'big' : null], # != null)"), + ( + "reasons", + "filter([s, 'fixed', x > 1 ? 'big' : null], # != null)", + ), ("summary", "[`total ${x + y}`, s]"), ("n", "len($.reasons)"), ], @@ -1323,7 +1344,14 @@ fn an_array_feeds_a_later_node_like_version_1() { let paths = columns_keep_version_one( graph, composite_rows(), - &["/reasons", "/summary", "/first", "/count", "/has", "/decision"], + &[ + "/reasons", + "/summary", + "/first", + "/count", + "/has", + "/decision", + ], ); assert!(paths.typed > 0, "{paths:?}"); } @@ -1437,7 +1465,11 @@ fn a_value_compared_with_a_list_runs_typed() { }}), ); typed_like_version_one(table, rows.clone()); - for source in ["loc != frequent", "frequent == loc", "(frequent ?? []) != n"] { + for source in [ + "loc != frequent", + "frequent == loc", + "(frequent ?? []) != n", + ] { typed_like_version_one(expression(source), rows.clone()); } } @@ -1487,11 +1519,7 @@ fn a_collect_table_with_computed_outputs_runs_typed() { for path in [None, Some("hits"), Some("result.hits")] { let graph = collect_table(path, inputs.clone(), outputs.clone(), rules.clone()); let label = graph.to_string(); - let paths = columns_keep_version_one( - graph, - collect_rows(), - &["", "/hits", "/result/hits"], - ); + let paths = columns_keep_version_one(graph, collect_rows(), &["", "/hits", "/result/hits"]); assert!(paths.typed > 0 && paths.laned == 0, "{label}: {paths:?}"); } } @@ -1535,10 +1563,7 @@ fn a_division_that_overflows_compares_like_version_1() { #[test] fn a_failing_inner_filter_fails_under_an_outer_filter_that_keeps_nothing() { - let rows = vec![ - json!({"t": "a", "s": "q"}), - json!({"t": "b", "s": null}), - ]; + let rows = vec![json!({"t": "a", "s": "q"}), json!({"t": "b", "s": null})]; for source in [ "filter(filter([t], contains(null, '10%')), false)", "filter(filter([t, s], upper(#) != 'Q'), false)", @@ -1566,7 +1591,11 @@ fn a_closure_over_a_missing_list_fails_even_with_a_fallback() { #[test] fn an_index_beyond_any_list_fails_like_version_1() { - for source in ["[][79228162514264337593543950335]", "[x, 2][1e28]", "[x, 2][3]"] { + for source in [ + "[][79228162514264337593543950335]", + "[x, 2][1e28]", + "[x, 2][3]", + ] { columns_match_version_one(expression(source), composite_rows()); } } @@ -1809,17 +1838,19 @@ fn text_work_on_one_column_runs_once_per_distinct_value_like_version_1() { #[test] fn text_cells_on_one_column_run_once_per_distinct_value_like_version_1() { - let graph = graph(json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { - "hitPolicy": "first", - "inputs": [{"id": "i0", "field": "lower(s)"}, {"id": "i1", "field": "n"}, {"id": "i2", "field": "t"}], - "outputs": [{"id": "o0", "field": "out"}, {"id": "o1", "field": "label"}], - "rules": [ - {"_id": "r0", "i0": "some(['acid', 'base'], contains($, #))", "i1": "> 1", "i2": "", "o0": "'r0'", "o1": "upper(s)"}, - {"_id": "r1", "i0": "contains($, 'toxic')", "i1": "", "i2": "time($) > 600", "o0": "'r1'", "o1": "lower(s) + '?'"}, - {"_id": "r2", "i0": "startsWith($, 'flam')", "i1": "", "i2": "", "o0": "'r2'", "o1": "'x'"}, - {"_id": "r3", "i0": "", "i1": "", "i2": "", "o0": "'r3'", "o1": "trim(s)"} - ] - }})); + let graph = graph( + json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": [{"id": "i0", "field": "lower(s)"}, {"id": "i1", "field": "n"}, {"id": "i2", "field": "t"}], + "outputs": [{"id": "o0", "field": "out"}, {"id": "o1", "field": "label"}], + "rules": [ + {"_id": "r0", "i0": "some(['acid', 'base'], contains($, #))", "i1": "> 1", "i2": "", "o0": "'r0'", "o1": "upper(s)"}, + {"_id": "r1", "i0": "contains($, 'toxic')", "i1": "", "i2": "time($) > 600", "o0": "'r1'", "o1": "lower(s) + '?'"}, + {"_id": "r2", "i0": "startsWith($, 'flam')", "i1": "", "i2": "", "o0": "'r2'", "o1": "'x'"}, + {"_id": "r3", "i0": "", "i1": "", "i2": "", "o0": "'r3'", "o1": "trim(s)"} + ] + }}), + ); for distinct in [false, true] { for count in [40, 300] { columns_match_version_one(graph.clone(), text_rows(count, distinct)); @@ -1872,11 +1903,19 @@ fn failing_rows_of_a_deduplicated_unit_fail_like_version_1() { columns_match_version_one(expression(source), rows.clone()); } let graph = chain(vec![ - entries("first", true, &[("t", "upper(s) + '!'"), ("r", "(d / m) * 100")]), + entries( + "first", + true, + &[("t", "upper(s) + '!'"), ("r", "(d / m) * 100")], + ), entries( "second", false, - &[("u", "lower(t) + string(n + 1)"), ("w", "r * n"), ("z", "t + string(r)")], + &[ + ("u", "lower(t) + string(n + 1)"), + ("w", "r * n"), + ("z", "t + string(r)"), + ], ), ]); columns_match_version_one(graph, rows); @@ -1897,15 +1936,17 @@ fn a_date_list_with_an_item_that_fails_fails_even_when_an_earlier_item_matches() ] { columns_match_version_one(expression(source), rows.clone()); } - let table = graph(json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { - "hitPolicy": "first", - "inputs": [{"id": "i0", "field": "d(ds)"}], - "outputs": [{"id": "o0", "field": "out"}], - "rules": [ - {"_id": "r0", "i0": "[d('2023-01-31'), d('2023-01-31'), d('2025-03-30 02:30', '+05:30')]", "o0": "'r0'"}, - {"_id": "r1", "i0": "", "o0": "'r1'"} - ] - }})); + let table = graph( + json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": [{"id": "i0", "field": "d(ds)"}], + "outputs": [{"id": "o0", "field": "out"}], + "rules": [ + {"_id": "r0", "i0": "[d('2023-01-31'), d('2023-01-31'), d('2025-03-30 02:30', '+05:30')]", "o0": "'r0'"}, + {"_id": "r1", "i0": "", "o0": "'r1'"} + ] + }}), + ); columns_match_version_one(table, rows); } @@ -2002,20 +2043,19 @@ fn a_batch_where_most_rows_fail_matches_version_1() { }) .collect(); columns_match_version_one(expression("n * 2 + m"), rows.clone()); - columns_match_version_one( - expression("len(s) > 2 ? n / (m + 1) : m"), - rows.clone(), + columns_match_version_one(expression("len(s) > 2 ? n / (m + 1) : m"), rows.clone()); + let table = graph( + json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": [{"id": "i0", "field": "s"}], + "outputs": [{"id": "o0", "field": "out"}], + "rules": [ + {"_id": "r0", "i0": "'k0'", "o0": "m + 1"}, + {"_id": "r1", "i0": "'k10'", "o0": "n * 3"}, + {"_id": "r2", "i0": "", "o0": "n * m"} + ] + }}), ); - let table = graph(json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { - "hitPolicy": "first", - "inputs": [{"id": "i0", "field": "s"}], - "outputs": [{"id": "o0", "field": "out"}], - "rules": [ - {"_id": "r0", "i0": "'k0'", "o0": "m + 1"}, - {"_id": "r1", "i0": "'k10'", "o0": "n * 3"}, - {"_id": "r2", "i0": "", "o0": "n * m"} - ] - }})); columns_match_version_one(table, rows); } @@ -2052,11 +2092,7 @@ fn legacy_dates_of_distinct_texts_run_typed() { _ => json!({"t": "", "u": "2025-01-01"}), }) .collect(); - for source in [ - "(date(t) - date(u)) / 3600", - "date(t) > date(u)", - "date(t)", - ] { + for source in ["(date(t) - date(u)) / 3600", "date(t) > date(u)", "date(t)"] { columns_match_version_one(expression(source), rows.clone()); } } @@ -2159,16 +2195,18 @@ fn numbers_at_the_edges_of_a_mantissa_keep_version_1_results() { } fn dollar_table(rules: Value) -> Value { - graph(json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { - "hitPolicy": "first", - "inputs": [ - {"id": "i0", "field": "level"}, - {"id": "i1"}, - {"id": "i2", "field": "$"} - ], - "outputs": [{"id": "o0", "field": "out"}], - "rules": rules - }})) + graph( + json!({"id": "node", "name": "node", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": [ + {"id": "i0", "field": "level"}, + {"id": "i1"}, + {"id": "i2", "field": "$"} + ], + "outputs": [{"id": "o0", "field": "out"}], + "rules": rules + }}), + ) } fn dollar_rows() -> Vec { @@ -2232,7 +2270,10 @@ fn membership_in_the_list_being_iterated_runs_typed() { json!({"strs": ["x", null]}), json!({"strs": ["q"]}), ]; - for source in ["filter(strs, upper(#) in strs)", "some(strs, lower(#) not in strs)"] { + for source in [ + "filter(strs, upper(#) in strs)", + "some(strs, lower(#) not in strs)", + ] { typed_like_version_one(expression(source), texts.clone()); } let mixed = vec![ @@ -2264,7 +2305,11 @@ fn membership_in_another_list_of_the_row_matches_version_one() { ] { columns_match_version_one(expression(source), rows.clone()); } - let clean: Vec = rows.iter().filter(|row| !row.to_string().contains("null")).cloned().collect(); + let clean: Vec = rows + .iter() + .filter(|row| !row.to_string().contains("null")) + .cloned() + .collect(); let paths = columns_match_version_one(expression("filter(a, not (# in b))"), clean.clone()); assert!(paths.typed > 0 && paths.laned == 0, "{paths:?}"); let paths = columns_match_version_one(expression("count(n, # in m)"), clean); diff --git a/core/expression/src/lane/columns.rs b/core/expression/src/lane/columns.rs index fe9a5f53..4db64894 100644 --- a/core/expression/src/lane/columns.rs +++ b/core/expression/src/lane/columns.rs @@ -1,7 +1,7 @@ use crate::context::EvaluationContext; +use crate::lane::foreign::{Decimal128, Float, Float64, Temporal}; use crate::lane::mask::{LaneSet, Lanes}; use crate::lane::program::{Binding, Kind}; -use crate::lane::foreign::{Decimal128, Float, Float64, Temporal}; use crate::lane::Bits; use crate::variable::Variable; use rust_decimal::Decimal; diff --git a/core/expression/src/lane/date/mod.rs b/core/expression/src/lane/date/mod.rs index 9421c930..eb1d3ddb 100644 --- a/core/expression/src/lane/date/mod.rs +++ b/core/expression/src/lane/date/mod.rs @@ -1155,7 +1155,12 @@ mod calendar_tests { #[test] fn remembered_dates_equal_parsed_ones() { - let zones = [Tz::UTC, Tz::America__New_York, Tz::Europe__Berlin, Tz::Australia__Lord_Howe]; + let zones = [ + Tz::UTC, + Tz::America__New_York, + Tz::Europe__Berlin, + Tz::Australia__Lord_Howe, + ]; let mut texts: Vec = vec![ "".into(), "nope".into(), @@ -1169,19 +1174,31 @@ mod calendar_tests { "2024-02-29T12:00:00.123456789+13:45 and far too long to be kept".into(), ]; for day in 0..40_000u32 { - texts.push(format!("{:04}-{:02}-{:02}", 1990 + day / 372, 1 + day / 31 % 12, 1 + day % 31)); + texts.push(format!( + "{:04}-{:02}-{:02}", + 1990 + day / 372, + 1 + day / 31 % 12, + 1 + day % 31 + )); } for round in 0..2 { for (at, text) in texts.iter().enumerate() { let tz = zones[(at + round) % zones.len()]; - let (kept, parsed) = (super::Date::remembered(text, tz), super::Date::from_text(text, tz)); + let (kept, parsed) = ( + super::Date::remembered(text, tz), + super::Date::from_text(text, tz), + ); assert_eq!(kept.0, parsed.0, "{text} in {tz}"); assert_eq!( kept.0.map(|at| at.timezone()), parsed.0.map(|at| at.timezone()), "{text} in {tz}" ); - assert_eq!(super::Date::remembered(text, tz).0, parsed.0, "{text} in {tz} again"); + assert_eq!( + super::Date::remembered(text, tz).0, + parsed.0, + "{text} in {tz} again" + ); } } } @@ -1204,8 +1221,10 @@ mod calendar_tests { _ => next(4_000_000_000) as i64 - 2_000_000_000, }; let (Some(a), Some(b)) = ( - Utc.timestamp_opt(seconds, next(1_000) as u32 * 1_000_000).single(), - Utc.timestamp_opt(seconds + apart, next(1_000) as u32 * 1_000_000).single(), + Utc.timestamp_opt(seconds, next(1_000) as u32 * 1_000_000) + .single(), + Utc.timestamp_opt(seconds + apart, next(1_000) as u32 * 1_000_000) + .single(), ) else { continue; }; diff --git a/core/expression/src/lane/mod.rs b/core/expression/src/lane/mod.rs index edee8e5b..6cd529de 100644 --- a/core/expression/src/lane/mod.rs +++ b/core/expression/src/lane/mod.rs @@ -23,11 +23,11 @@ pub use bits::Bits; #[doc(hidden)] pub use cells::{CellEnv, CellSet, Pieces}; pub use columns::{Column, Columns, Dictionary, Values}; -pub use foreign::{Decimal128, Float64, Temporal, TimeUnit}; #[doc(hidden)] pub use compile::{Hints, LaneCompiler}; #[doc(hidden)] pub use exec::{Context, Executor, Fallbacks, Fault, Frame}; +pub use foreign::{Decimal128, Float64, Temporal, TimeUnit}; #[doc(hidden)] pub use key::ShortKey; #[doc(hidden)] diff --git a/core/expression/src/typed/build.rs b/core/expression/src/typed/build.rs index 27914075..73731b12 100644 --- a/core/expression/src/typed/build.rs +++ b/core/expression/src/typed/build.rs @@ -1579,7 +1579,8 @@ impl<'h> Build<'h> { Func::Part(at) => Ins::Part { dst: self.fresh()?, a, - b: self.arg(*args.get(1).ok_or_else(|| Unsupported::new("typed: call"))?)?, + b: self + .arg(*args.get(1).ok_or_else(|| Unsupported::new("typed: call"))?)?, at: *at, }, f if f.mapping() => Ins::Map { diff --git a/core/expression/src/typed/date.rs b/core/expression/src/typed/date.rs index aaaedb83..d2285a07 100644 --- a/core/expression/src/typed/date.rs +++ b/core/expression/src/typed/date.rs @@ -1,6 +1,8 @@ -use crate::functions::{DateMethod, DeprecatedFunction, FunctionKind, InternalFunction, MethodKind}; -use crate::lane::date::helpers::date_time; +use crate::functions::{ + DateMethod, DeprecatedFunction, FunctionKind, InternalFunction, MethodKind, +}; use crate::lane::builtins::{Arg as Given, Builtin, Builtins, Dates, Out, RowContext}; +use crate::lane::date::helpers::date_time; use crate::lane::date::Date; use crate::lane::Bits; use crate::typed::exec::{Buf, Exec, Others, Reg}; @@ -179,8 +181,11 @@ impl<'e, 'x> Exec<'e, 'x> { return; } let mut skip = skip; - if let (Host::Legacy(DeprecatedFunction::Date), [DV::Text(text)], Rep::Dyn | Rep::Fix(0)) = - (host, views.as_slice(), *rep) + if let ( + Host::Legacy(DeprecatedFunction::Date), + [DV::Text(text)], + Rep::Dyn | Rep::Fix(0), + ) = (host, views.as_slice(), *rep) { let mut done = [0u64; Reg::WORDS]; let mut last: Option<(&[u8], i64)> = None; @@ -395,7 +400,8 @@ impl<'e, 'x> Exec<'e, 'x> { d.dates[i] = match last { Some((seen, shifted)) if seen == x - && seen.0.map(|at| at.timezone()) == x.0.map(|at| at.timezone()) => + && seen.0.map(|at| at.timezone()) + == x.0.map(|at| at.timezone()) => { shifted } diff --git a/core/expression/src/typed/exec.rs b/core/expression/src/typed/exec.rs index 957eb993..6f263450 100644 --- a/core/expression/src/typed/exec.rs +++ b/core/expression/src/typed/exec.rs @@ -1024,7 +1024,9 @@ impl<'e, 'x> Exec<'e, 'x> { let mut odd = [0u64; Reg::WORDS]; let t = &table; match op { - Cmp::Eq | Cmp::Ne => Self::scaled_k(am, asc, t, fits, o, &mut odd, |m, c| m == c), + Cmp::Eq | Cmp::Ne => { + Self::scaled_k(am, asc, t, fits, o, &mut odd, |m, c| m == c) + } Cmp::Lt => Self::scaled_k(am, asc, t, fits, o, &mut odd, |m, c| m < c), Cmp::Le => Self::scaled_k(am, asc, t, fits, o, &mut odd, |m, c| m <= c), Cmp::Gt => Self::scaled_k(am, asc, t, fits, o, &mut odd, |m, c| m > c), @@ -1340,8 +1342,16 @@ impl<'e, 'x> Exec<'e, 'x> { let mut table = [(0i64, 0u64, 0u8); 32]; for (s, entry) in table.iter_mut().enumerate().take(19) { if let Some((lo, hi)) = range.scaled(s as u8) { - let lo = if range.lo_closed { Some(lo) } else { lo.checked_add(1) }; - let hi = if range.hi_closed { Some(hi) } else { hi.checked_sub(1) }; + let lo = if range.lo_closed { + Some(lo) + } else { + lo.checked_add(1) + }; + let hi = if range.hi_closed { + Some(hi) + } else { + hi.checked_sub(1) + }; *entry = match lo.zip(hi) { Some((l, h)) if h >= l => (l, h.wrapping_sub(l) as u64, 1), Some(_) => (0, 0, 2), @@ -2250,7 +2260,14 @@ impl<'e, 'x> Exec<'e, 'x> { } } - fn rounded(func: Func, rep: Rep, am: &[i64], asc: &[u8], d: &mut Reg, slow: &mut [u64; Reg::WORDS]) { + fn rounded( + func: Func, + rep: Rep, + am: &[i64], + asc: &[u8], + d: &mut Reg, + slow: &mut [u64; Reg::WORDS], + ) { const P: [i64; 19] = Dec::POW10; let pow = |k: u8| P[usize::from(k.min(18))]; match func { diff --git a/core/expression/src/typed/hir.rs b/core/expression/src/typed/hir.rs index efa1b992..aab3fcc6 100644 --- a/core/expression/src/typed/hir.rs +++ b/core/expression/src/typed/hir.rs @@ -745,7 +745,9 @@ impl Hir { Op::Or(a, b) => format!("or %{a}, %{b}"), Op::If(c, t, e) => format!("if %{c} then %{t} else %{e}"), Op::Coalesce(a, b) => format!("coalesce %{a}, %{b}"), - Op::InRow(a, list, field, of) => format!("inrow %{a} list {list} field {field} of {of:?}"), + Op::InRow(a, list, field, of) => { + format!("inrow %{a} list {list} field {field} of {of:?}") + } Op::InSet(a, set) => format!( "inset %{a} [{}]", set.iter() diff --git a/core/expression/src/typed/lower.rs b/core/expression/src/typed/lower.rs index df2a2553..8e8e99cc 100644 --- a/core/expression/src/typed/lower.rs +++ b/core/expression/src/typed/lower.rs @@ -16,11 +16,11 @@ use crate::typed::hir::{ Arith, Clock, Cmp, Collect, ColumnDef, Dict, DictId, DictKind, Fold, Func, Hir, Host, Kind, ListDef, ListId, Lit, Node, NodeId, Op, Output, Range, Schema, Scope, Stamp, Ty, Unsupported, }; -use compose::Val; use crate::typed::ins::Pattern; use crate::typed::num::Dec; use crate::variable::Variable; use bumpalo::Bump; +use compose::Val; use std::collections::HashMap; use std::sync::Arc; @@ -633,7 +633,11 @@ impl Lowering { let mut picks = Vec::with_capacity(spec.outputs.len()); for at in 0..spec.outputs.len() { let blind: Vec = match unfilled { - true => spec.rules.iter().map(|rule| rule.value(at).is_none()).collect(), + true => spec + .rules + .iter() + .map(|rule| rule.value(at).is_none()) + .collect(), false => Vec::new(), }; let (sel, total) = match unfilled { @@ -1256,12 +1260,10 @@ impl Lowering { }; let rest = segments.join("."); match base { - Base::Pointer if ctx.elem.is_some() => { - match self.descend_elem(ctx, &segments) { - Some(Val::Node(id)) => Ok(id), - _ => Err(Unsupported::new("member of a composite element")), - } - } + Base::Pointer if ctx.elem.is_some() => match self.descend_elem(ctx, &segments) { + Some(Val::Node(id)) => Ok(id), + _ => Err(Unsupported::new("member of a composite element")), + }, Base::Pointer => match (ctx.item, ctx.pointer, rest.is_empty()) { (Some(item), _, true) => Ok(item), (Some(_), _, false) => Err(Unsupported::new("member of a mapped element")), @@ -1276,9 +1278,9 @@ impl Lowering { } Base::Dollar => match self.reach(&rest) { Some(Val::Node(id)) => Ok(id), - Some(Val::Seq(_)) => Err(Unsupported::new(format!( - "list $.{rest} used as a value" - ))), + Some(Val::Seq(_)) => { + Err(Unsupported::new(format!("list $.{rest} used as a value"))) + } Some(_) => Err(Unsupported::new(format!( "composite $.{rest} used as a value" ))), @@ -2687,7 +2689,9 @@ impl Lowering { }; match self.named(path) { Some(Named::Seq(_)) if self.outer && across.is_some() => { - return Err(Unsupported::new(format!("list {path} made in the same pass"))) + return Err(Unsupported::new(format!( + "list {path} made in the same pass" + ))) } Some(Named::Seq(seq)) => return Ok(seq), Some(Named::Node(_) | Named::Val(_)) => { diff --git a/core/expression/src/typed/lower/compose.rs b/core/expression/src/typed/lower/compose.rs index 329871e4..bef08497 100644 --- a/core/expression/src/typed/lower/compose.rs +++ b/core/expression/src/typed/lower/compose.rs @@ -53,7 +53,9 @@ impl Lowering { fn composite(&mut self, name: &str, val: Val, scope: Scope) -> Result<(), Unsupported> { if scope != Scope::Row { - return Err(Unsupported::new(format!("composite output {name} in a list"))); + return Err(Unsupported::new(format!( + "composite output {name} in a list" + ))); } let shape = self.shaped(&val, scope)?; let null = self.konst(Lit::Null); @@ -275,7 +277,9 @@ impl Lowering { .map(|(_, val)| Elem::plain(val)) .collect(), )), - _ => Err(Unsupported::new("values of a value that is not a static object")), + _ => Err(Unsupported::new( + "values of a value that is not a static object", + )), }, Ast::FunctionCall { kind: FunctionKind::Internal(InternalFunction::Keys), @@ -287,11 +291,10 @@ impl Lowering { .iter() .map(|(key, _)| Lit::Text(key.clone())) .collect(), - Val::List(elems) if elems.iter().all(|e| e.keep.is_none() && !e.splice) => { - (0..elems.len()) - .map(|at| Lit::Num(Dec::int(at as i64))) - .collect() - } + Val::List(elems) if elems.iter().all(|e| e.keep.is_none() && !e.splice) => (0 + ..elems.len()) + .map(|at| Lit::Num(Dec::int(at as i64))) + .collect(), _ => return Err(Unsupported::new("keys of a value that is not static")), }; let mut leaves = Vec::new(); @@ -332,7 +335,9 @@ impl Lowering { } Ok(Val::List(out)) } - _ => Err(Unsupported::new("flatten of a value that is not a static list")), + _ => Err(Unsupported::new( + "flatten of a value that is not a static list", + )), }, Ast::Member { node, property } => { let mut segments = Vec::new(); @@ -640,7 +645,11 @@ impl Lowering { Ok(y) } - fn both(&mut self, a: Option, b: Option) -> Result, Unsupported> { + fn both( + &mut self, + a: Option, + b: Option, + ) -> Result, Unsupported> { match (a, b) { (Some(a), Some(b)) => Ok(Some(self.logic(true, a, b)?)), (a, b) => Ok(a.or(b)), @@ -768,7 +777,9 @@ impl Lowering { [] => return Err(Unsupported::new("call without arguments")), }; let Val::List(elems) = self.value(source, ctx, r)? else { - return Err(Unsupported::new("fold over a value that is not a static list")); + return Err(Unsupported::new( + "fold over a value that is not a static list", + )); }; Self::statics(&elems)?; let mut leaves = Vec::new(); @@ -964,7 +975,10 @@ impl Lowering { } }); } - let both = match nulls.iter().any(|n| self.lit(*n) == Some(&Lit::Bool(false))) { + let both = match nulls + .iter() + .any(|n| self.lit(*n) == Some(&Lit::Bool(false))) + { true => self.konst(Lit::Bool(false)), false => self.logic(true, nulls[0], nulls[1])?, }; @@ -999,9 +1013,17 @@ impl Lowering { )) } - pub(super) fn within(&mut self, x: NodeId, list: &Ast, ctx: Ctx, r: &mut dyn Resolve) -> Lowered { + pub(super) fn within( + &mut self, + x: NodeId, + list: &Ast, + ctx: Ctx, + r: &mut dyn Resolve, + ) -> Lowered { let Val::List(elems) = self.value(list, ctx, r)? else { - return Err(Unsupported::new("membership in a value that is not a static list")); + return Err(Unsupported::new( + "membership in a value that is not a static list", + )); }; Self::statics(&elems)?; let mut leaves = Vec::new(); diff --git a/core/expression/src/typed/mod.rs b/core/expression/src/typed/mod.rs index 9c2c1343..7db02ac2 100644 --- a/core/expression/src/typed/mod.rs +++ b/core/expression/src/typed/mod.rs @@ -18,8 +18,8 @@ mod text; pub use batch::{Batch, List}; pub use hir::{ Arith, Clock, Cmp, Collect, ColumnDef, Dict, DictId, DictKind, FieldId, Fold, Func, Hir, Host, - Item, Kind, ListDef, ListId, Lit, Node, NodeId, Op, Output, Range, Schema, Scope, Shape, Stamp, Ty, - Unsupported, + Item, Kind, ListDef, ListId, Lit, Node, NodeId, Op, Output, Range, Schema, Scope, Shape, Stamp, + Ty, Unsupported, }; pub use lower::{Class, Hit, Lowering, Resolve, Resolved, TableRule, TableSpec}; pub use num::{Dec, Fault}; diff --git a/core/expression/src/typed/output.rs b/core/expression/src/typed/output.rs index f521555d..32eabb76 100644 --- a/core/expression/src/typed/output.rs +++ b/core/expression/src/typed/output.rs @@ -665,9 +665,11 @@ impl Outputs { _ => { let found = match (&slot.data, on) { (_, false) => None, - (Data::Code(_), true) => slot.code(e).zip(slot.dict()).and_then( - |(code, d)| hir.schema.dicts.get(d as usize)?.text(code), - ), + (Data::Code(_), true) => { + slot.code(e).zip(slot.dict()).and_then(|(code, d)| { + hir.schema.dicts.get(d as usize)?.text(code) + }) + } (_, true) => slot.text(e), }; let lo = u32::try_from(text.len()).ok()?; diff --git a/core/expression/src/typed/tests/lower.rs b/core/expression/src/typed/tests/lower.rs index 047f71b2..b7a8c5b9 100644 --- a/core/expression/src/typed/tests/lower.rs +++ b/core/expression/src/typed/tests/lower.rs @@ -452,7 +452,10 @@ fn fallible_operands_lower_with_a_check() { "{source}\n{hir}" ); } - for source in ["filter(c.xs, # * 2 in c.xs)", "some(c.ts, upper(#) in c.ts)"] { + for source in [ + "filter(c.xs, # * 2 in c.xs)", + "some(c.ts, upper(#) in c.ts)", + ] { let mut lowering = Lowering::new(None); let mut probe = Probe::new(); Probe::unit(&mut lowering, &mut probe, "c.o", source) diff --git a/core/expression/src/typed/text.rs b/core/expression/src/typed/text.rs index abfbbc6e..de36cdc9 100644 --- a/core/expression/src/typed/text.rs +++ b/core/expression/src/typed/text.rs @@ -124,7 +124,10 @@ impl<'e, 'x> Exec<'e, 'x> { if func == Func::Trim && bytes.is_ascii() { let space = |b: &u8| matches!(b, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r'); let lo = bytes.iter().position(|b| !space(b)).unwrap_or(bytes.len()); - let hi = bytes.iter().rposition(|b| !space(b)).map_or(lo, |at| at + 1); + let hi = bytes + .iter() + .rposition(|b| !space(b)) + .map_or(lo, |at| at + 1); d.push(i, &bytes[lo..hi]); return true; }