use std::sync::Arc;
use super::{
binding::VectorSource, ArrayValueType, AxisValues, BindingGeneration, BindingSelector,
DataPayload, DataRole, DataSourceInfo, DataSourceRef, DataValueType, EstimateStatusBinding,
InstanceId, KeyValues, RawKey, RawKeyValues, SourceRows,
};
use crate::{
elements::ElementRef,
errors::{Diagnostic, DiagnosticKind, DiagnosticReference, ErrorContext, OperationPhase},
plots::PlotKind,
BooleanValues, CategoryValues, Error, NumericValues, Result,
};
#[derive(Debug, Clone)]
pub enum DataSelector {
Role(DataRole),
Named(String),
Reference(DataRoleRef),
}
impl From<DataRole> for DataSelector {
fn from(role: DataRole) -> Self {
Self::Role(role)
}
}
impl From<DataRoleRef> for DataSelector {
fn from(reference: DataRoleRef) -> Self {
Self::Reference(reference)
}
}
impl From<&DataRoleRef> for DataSelector {
fn from(reference: &DataRoleRef) -> Self {
Self::Reference(reference.clone())
}
}
impl From<&str> for DataSelector {
fn from(name: &str) -> Self {
Self::Named(name.to_owned())
}
}
impl From<String> for DataSelector {
fn from(name: String) -> Self {
Self::Named(name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum DomainSlot {
Observations,
HistogramBins,
HistogramKde,
HistogramRug,
RaincloudSummary,
RaincloudDensity,
RaincloudPoints,
Alpha(DataRole),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum DomainIdentity {
Bound {
owner: ElementRef,
slot: DomainSlot,
revision: InstanceId,
},
Scientific {
owner: ElementRef,
group: Option<super::GroupKey>,
identity: InstanceId,
},
Source {
capture: DataSourceRef,
coordinate: SourceCoordinate,
row_identity: Option<InstanceId>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SourceCoordinate {
Rows,
Fields,
Array,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataDomainRef(DomainIdentity);
impl DataDomainRef {
pub(crate) fn bound(owner: &ElementRef, slot: DomainSlot, revision: &InstanceId) -> Self {
Self(DomainIdentity::Bound {
owner: owner.clone(),
slot,
revision: revision.clone(),
})
}
pub(crate) fn scientific(owner: &ElementRef, group: Option<&super::GroupKey>) -> Self {
Self(DomainIdentity::Scientific {
owner: owner.clone(),
group: group.cloned(),
identity: InstanceId::new(),
})
}
pub fn group_key(&self) -> Option<&super::GroupKey> {
match &self.0 {
DomainIdentity::Scientific { group, .. } => group.as_ref(),
_ => None,
}
}
fn same_position(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(
DomainIdentity::Bound { owner, slot, .. },
DomainIdentity::Bound {
owner: other_owner,
slot: other_slot,
..
},
) => owner == other_owner && slot == other_slot,
_ => self == other,
}
}
pub fn owner(&self) -> Option<&ElementRef> {
match &self.0 {
DomainIdentity::Bound { owner, .. } | DomainIdentity::Scientific { owner, .. } => {
Some(owner)
}
DomainIdentity::Source { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataRoleRef {
role: DataRole,
owner: ElementRef,
binding: InstanceId,
domain: Option<DataDomainRef>,
}
impl DataRoleRef {
pub fn role(&self) -> Option<DataRole> {
Some(self.role)
}
pub fn owner(&self) -> Option<&ElementRef> {
Some(&self.owner)
}
pub fn domain(&self) -> Option<&DataDomainRef> {
self.domain.as_ref()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AxisValueType {
Numeric,
Category,
Keys,
Date,
Instant,
Duration,
}
fn payload_axis_type(value: &DataPayload) -> Option<AxisValueType> {
match value {
DataPayload::Axis(AxisValues::Numeric(_)) => Some(AxisValueType::Numeric),
DataPayload::Axis(AxisValues::Category(_)) => Some(AxisValueType::Category),
DataPayload::Axis(AxisValues::Keys(_)) => Some(AxisValueType::Keys),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ComponentPathPart {
Field(String),
Index(usize),
Key(RawKey),
}
impl From<&str> for ComponentPathPart {
fn from(field: &str) -> Self {
Self::Field(field.to_owned())
}
}
#[derive(Debug, Clone)]
struct SourceRelation {
source: VectorSource,
field: Option<RawKey>,
length: usize,
}
#[derive(Debug, Clone)]
pub struct DataComponentInfo {
path: Arc<[ComponentPathPart]>,
name: Option<String>,
value_type: DataValueType,
axis_type: Option<AxisValueType>,
shape: Arc<[usize]>,
nullable: bool,
has_nulls: bool,
relation: Option<SourceRelation>,
}
impl DataComponentInfo {
#[expect(
clippy::too_many_arguments,
reason = "construct one complete actual column description and relation"
)]
fn vector(
path: Vec<ComponentPathPart>,
name: Option<&str>,
value_type: DataValueType,
source: &VectorSource,
field: Option<&RawKey>,
length: usize,
nullable: bool,
has_nulls: bool,
) -> Self {
Self {
path: path.into(),
name: name.map(str::to_owned),
value_type,
axis_type: None,
shape: Arc::from([length]),
nullable,
has_nulls,
relation: Some(SourceRelation {
source: source.clone(),
field: field.cloned(),
length,
}),
}
}
pub(crate) fn numeric(path: Vec<ComponentPathPart>, values: &NumericValues) -> Self {
Self::vector(
path,
Some(values.name()),
DataValueType::Numeric,
values.vector_source(),
values.field_key(),
values.len(),
true,
values.has_nulls(),
)
}
pub(crate) fn category(path: Vec<ComponentPathPart>, values: &CategoryValues) -> Self {
let field = values.field_key();
match values.key_values() {
KeyValues::Strings(values) => Self::vector(
path,
Some(values.original_name()),
DataValueType::Category,
values.vector_source(),
field,
values.len(),
true,
values.has_nulls(),
),
KeyValues::Raw(values) => Self::raw_keys(path, &values, field),
}
}
pub(crate) fn raw_keys(
path: Vec<ComponentPathPart>,
values: &RawKeyValues,
field: Option<&RawKey>,
) -> Self {
Self::vector(
path,
Some(values.name()),
DataValueType::RawKeys,
values.vector_source(),
field,
values.len(),
true,
values.has_nulls(),
)
}
pub(crate) fn boolean(path: Vec<ComponentPathPart>, values: &BooleanValues) -> Self {
Self::vector(
path,
Some(values.name()),
DataValueType::Boolean,
values.vector_source(),
values.field_key(),
values.len(),
true,
values.has_nulls(),
)
}
pub(crate) fn statuses(binding: &EstimateStatusBinding) -> Self {
if let Some(values) = binding.get_boolean() {
return Self::boolean(vec!["get_boolean".into()], values);
}
if let Some((values, _)) = binding.get_categorical() {
return Self::category(
vec!["get_categorical".into(), ComponentPathPart::Index(0)],
values,
);
}
Self::vector(
vec![],
None,
DataValueType::EstimateStatuses,
binding.vector_source(),
None,
binding.statuses().len(),
false,
false,
)
}
pub(crate) fn scientific(name: &str, value: &DataPayload) -> Result<Self> {
Self::scientific_at(
vec![ComponentPathPart::Field(super::source::copy_source_string(
name,
)?)],
value,
)
}
pub(crate) fn scientific_at(path: Vec<ComponentPathPart>, value: &DataPayload) -> Result<Self> {
let mut component = Self::captured_at(path, value)?;
component.relation = None;
Ok(component)
}
pub(crate) fn captured(name: &str, value: &DataPayload) -> Result<Self> {
Self::captured_at(
vec![ComponentPathPart::Field(super::source::copy_source_string(
name,
)?)],
value,
)
}
pub(crate) fn captured_at(path: Vec<ComponentPathPart>, value: &DataPayload) -> Result<Self> {
let mut component = match value {
DataPayload::Numeric(values) => Self::numeric(path, values),
DataPayload::Category(values) => Self::category(path, values),
DataPayload::RawKeys(values) => Self::raw_keys(path, values, None),
DataPayload::Boolean(values) => Self::boolean(path, values),
DataPayload::Integer(values) => Self::vector(
path,
Some(values.name()),
DataValueType::Integer,
values.vector_source(),
None,
values.len(),
true,
values.iter().any(|value| value.is_none()),
),
DataPayload::Axis(values) => match values {
AxisValues::Numeric(values) => Self::numeric(path, values),
AxisValues::Category(values) => Self::category(path, values),
AxisValues::Keys(values) => Self::raw_keys(path, values, None),
},
DataPayload::EstimateStatuses(statuses) => Self {
path: path.into(),
name: None,
value_type: DataValueType::EstimateStatuses,
axis_type: None,
shape: Arc::from([statuses.len()]),
nullable: false,
has_nulls: false,
relation: None,
},
_ => return Err(Error::Render("unsupported scientific field payload".into())),
};
component.value_type = value.value_type();
component.axis_type = payload_axis_type(value);
Ok(component)
}
pub(crate) fn scientific_with_members(
name: &str,
value: &DataPayload,
members: &[Option<SourceMembers>],
) -> Result<Self> {
let mut component = Self::captured(name, value)?;
if let Some(source) = component
.relation
.as_ref()
.map(|relation| relation.source.info())
{
let mut supplied = false;
for entries in members.iter().flatten() {
crate::operation::check()?;
if entries
.entries()
.iter()
.any(|entry| entry.source() == source)
{
supplied = true;
break;
}
}
if !supplied {
component.relation = None;
}
}
Ok(component)
}
pub fn path(&self) -> &[ComponentPathPart] {
&self.path
}
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn value_type(&self) -> Option<DataValueType> {
Some(self.value_type)
}
pub fn array_type(&self) -> Option<ArrayValueType> {
None
}
pub fn axis_type(&self) -> Option<AxisValueType> {
self.axis_type
}
pub fn shape(&self) -> Option<&[usize]> {
Some(&self.shape)
}
pub fn nullable(&self) -> bool {
self.nullable
}
pub fn has_nulls(&self) -> bool {
self.has_nulls
}
pub fn sources(&self) -> &[DataSourceInfo] {
self.relation
.as_ref()
.map_or(&[], |relation| std::slice::from_ref(relation.source.info()))
}
}
#[derive(Debug, Clone)]
pub struct DataDomainInfo {
reference: DataDomainRef,
shape: Arc<[usize]>,
keys: Option<RawKeyValues>,
source_rows: Option<SourceRows>,
components: Arc<[DataComponentInfo]>,
}
impl DataDomainInfo {
pub(crate) fn bound(
reference: DataDomainRef,
length: usize,
rows: Option<&SourceRows>,
components: Vec<DataComponentInfo>,
) -> Self {
Self {
reference,
shape: Arc::from([length]),
keys: None,
source_rows: rows.filter(|rows| rows.len() == length).cloned(),
components: components.into(),
}
}
pub(crate) fn with_source_rows(mut self, rows: Option<&SourceRows>) -> Self {
self.source_rows = rows
.filter(|rows| self.shape.as_ref() == [rows.len()])
.cloned();
self
}
pub(crate) fn with_keys(mut self, keys: &RawKeyValues) -> Self {
self.keys = Some(keys.clone());
self
}
pub(crate) fn with_component(mut self, component: DataComponentInfo) -> Result<Self> {
if component.shape() != Some(self.shape()) {
return Err(Error::Render(
"result component does not align with its domain".into(),
));
}
let mut components =
super::source::collect_source(self.components.iter().cloned().map(Ok))?;
super::source::reserve_source(&mut components, 1)?;
components.push(component);
self.components = components.into();
Ok(self)
}
pub fn reference(&self) -> &DataDomainRef {
&self.reference
}
pub fn shape(&self) -> &[usize] {
&self.shape
}
pub fn keys(&self) -> Option<&RawKeyValues> {
self.keys.as_ref()
}
pub fn axis_keys(&self) -> Option<&[RawKeyValues]> {
self.keys.as_ref().map(std::slice::from_ref)
}
pub fn source_rows(&self) -> Option<&SourceRows> {
self.source_rows.as_ref()
}
pub fn components(&self) -> &[DataComponentInfo] {
&self.components
}
#[expect(
clippy::too_many_lines,
reason = "the original member address resolves once with its exact typed failure"
)]
pub(crate) fn resolve(&self, address: &MemberAddress) -> Result<usize> {
let mut context = ErrorContext::new()
.with_operation(OperationPhase::Check)
.with_member(address.clone());
if let Some(owner) = self.reference.owner() {
context = context.with_element(owner.clone());
}
let invalid_index = |index: Vec<super::ExactInteger>| {
Error::Data(
Diagnostic::new(
DiagnosticKind::IndexOutOfBounds {
index,
shape: Some(self.shape.to_vec()),
},
format!(
"invalid member address {address:?} for domain {:?}",
self.shape
),
)
.with_context(context.clone()),
)
};
let unknown_key = |key: RawKey| {
Error::Data(
Diagnostic::new(
DiagnosticKind::UnknownKey { key: Some(key) },
format!(
"unknown member address {address:?} for domain {:?}",
self.shape
),
)
.with_context(context.clone()),
)
};
let absent_keys = |constraint: &str| {
Error::Data(
Diagnostic::new(
DiagnosticKind::InvalidValue {
value: None,
constraint: constraint.to_owned(),
},
constraint,
)
.with_context(context.clone()),
)
};
match address {
MemberAddress::Slot(slot) => {
if self.shape.len() == 1 && *slot < self.shape[0] {
Ok(*slot)
} else {
Err(invalid_index(vec![(*slot).into()]))
}
}
MemberAddress::Index(indices) => {
if indices.len() != self.shape.len()
|| indices
.iter()
.zip(self.shape.iter())
.any(|(index, extent)| index >= extent)
{
return Err(invalid_index(
indices.iter().copied().map(Into::into).collect(),
));
}
indices
.iter()
.zip(self.shape.iter())
.try_fold(0usize, |slot, (index, extent)| {
slot.checked_mul(*extent)?.checked_add(*index)
})
.ok_or_else(|| invalid_index(indices.iter().copied().map(Into::into).collect()))
}
MemberAddress::RowId(id) => {
let rows = self
.source_rows
.as_ref()
.ok_or_else(|| absent_keys("member domain has no explicit row IDs"))?;
rows.iter()
.position(|row| row == *id)
.ok_or_else(|| unknown_key(RawKey::Integer((*id).into())))
}
MemberAddress::Key(key) => {
let keys = self
.keys
.as_ref()
.ok_or_else(|| absent_keys("member domain has no explicit member keys"))?;
let slots: Vec<_> = keys
.iter()
.enumerate()
.filter_map(|(slot, value)| (value == Some(key)).then_some(slot))
.collect();
match slots.as_slice() {
[] => Err(unknown_key(key.clone())),
[slot] => Ok(*slot),
_ => Err(Error::Data(
Diagnostic::new(
DiagnosticKind::Ambiguous {
candidates: slots
.into_iter()
.map(|slot| DiagnosticReference::Member {
domain: Some(self.reference.clone()),
address: MemberAddress::Slot(slot),
})
.collect(),
},
"ambiguous original member key",
)
.with_context(context),
)),
}
}
}
}
fn members(&self, slot: usize) -> Option<SourceMembers> {
let entries: Vec<_> = self
.components
.iter()
.filter_map(|component| component.origin(self, slot))
.collect();
(!entries.is_empty()).then(|| SourceMembers {
entries: entries.into(),
})
}
}
#[derive(Debug, Clone)]
pub struct DataRoleInfo {
reference: DataRoleRef,
plot_kind: Option<PlotKind>,
value_type: DataValueType,
array_type: Option<ArrayValueType>,
axis_type: Option<AxisValueType>,
shape: Option<Arc<[usize]>>,
name: Option<String>,
domains: Arc<[DataDomainInfo]>,
source: Option<DataSourceRef>,
selector: Option<BindingSelector>,
}
impl DataRoleInfo {
pub fn reference(&self) -> &DataRoleRef {
&self.reference
}
pub fn role(&self) -> Option<DataRole> {
self.reference.role()
}
pub fn plot_kind(&self) -> Option<PlotKind> {
self.plot_kind
}
pub fn value_type(&self) -> DataValueType {
self.value_type
}
pub fn array_type(&self) -> Option<ArrayValueType> {
self.array_type
}
pub fn axis_type(&self) -> Option<AxisValueType> {
self.axis_type
}
pub fn shape(&self) -> Option<&[usize]> {
self.shape.as_deref()
}
pub fn domain(&self) -> Option<&DataDomainRef> {
self.reference.domain()
}
pub fn domains(&self) -> &[DataDomainInfo] {
&self.domains
}
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn source(&self) -> Option<&DataSourceRef> {
self.source.as_ref()
}
pub fn selector(&self) -> Option<&BindingSelector> {
self.selector.as_ref()
}
}
#[derive(Debug, Clone)]
pub struct DataValue {
info: DataRoleInfo,
value: Arc<DataPayload>,
}
impl DataValue {
#[expect(
clippy::too_many_arguments,
reason = "construct a single owning value with its actual declaration and domain metadata"
)]
pub(crate) fn bound(
role: DataRole,
owner: &ElementRef,
revision: &InstanceId,
plot_kind: Option<PlotKind>,
value: DataPayload,
shape: Option<Vec<usize>>,
name: Option<&str>,
domains: Vec<DataDomainInfo>,
) -> Self {
let domain = (domains.len() == 1).then(|| domains[0].reference.clone());
let mut sources = domains
.iter()
.flat_map(|domain| domain.components.iter())
.flat_map(DataComponentInfo::sources);
let first = sources.next();
let mut source = first.map(|source| source.reference().clone());
let mut selector = first.and_then(|source| source.selector().cloned());
for item in sources {
if source.as_ref() != Some(item.reference()) {
source = None;
selector = None;
}
if selector.as_ref() != item.selector() {
selector = None;
}
}
let axis_type = payload_axis_type(&value);
let array_type = match &value {
DataPayload::Array(array) => Some(array.array_type()),
_ => None,
};
Self {
info: DataRoleInfo {
reference: DataRoleRef {
role,
owner: owner.clone(),
binding: revision.clone(),
domain,
},
plot_kind,
value_type: value.value_type(),
array_type,
axis_type,
shape: shape.map(Arc::from),
name: name.map(str::to_owned),
domains: domains.into(),
source,
selector,
},
value: Arc::new(value),
}
}
pub fn info(&self) -> &DataRoleInfo {
&self.info
}
pub fn value(&self) -> &DataPayload {
&self.value
}
pub fn numeric(&self) -> Result<NumericValues> {
match self.value() {
DataPayload::Numeric(values) | DataPayload::Axis(AxisValues::Numeric(values)) => {
Ok(values.clone())
}
DataPayload::AlphaEncoding(encoding)
if encoding.get_keyed().is_none() && encoding.get_bins().is_none() =>
{
encoding
.values()
.and_then(crate::scales::AlphaValues::get_numeric_source)
.cloned()
.ok_or_else(|| self.incompatible(DataValueType::Numeric))
}
_ => Err(self.incompatible(DataValueType::Numeric)),
}
}
pub fn category(&self) -> Result<CategoryValues> {
match self.value() {
DataPayload::Category(values) | DataPayload::Axis(AxisValues::Category(values)) => {
Ok(values.clone())
}
DataPayload::AlphaEncoding(encoding)
if encoding.get_keyed().is_none() && encoding.get_bins().is_none() =>
{
encoding
.values()
.and_then(crate::scales::AlphaValues::get_category_source)
.and_then(KeyValues::get_strings)
.cloned()
.ok_or_else(|| self.incompatible(DataValueType::Category))
}
_ => Err(self.incompatible(DataValueType::Category)),
}
}
pub fn boolean(&self) -> Result<BooleanValues> {
match self.value() {
DataPayload::Boolean(values) => Ok(values.clone()),
_ => Err(self.incompatible(DataValueType::Boolean)),
}
}
pub fn axis(&self) -> Result<AxisValues> {
match self.value() {
DataPayload::Axis(values) => Ok(values.clone()),
DataPayload::Numeric(values) => Ok(AxisValues::Numeric(values.clone())),
DataPayload::Category(values) => Ok(AxisValues::Category(values.clone())),
DataPayload::RawKeys(values) => Ok(AxisValues::Keys(values.clone())),
_ => Err(self.incompatible(DataValueType::Axis)),
}
}
fn context(&self) -> ErrorContext {
ErrorContext::new()
.with_operation(OperationPhase::Check)
.with_element(self.info.reference.owner().expect("bound role").clone())
.with_role(self.info.reference.role().expect("fixed role"))
}
fn incompatible(&self, expected: DataValueType) -> Error {
Error::Data(
Diagnostic::new(
DiagnosticKind::WrongType {
expected,
actual: self.info.value_type,
},
format!(
"role {:?} at {:?} contains {:?}, not a unique {} value",
self.info.role(),
self.info.reference.owner(),
self.info.value_type,
expected.as_str()
),
)
.with_context(self.context()),
)
}
pub fn source_rows(&self) -> Option<&SourceRows> {
self.info.domain()?;
self.info.domains[0].source_rows()
}
pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
let domain = self.info.domain().ok_or_else(|| {
Error::Data(
Diagnostic::new(
DiagnosticKind::Ambiguous {
candidates: self
.info
.domains
.iter()
.map(|domain| DiagnosticReference::Domain(domain.reference.clone()))
.collect(),
},
"role has no unique member domain; select an actual domain",
)
.with_context(self.context()),
)
})?;
self.members_in(domain, address)
}
pub fn members_in(
&self,
domain: &DataDomainRef,
address: impl Into<MemberAddress>,
) -> Result<Option<SourceMembers>> {
let domain = self
.info
.domains
.iter()
.find(|info| info.reference() == domain)
.ok_or_else(|| {
let current = self
.info
.domains
.iter()
.find(|info| info.reference.same_position(domain))
.map(|info| Box::new(DiagnosticReference::Domain(info.reference.clone())));
Error::Data(
Diagnostic::new(
DiagnosticKind::StaleReference {
reference: Box::new(DiagnosticReference::Domain(domain.clone())),
current,
},
"member domain is foreign or no longer bound",
)
.with_context(self.context()),
)
})?;
let slot = domain.resolve(&address.into())?;
Ok(domain.members(slot))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MemberAddress {
Slot(usize),
Index(Vec<usize>),
RowId(usize),
Key(RawKey),
}
impl From<usize> for MemberAddress {
fn from(slot: usize) -> Self {
Self::Slot(slot)
}
}
#[derive(Debug, Clone)]
pub struct SourceMember {
address: MemberAddress,
key: Option<RawKey>,
row_id: Option<usize>,
}
impl SourceMember {
pub fn address(&self) -> &MemberAddress {
&self.address
}
pub fn key(&self) -> Option<&RawKey> {
self.key.as_ref()
}
pub fn row_id(&self) -> Option<usize> {
self.row_id
}
}
#[derive(Debug, Clone)]
pub struct SourceMembersEntry {
source: DataSourceInfo,
domain: DataDomainInfo,
field_key: Option<RawKey>,
members: Option<Arc<[SourceMember]>>,
member_limit: Option<usize>,
}
impl SourceMembersEntry {
pub fn source(&self) -> &DataSourceInfo {
&self.source
}
pub fn domain(&self) -> &DataDomainInfo {
&self.domain
}
pub fn field_key(&self) -> Option<&RawKey> {
self.field_key.as_ref()
}
pub fn members(&self) -> Option<&[SourceMember]> {
self.members
.as_deref()
.map(|members| &members[..self.member_limit.unwrap_or(members.len())])
}
}
#[derive(Debug, Clone)]
pub struct SourceMembers {
entries: Arc<[SourceMembersEntry]>,
}
#[derive(Default)]
struct MemberAccumulator {
entries: Vec<(SourceMembersEntry, Vec<SourceMember>)>,
}
impl MemberAccumulator {
fn append(&mut self, domain: &DataDomainInfo, slot: usize) -> Result<()> {
self.append_components(domain, slot, domain.components().iter())
}
fn append_components<'a>(
&mut self,
domain: &DataDomainInfo,
slot: usize,
components: impl Iterator<Item = &'a DataComponentInfo>,
) -> Result<()> {
domain.resolve(&MemberAddress::Slot(slot))?;
for component in components {
crate::operation::check()?;
let Some(entry) = component.origin(domain, slot) else {
continue;
};
let index = self.entries.iter().position(|(current, _)| {
current.source == entry.source
&& current.domain.reference == entry.domain.reference
&& current.field_key == entry.field_key
});
let index = if let Some(index) = index {
index
} else {
super::source::reserve_source(&mut self.entries, 1)?;
let index = self.entries.len();
self.entries.push((entry.clone(), Vec::new()));
index
};
if let Some(members) = entry.members() {
let retained = &mut self.entries[index].1;
if retained.capacity() - retained.len() < members.len() {
super::source::reserve_source(retained, retained.len().max(members.len()))?;
}
retained.extend_from_slice(members);
}
}
Ok(())
}
fn finish(self) -> Result<SourceMembers> {
let entries =
super::source::collect_source(self.entries.into_iter().map(|(mut entry, members)| {
entry.members = Some(members.into());
Ok(entry)
}))?;
Ok(SourceMembers {
entries: entries.into(),
})
}
}
impl SourceMembers {
pub(crate) fn from_slots(
values: &[&DataValue],
slots: impl IntoIterator<Item = usize>,
) -> Result<Self> {
let domains = super::source::collect_source(values.iter().map(|value| {
let [domain] = value.info.domains.as_ref() else {
return Err(Error::Render(
"scientific input has no unique member domain".into(),
));
};
Ok(domain)
}))?;
Self::from_domains(&domains, slots)
}
pub(crate) fn from_domains(
domains: &[&DataDomainInfo],
slots: impl IntoIterator<Item = usize>,
) -> Result<Self> {
let mut accumulator = MemberAccumulator::default();
for (index, slot) in slots.into_iter().enumerate() {
if index.is_multiple_of(1024) {
crate::operation::checkpoint()?;
}
for domain in domains {
accumulator.append(domain, slot)?;
}
}
accumulator.finish()
}
pub(crate) fn from_component_slots(
domain: &DataDomainInfo,
component: &DataComponentInfo,
slots: impl IntoIterator<Item = usize>,
) -> Result<Self> {
let mut accumulator = MemberAccumulator::default();
for (index, slot) in slots.into_iter().enumerate() {
if index.is_multiple_of(1024) {
crate::operation::checkpoint()?;
}
accumulator.append_components(domain, slot, std::iter::once(component))?;
}
accumulator.finish()
}
pub(crate) fn prefixes(value: &DataValue, slots: &[usize]) -> Result<Vec<Self>> {
let [domain] = value.info.domains.as_ref() else {
return Err(Error::Render(
"cumulative input has no unique member domain".into(),
));
};
let mut accumulator = MemberAccumulator::default();
let mut counts = Vec::new();
super::source::reserve_source(
&mut counts,
slots
.len()
.checked_add(1)
.ok_or_else(|| Error::Render("cumulative member length overflow".into()))?,
)?;
counts.push(Vec::new());
for (index, &slot) in slots.iter().enumerate() {
if index.is_multiple_of(1024) {
crate::operation::checkpoint()?;
}
accumulator.append(domain, slot)?;
counts.push(super::source::collect_source(
accumulator
.entries
.iter()
.map(|(_, members)| Ok(members.len())),
)?);
}
let all = accumulator.finish()?;
super::source::collect_source(counts.into_iter().map(|counts| {
let entries = super::source::collect_source(
all.entries
.iter()
.zip(counts)
.filter(|(_, count)| *count != 0)
.map(|(entry, count)| {
let mut entry = entry.clone();
entry.member_limit = Some(count);
Ok(entry)
}),
)?;
Ok(Self {
entries: entries.into(),
})
}))
}
pub fn entries(&self) -> &[SourceMembersEntry] {
&self.entries
}
}
impl SourceRelation {
fn original_address(&self, member: usize) -> Option<OriginalAddress> {
let relation = self;
if member >= relation.length {
return None;
}
let slot = relation.source.slot(member);
let info = relation.source.info();
let member_shape = info.member_shape();
let mut field_key = relation.field.clone();
let mut field_position = None;
let mut key = None;
let field_axis = info.generation() == Some(BindingGeneration::ColumnNames)
|| info.grid_axis() == Some(1);
let (coordinate, shape, address) = if field_axis {
let position = info
.selected_indices()
.and_then(|indices| indices.get(slot))
.copied()
.unwrap_or(slot);
key = info
.selected_keys()
.and_then(|keys| keys.get(slot))
.cloned();
(
SourceCoordinate::Fields,
vec![*info.source_shape().get(1)?],
MemberAddress::Slot(position),
)
} else if let [_, width] = member_shape {
if *width == 0 {
return None;
}
let row = slot / width;
let selected_column = slot % width;
let key = info
.selected_keys()
.and_then(|keys| keys.get(selected_column))
.cloned();
if let Some(key) = key {
field_key = Some(key);
field_position = Some(selected_column);
(
SourceCoordinate::Rows,
vec![info.source_shape()[0]],
MemberAddress::Slot(row),
)
} else {
let column = info
.selected_indices()
.and_then(|indices| indices.get(selected_column))
.copied()
.unwrap_or(selected_column);
(
SourceCoordinate::Array,
info.source_shape().to_vec(),
MemberAddress::Index(vec![row, column]),
)
}
} else {
if info.generation() == Some(BindingGeneration::RowPosition)
|| info.grid_axis() == Some(0)
{
field_key = None;
} else if field_key.is_none()
&& info.selected_keys().is_some_and(|keys| keys.len() == 1)
{
field_key = info.selected_keys().and_then(|keys| keys.first()).cloned();
}
if field_key.is_some() {
field_position = Some(0);
}
(
SourceCoordinate::Rows,
vec![*info.source_shape().first()?],
MemberAddress::Slot(slot),
)
};
Some(OriginalAddress {
coordinate,
shape,
address,
key,
field_key,
field_position,
})
}
}
struct OriginalAddress {
coordinate: SourceCoordinate,
shape: Vec<usize>,
address: MemberAddress,
key: Option<RawKey>,
field_key: Option<RawKey>,
field_position: Option<usize>,
}
impl DataComponentInfo {
fn origin(&self, bound: &DataDomainInfo, member: usize) -> Option<SourceMembersEntry> {
let relation = self.relation.as_ref()?;
let OriginalAddress {
coordinate,
shape,
address,
key,
field_key,
field_position,
} = relation.original_address(member)?;
let info = relation.source.info();
let mut row_id = None;
let mut rows = None;
let mut row_identity = None;
if coordinate == SourceCoordinate::Rows
&& relation.source.has_distinct_rows()
&& info.generation().is_none()
&& info.member_shape().len() == 1
{
row_id = bound.source_rows().and_then(|rows| rows.get(member));
if relation.source.is_identity()
&& relation.length == info.member_shape()[0]
&& bound.shape() == info.member_shape()
{
rows = bound.source_rows().cloned();
}
if row_id.is_some() {
if let DomainIdentity::Bound { revision, .. } = &bound.reference.0 {
row_identity = Some(revision.clone());
}
}
}
let reference = DataDomainRef(DomainIdentity::Source {
capture: info.reference().clone(),
coordinate,
row_identity,
});
let mut component = self.clone();
component.shape = match coordinate {
SourceCoordinate::Rows => Arc::from(shape.as_slice()),
SourceCoordinate::Fields | SourceCoordinate::Array => Arc::from(info.member_shape()),
};
component.has_nulls = relation.source.original_has_nulls(field_position);
if let Some(field) = &field_key {
component.path = Arc::from([ComponentPathPart::Key(field.clone())]);
if let Some((_, name)) = field_position.and_then(|position| info.field(position)) {
component.name = Some(name);
}
}
Some(SourceMembersEntry {
source: info.clone(),
field_key,
domain: DataDomainInfo {
reference,
shape: shape.into(),
source_rows: rows,
keys: if coordinate == SourceCoordinate::Fields {
relation.source.field_axis_keys().cloned()
} else {
None
},
components: Arc::from([component]),
},
member_limit: None,
members: Some(Arc::from([SourceMember {
address,
key,
row_id,
}])),
})
}
}
pub(crate) fn select_value(values: &[DataValue], selector: DataSelector) -> Result<DataValue> {
match selector {
DataSelector::Role(role) => {
let mut context = ErrorContext::new()
.with_operation(OperationPhase::Check)
.with_role(role);
if let Some(owner) = values
.first()
.and_then(|value| value.info.reference.owner())
{
context = context.with_element(owner.clone());
}
let matches: Vec<_> = values
.iter()
.filter(|value| value.info.role() == Some(role))
.collect();
match matches.as_slice() {
[] => Err(Error::Data(
Diagnostic::new(
DiagnosticKind::UnknownKey { key: None },
format!("role {role:?} is not bound"),
)
.with_context(context),
)),
[found] => Ok((*found).clone()),
_ => Err(Error::Data(
Diagnostic::new(
DiagnosticKind::Ambiguous {
candidates: matches
.into_iter()
.map(|value| {
DiagnosticReference::Role(value.info.reference.clone())
})
.collect(),
},
format!("role {role:?} is ambiguous; use its actual reference"),
)
.with_context(context),
)),
}
}
DataSelector::Reference(reference) => {
if let Some(value) = values
.iter()
.find(|value| value.info.reference == reference)
{
return Ok(value.clone());
}
let current = values
.iter()
.find(|value| {
value.info.reference.owner == reference.owner
&& value.info.reference.role == reference.role
})
.map(|value| Box::new(DiagnosticReference::Role(value.info.reference.clone())));
let context = ErrorContext::new()
.with_operation(OperationPhase::Check)
.with_element(reference.owner.clone())
.with_role(reference.role);
Err(Error::Data(
Diagnostic::new(
DiagnosticKind::StaleReference {
reference: Box::new(DiagnosticReference::Role(reference)),
current,
},
"data role reference is foreign or no longer bound",
)
.with_context(context),
))
}
DataSelector::Named(name) => {
let message = format!("no explicitly declared named input {name:?}");
Err(Error::Data(
Diagnostic::new(
DiagnosticKind::UnknownKey {
key: Some(name.into()),
},
message,
)
.with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
))
}
}
}