Skip to main content

polydat_core/
dataset_value.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The values of the dataset port types (`forms`, `fragment`,
5//! `admitted_rows`): what a vector dataset publishes about its
6//! predicates and records, on a wire as the types `vectordata` defines.
7//!
8//! A host reads one by matching [`DatasetValue`], with no downcast and
9//! no inspection of a payload: the port type in a program's manifest
10//! says which kind a wire carries, and the variant holds vectordata's
11//! own type. Polydat adds only the two pairings vectordata has no type
12//! for: a facet's forms with the layout and the records they describe
13//! (`PredicateForms`, `RecordForms`), and one record's place among
14//! them for a cycle (`PredicateFragment`, `RecordFragment`).
15//!
16//! The variants exist when the `vectordata` feature is on. Without it
17//! the port types are still names of the language, and no value of
18//! them can be made, so [`DatasetValue`] has no variant and
19//! `Value::Dataset` is never constructed.
20//!
21//! Nothing here checks a record. That a dataset's records meet what it
22//! declares is established where the dataset is published; these
23//! values hand on what vectordata reads.
24
25#[cfg(feature = "vectordata")]
26use std::sync::Arc;
27
28use crate::ast::PortType;
29
30#[cfg(feature = "vectordata")]
31pub use self::types::{PredicateForms, PredicateFragment, RecordForms, RecordFragment};
32#[cfg(feature = "vectordata")]
33pub use self::wires::Shared;
34
35/// A value of one of the dataset port types.
36#[derive(Debug, Clone)]
37pub enum DatasetValue {
38    /// The base positions a query's predicate admits: vectordata's
39    /// set over the query's `metadata_results` record, which is not
40    /// read until it is asked. Port type `admitted_rows`.
41    #[cfg(feature = "vectordata")]
42    AdmittedRows(Arc<vectordata::ground_truth::OrdinalSet>),
43    /// The forms of a predicate facet. Port type `forms`.
44    #[cfg(feature = "vectordata")]
45    PredicateForms(Arc<PredicateForms>),
46    /// The one form of a record facet: its layout. Port type `forms`.
47    #[cfg(feature = "vectordata")]
48    RecordForms(Arc<RecordForms>),
49    /// One predicate, as its form and its record. Port type `fragment`.
50    #[cfg(feature = "vectordata")]
51    Predicate(PredicateFragment),
52    /// One metadata record. Port type `fragment`.
53    #[cfg(feature = "vectordata")]
54    Record(RecordFragment),
55}
56
57impl DatasetValue {
58    /// The port type of the wire this value rides.
59    pub fn port_type(&self) -> PortType {
60        match self {
61            #[cfg(feature = "vectordata")]
62            DatasetValue::AdmittedRows(_) => PortType::AdmittedRows,
63            #[cfg(feature = "vectordata")]
64            DatasetValue::PredicateForms(_) | DatasetValue::RecordForms(_) => PortType::Forms,
65            #[cfg(feature = "vectordata")]
66            DatasetValue::Predicate(_) | DatasetValue::Record(_) => PortType::Fragment,
67            #[cfg(not(feature = "vectordata"))]
68            _ => match *self {},
69        }
70    }
71
72    /// A short rendering for diagnostics and dry runs: what the value
73    /// is and where it comes from, never the records themselves. A set
74    /// of admitted rows shows its first positions and its size.
75    pub fn display(&self) -> String {
76        match self {
77            #[cfg(feature = "vectordata")]
78            DatasetValue::AdmittedRows(set) => format!("{set:?}"),
79            #[cfg(feature = "vectordata")]
80            DatasetValue::PredicateForms(forms) => format!(
81                "forms of {}: {} over {} predicates",
82                forms.origin,
83                forms.census.forms().len(),
84                forms.census.count()
85            ),
86            #[cfg(feature = "vectordata")]
87            DatasetValue::RecordForms(forms) => format!(
88                "forms of {}: 1 over {} fields",
89                forms.origin,
90                forms.layout.names().len()
91            ),
92            #[cfg(feature = "vectordata")]
93            DatasetValue::Predicate(fragment) => format!(
94                "predicate {} of {}, form {}",
95                fragment.ordinal, fragment.forms.origin, fragment.form
96            ),
97            #[cfg(feature = "vectordata")]
98            DatasetValue::Record(fragment) => {
99                format!("record {} of {}", fragment.ordinal, fragment.forms.origin)
100            }
101            #[cfg(not(feature = "vectordata"))]
102            _ => match *self {},
103        }
104    }
105}
106
107/// Two dataset values are equal when they are the same thing: the same
108/// admitted positions, the same forms, or the same record of the same
109/// forms. Forms compare by identity, since they are built once and
110/// shared.
111impl PartialEq for DatasetValue {
112    fn eq(&self, other: &Self) -> bool {
113        match (self, other) {
114            #[cfg(feature = "vectordata")]
115            (DatasetValue::AdmittedRows(a), DatasetValue::AdmittedRows(b)) => {
116                Arc::ptr_eq(a, b) || a == b
117            }
118            #[cfg(feature = "vectordata")]
119            (DatasetValue::PredicateForms(a), DatasetValue::PredicateForms(b)) => Arc::ptr_eq(a, b),
120            #[cfg(feature = "vectordata")]
121            (DatasetValue::RecordForms(a), DatasetValue::RecordForms(b)) => Arc::ptr_eq(a, b),
122            #[cfg(feature = "vectordata")]
123            (DatasetValue::Predicate(a), DatasetValue::Predicate(b)) => {
124                Arc::ptr_eq(&a.forms, &b.forms) && a.form == b.form && a.ordinal == b.ordinal
125            }
126            #[cfg(feature = "vectordata")]
127            (DatasetValue::Record(a), DatasetValue::Record(b)) => {
128                Arc::ptr_eq(&a.forms, &b.forms) && a.ordinal == b.ordinal
129            }
130            #[cfg(feature = "vectordata")]
131            _ => false,
132            #[cfg(not(feature = "vectordata"))]
133            _ => match *self {},
134        }
135    }
136}
137
138#[cfg(feature = "vectordata")]
139mod types {
140    use std::sync::Arc;
141
142    use vectordata::binding::{Binder, Layout};
143    use vectordata::predicate_forms::FormCensus;
144    use vectordata::records::RecordFacet;
145
146    /// The forms of a predicate facet, with what a host needs to bind
147    /// a predicate of any of them: a `forms` value.
148    ///
149    /// Built once, when a program is built, by reading every predicate
150    /// of the facet. A host prepares one statement per form of
151    /// [`census`](Self::census) from the form's template, compiles the
152    /// form's binder against [`layout`](Self::layout)
153    /// (`form.binder(&forms.layout)`), and keeps both by the form's
154    /// index. A form whose binder cannot be compiled is that call's
155    /// error, with `form.count()` predicates behind it; nothing here
156    /// refuses it. The strata the facet publishes are
157    /// `census.strata()`.
158    #[non_exhaustive]
159    pub struct PredicateForms {
160        /// Every distinct form of the facet's predicates, with its
161        /// template and count, and the form of the predicate at each
162        /// ordinal.
163        pub census: FormCensus,
164        /// The layout of the metadata records the predicates select
165        /// among, which types each condition's field.
166        pub layout: Layout,
167        /// The predicates themselves: the record of the predicate at
168        /// an ordinal is what a form's binder binds.
169        pub predicates: RecordFacet,
170        /// The dataset and profile, for diagnostics.
171        pub origin: String,
172    }
173
174    impl PredicateForms {
175        pub(crate) fn new(
176            census: FormCensus,
177            layout: Layout,
178            predicates: RecordFacet,
179            origin: String,
180        ) -> Self {
181            Self {
182                census,
183                layout,
184                predicates,
185                origin,
186            }
187        }
188    }
189
190    impl std::fmt::Debug for PredicateForms {
191        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192            f.debug_struct("PredicateForms")
193                .field("origin", &self.origin)
194                .field("forms", &self.census.forms().len())
195                .field("predicates", &self.census.count())
196                .finish()
197        }
198    }
199
200    /// The one form of a metadata record facet: its layout, with the
201    /// binder that reads every field of a record in layout order. A
202    /// `forms` value.
203    #[non_exhaustive]
204    pub struct RecordForms {
205        /// The names and types of a record's fields, in wire order.
206        pub layout: Layout,
207        /// Reads every field of a record, in layout order.
208        pub binder: Binder,
209        /// The records.
210        pub records: RecordFacet,
211        /// The dataset and profile, for diagnostics.
212        pub origin: String,
213    }
214
215    impl RecordForms {
216        pub(crate) fn new(layout: Layout, records: RecordFacet, origin: String) -> Self {
217            Self {
218                binder: Binder::all(&layout),
219                layout,
220                records,
221                origin,
222            }
223        }
224    }
225
226    impl std::fmt::Debug for RecordForms {
227        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228            f.debug_struct("RecordForms")
229                .field("origin", &self.origin)
230                .field("fields", &self.layout.names())
231                .finish()
232        }
233    }
234
235    /// One predicate for a cycle, as structure: a `fragment` value.
236    ///
237    /// It names the predicate and does not hold its bytes, so making
238    /// one allocates nothing and reads no record. A host selects what
239    /// it prepared for [`form`](Self::form), reads the record
240    /// (`forms.predicates.record_shared(ordinal)` or `record_bytes`),
241    /// and binds it through that form's binder.
242    #[derive(Debug, Clone)]
243    #[non_exhaustive]
244    pub struct PredicateFragment {
245        /// The forms this predicate is one of.
246        pub forms: Arc<PredicateForms>,
247        /// The index of this predicate's form in `forms.census.forms()`.
248        pub form: u32,
249        /// The predicate's ordinal in the facet: a query ordinal.
250        pub ordinal: u64,
251    }
252
253    impl PredicateFragment {
254        pub(crate) fn new(forms: Arc<PredicateForms>, form: u32, ordinal: u64) -> Self {
255            Self {
256                forms,
257                form,
258                ordinal,
259            }
260        }
261    }
262
263    /// One metadata record for a cycle, as structure: a `fragment`
264    /// value. Like [`PredicateFragment`], it names the record and does
265    /// not hold its bytes; a host reads the record
266    /// (`forms.records.record_shared(ordinal)` or `record_bytes`) and
267    /// binds it through `forms.binder`.
268    #[derive(Debug, Clone)]
269    #[non_exhaustive]
270    pub struct RecordFragment {
271        /// The record facet's one form.
272        pub forms: Arc<RecordForms>,
273        /// The record's ordinal in the facet: a base ordinal.
274        pub ordinal: u64,
275    }
276
277    impl RecordFragment {
278        pub(crate) fn new(forms: Arc<RecordForms>, ordinal: u64) -> Self {
279            Self { forms, ordinal }
280        }
281    }
282}
283
284/// The `vectordata` types a host works with when it binds a fragment
285/// or reads forms, re-exported at vectordata's own paths so a host
286/// that reaches datasets only through polydat can name them. These are
287/// vectordata's types, not copies: a breaking release of vectordata
288/// that changes one is a breaking change here.
289///
290/// The node enums (`formats::mnode::MValue`, `formats::pnode::OpType`,
291/// `formats::pnode::Comparand`) are
292/// exhaustive on purpose, so a host's `match` over one stops compiling
293/// when vectordata adds a kind, rather than binding the new kind as
294/// something else.
295#[cfg(feature = "vectordata")]
296pub mod vectordata {
297    /// The record codec stage: a record as a typed node.
298    pub mod formats {
299        /// Any record, decoded.
300        pub mod anode {
301            pub use ::vectordata::formats::anode::{ANode, decode, encode};
302        }
303        /// A metadata record, and one field of it read in place.
304        pub mod mnode {
305            pub use ::vectordata::formats::mnode::{MNode, MValue, TypeTag};
306            /// A field of a record, read without decoding the record.
307            pub mod scan {
308                pub use ::vectordata::formats::mnode::scan::Field;
309            }
310        }
311        /// A predicate record, and a predicate with its comparands
312        /// left open.
313        pub mod pnode {
314            pub use ::vectordata::formats::pnode::{
315                Comparand, ConjugateNode, ConjugateType, FieldRef, OpType, PNode, PredicateNode,
316            };
317            /// A predicate's structure with its comparands as slots:
318            /// what a host renders once per form.
319            pub mod template {
320                pub use ::vectordata::formats::pnode::template::{
321                    PredicateTemplate, parse_template,
322                };
323            }
324        }
325    }
326    /// Layouts and the binders that read a record's values.
327    pub mod binding {
328        pub use ::vectordata::binding::{
329            BindError, BindType, Binder, Condition, Layout, LayoutSource, Nullability,
330            PredicateBinder,
331        };
332    }
333    /// The forms of a predicate facet.
334    pub mod predicate_forms {
335        pub use ::vectordata::predicate_forms::{
336            Access, FormCensus, PredicateForm, PredicateStrata,
337        };
338    }
339    /// Record facets, their bytes, and the packaged text renderings.
340    pub mod records {
341        pub use ::vectordata::records::{
342            RecordCodec, RecordError, RecordFacet, SharedBytes, codec_by_name, codec_names,
343        };
344    }
345    /// The rows a predicate admits.
346    pub mod ground_truth {
347        pub use ::vectordata::ground_truth::OrdinalSet;
348    }
349}
350
351#[cfg(feature = "vectordata")]
352mod wires {
353    use std::sync::Arc;
354
355    use vectordata::ground_truth::OrdinalSet;
356
357    use super::{DatasetValue, PredicateForms, PredicateFragment, RecordForms, RecordFragment};
358    use crate::ast::{PortType, Value};
359    use crate::derive_support::{Wire, extract_mismatch};
360
361    /// A shared dataset value as a node's argument or result: the
362    /// rows a predicate admits (`Shared<OrdinalSet>`, an
363    /// `admitted_rows` wire) or the forms of a facet
364    /// (`Shared<PredicateForms>`, `Shared<RecordForms>`, a `forms`
365    /// wire). It derefs to the value. A node function names this
366    /// rather than the `Arc` inside it, because a bare `Arc<T>`
367    /// argument is an untyped `handle` wire to the node macro.
368    #[derive(Debug)]
369    pub struct Shared<T>(pub Arc<T>);
370
371    impl<T> Clone for Shared<T> {
372        fn clone(&self) -> Self {
373            Shared(self.0.clone())
374        }
375    }
376
377    impl<T> std::ops::Deref for Shared<T> {
378        type Target = T;
379        fn deref(&self) -> &T {
380            &self.0
381        }
382    }
383
384    /// A value of the right port type and the wrong kind: the forms of
385    /// a record facet where a predicate facet's were wanted. The port
386    /// type cannot tell the two apart, so this is a program's error and
387    /// is said in its terms.
388    fn wrong_kind(wanted: &str, got: &DatasetValue) -> ! {
389        let got = match got {
390            DatasetValue::AdmittedRows(_) => "the rows a predicate admits",
391            DatasetValue::PredicateForms(_) => "the forms of a predicate facet",
392            DatasetValue::RecordForms(_) => "the forms of a record facet",
393            DatasetValue::Predicate(_) => "a predicate fragment",
394            DatasetValue::Record(_) => "a record fragment",
395        };
396        panic!("expected {wanted}, got {got}")
397    }
398
399    /// The rows a predicate admits: an `admitted_rows` wire.
400    impl Wire for Shared<OrdinalSet> {
401        const PORT: PortType = PortType::AdmittedRows;
402        fn extract(v: &Value) -> Self {
403            match v {
404                Value::Dataset(DatasetValue::AdmittedRows(set)) => Shared(set.clone()),
405                other => extract_mismatch("Shared<OrdinalSet>", Self::PORT, other),
406            }
407        }
408        fn inject(self) -> Value {
409            Value::Dataset(DatasetValue::AdmittedRows(self.0))
410        }
411    }
412
413    /// The forms of a predicate facet: a `forms` wire.
414    impl Wire for Shared<PredicateForms> {
415        const PORT: PortType = PortType::Forms;
416        fn extract(v: &Value) -> Self {
417            match v {
418                Value::Dataset(DatasetValue::PredicateForms(forms)) => Shared(forms.clone()),
419                Value::Dataset(d @ DatasetValue::RecordForms(_)) => {
420                    wrong_kind("the forms of a predicate facet", d)
421                }
422                other => extract_mismatch("Shared<PredicateForms>", Self::PORT, other),
423            }
424        }
425        fn inject(self) -> Value {
426            Value::Dataset(DatasetValue::PredicateForms(self.0))
427        }
428    }
429
430    /// The forms of a record facet: a `forms` wire.
431    impl Wire for Shared<RecordForms> {
432        const PORT: PortType = PortType::Forms;
433        fn extract(v: &Value) -> Self {
434            match v {
435                Value::Dataset(DatasetValue::RecordForms(forms)) => Shared(forms.clone()),
436                Value::Dataset(d @ DatasetValue::PredicateForms(_)) => {
437                    wrong_kind("the forms of a record facet", d)
438                }
439                other => extract_mismatch("Shared<RecordForms>", Self::PORT, other),
440            }
441        }
442        fn inject(self) -> Value {
443            Value::Dataset(DatasetValue::RecordForms(self.0))
444        }
445    }
446
447    /// One predicate as structure: a `fragment` wire.
448    impl Wire for PredicateFragment {
449        const PORT: PortType = PortType::Fragment;
450        fn extract(v: &Value) -> Self {
451            match v {
452                Value::Dataset(DatasetValue::Predicate(fragment)) => fragment.clone(),
453                Value::Dataset(d @ DatasetValue::Record(_)) => {
454                    wrong_kind("a predicate fragment", d)
455                }
456                other => extract_mismatch("PredicateFragment", Self::PORT, other),
457            }
458        }
459        fn inject(self) -> Value {
460            Value::Dataset(DatasetValue::Predicate(self))
461        }
462    }
463
464    /// One metadata record as structure: a `fragment` wire.
465    impl Wire for RecordFragment {
466        const PORT: PortType = PortType::Fragment;
467        fn extract(v: &Value) -> Self {
468            match v {
469                Value::Dataset(DatasetValue::Record(fragment)) => fragment.clone(),
470                Value::Dataset(d @ DatasetValue::Predicate(_)) => {
471                    wrong_kind("a record fragment", d)
472                }
473                other => extract_mismatch("RecordFragment", Self::PORT, other),
474            }
475        }
476        fn inject(self) -> Value {
477            Value::Dataset(DatasetValue::Record(self))
478        }
479    }
480}