Skip to main content

polydat_grammar/
port_type.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The port type vocabulary: every type a wire, a port, a cast, or a
5//! declaration can name, with its keyword. What a type means to a
6//! compiled buffer (its slot color, width, and scratch element) is
7//! the runtime's, defined on this type by `polydat-core`.
8
9use std::fmt;
10
11/// Compile-time type tag for a port on a Polydat node.
12///
13/// **Narrow types and runtime storage:**
14///
15/// `PortType` includes narrow integer and float variants (U8/U16/U32,
16/// I8/I16/I32, F16/F32) that have no `Value` of their own. At
17/// runtime, narrow values are stored in the wide `Value` of their
18/// kind, with the assumption that the bits fit:
19///
20/// - unsigned (`u8`, `u16`, `u32`) → zero-extended in `Value::U64`
21/// - signed (`i8`, `i16`, `i32`) → sign-extended in `Value::I64`
22/// - `f32` → losslessly widened in `Value::F64` (`f16` rides
23///   `Value::U64` as its bit pattern; see [`PortType::F16`])
24///
25/// The narrow `PortType` variants exist for compile-time type
26/// checking and auto-adapter insertion (`U32ToU64`, `F32ToF64`).
27/// P2/P3 compiled kernels use flat u64 buffers where this packing
28/// is natural. The `Value` enum stays small — no combinatorial
29/// explosion of narrow variant types.
30///
31/// Every input and output port declares its `PortType`. The assembler
32/// uses these to validate wiring and auto-insert type adapters (e.g.,
33/// `u64 → f64` widening). At runtime, the corresponding `Value`
34/// variant is used.
35///
36/// **Widening rules** (auto-inserted by the assembler):
37/// - `U32 → U64`, `I32 → I64`, `F32 → F64` (lossless widening)
38/// - `U64 → F64` (lossless for values < 2^53)
39/// - `Bool → U64` (true=1, false=0)
40/// - Any type → `Str` (via display conversion)
41///
42/// **Narrowing** is never implicit — use explicit cast functions.
43///
44/// **Exhaustive on purpose.** The language grows a type now and then,
45/// and a `match` over every variant is then a compile error until it
46/// decides what the new type means. Polydat's own code relies on that,
47/// and so should a host's code that behaves differently per type. A host
48/// that only names or classifies types should not match at all: use
49/// [`Self::to_keyword`] or `Display` for a label, [`Self::from_keyword`]
50/// to parse one, and [`Self::numeric_domain`] or polydat's `SlotShape`
51/// queries to classify, none of which breaks when a type is added.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum PortType {
54    /// 64-bit unsigned integer. The primary numeric type.
55    U64,
56    /// 64-bit IEEE 754 float. Used for math, distributions, noise.
57    F64,
58    /// 32-bit unsigned integer. Widens to U64 automatically.
59    U32,
60    /// 32-bit signed integer. Widens to I64 automatically.
61    I32,
62    /// 64-bit signed integer.
63    I64,
64    /// 32-bit IEEE 754 float. Widens to F64 automatically.
65    F32,
66    /// 8-bit unsigned integer (cranelift I8 lane, unsigned
67    /// interpretation). Zero-extended in `Value::U64`; widens to
68    /// U64 automatically.
69    U8,
70    /// 8-bit signed integer (cranelift I8 lane, signed
71    /// interpretation). Sign-extended in `Value::I64`; widens to
72    /// I64 automatically.
73    I8,
74    /// 16-bit unsigned integer (cranelift I16 lane, unsigned
75    /// interpretation). Zero-extended in `Value::U64`; widens to
76    /// U64 automatically.
77    U16,
78    /// 16-bit signed integer (cranelift I16 lane, signed
79    /// interpretation). Sign-extended in `Value::I64`; widens to
80    /// I64 automatically.
81    I16,
82    /// 16-bit IEEE 754-2008 binary16 float (cranelift F16).
83    /// Carried as its bit pattern in `Value::U64` (low 16 bits),
84    /// the same stuffing convention as `F32`; widens to F32/F64
85    /// automatically (every f16 is exactly representable in both).
86    F16,
87    /// 128-bit unsigned integer (cranelift I128, unsigned
88    /// interpretation). Real `Value::U128` two-limb carrier — a
89    /// 128-bit value cannot ride a 64-bit slot. Rides two
90    /// consecutive u64 slots (a limb pair) on the compiled engines.
91    U128,
92    /// 128-bit signed integer (cranelift I128, signed
93    /// interpretation). Same carrier story as `U128`.
94    I128,
95    /// 128-bit SIMD register word, raw view — the full word as
96    /// algorithm-defined buffer state (heterogeneous lane
97    /// roles). Free bitcast to/from every lane-typed view.
98    Reg128,
99    /// Register word viewed as 16 × i8 lanes.
100    RegI8x16,
101    /// Register word viewed as 8 × i16 lanes.
102    RegI16x8,
103    /// Register word viewed as 4 × i32 lanes.
104    RegI32x4,
105    /// Register word viewed as 2 × i64 lanes.
106    RegI64x2,
107    /// Register word viewed as 8 × f16 lanes.
108    RegF16x8,
109    /// Register word viewed as 4 × f32 lanes.
110    RegF32x4,
111    /// Register word viewed as 2 × f64 lanes.
112    RegF64x2,
113    /// Boolean (true/false). Widens to U64 (1/0).
114    Bool,
115    /// Heap-allocated string. Any type auto-converts to Str.
116    Str,
117    /// Raw byte buffer.
118    Bytes,
119    /// Structured JSON value.
120    Json,
121    /// Adapter-contributed reflected type (e.g., CQL UUID).
122    Ext,
123    /// Type-erased Arc handle to a resolved resource (dataset,
124    /// prepared statement, ...). The producer node populates an
125    /// `Arc<dyn Any + Send + Sync>`; the consumer node downcasts to
126    /// the concrete type via `Value::as_handle::<T>()`.
127    Handle,
128    /// Typed `f32` vector slice (`Arc<[f32]>`). Bound natively by
129    /// adapters that understand `[f32]` (CQL `vector<float, N>`).
130    VecF32,
131    /// Typed `i32` vector slice (`Arc<[i32]>`).
132    VecI32,
133    /// Typed `f64` vector slice (`Arc<[f64]>`). Bound natively
134    /// for CQL `vector<double, N>`.
135    VecF64,
136    /// Typed `i64` vector slice (`Arc<[i64]>`). Bound natively
137    /// for CQL `vector<bigint, N>`.
138    VecI64,
139    /// Typed half-precision float vector (`Arc<[half::f16]>`).
140    /// Bound natively for CQL `vector<half_float, N>`-style
141    /// columns; stays at f16 on the wire so embeddings stored
142    /// as 16-bit floats don't widen to f32 at the boundary.
143    VecF16,
144    /// Typed `i16` vector slice (`Arc<[i16]>`). Bound natively
145    /// for CQL `vector<smallint, N>`.
146    VecI16,
147    /// Typed `i8` vector slice (`Arc<[i8]>`). Completes the
148    /// cranelift lane family; CQL `vector<tinyint, N>`.
149    VecI8,
150    /// Any value, as written: the slot of an input whose type may vary
151    /// over a kernel's lifetime (input_variance.md). Only a converter
152    /// node reads it, turning the value into the type its consumers
153    /// read; no other port has this type, and no value is typed `Dyn`.
154    Dyn,
155}
156
157/// A port type displays as its keyword ([`PortType::to_keyword`]), so
158/// source synthesized through `Display`, such as `extern x: {ty}`,
159/// parses back to the same type.
160impl fmt::Display for PortType {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.write_str(self.to_keyword())
163    }
164}
165
166/// The set of numbers a scalar port type can carry, described by the
167/// properties that decide whether one of them holds every value of
168/// another: how many bits the representation has, and how it spends
169/// them.
170///
171/// `Bool` is the one-bit unsigned domain, which is what the type
172/// system already says of it — it widens to `U64` as 1 and 0.
173/// Non-scalar types (`Str`, `Bytes`, `Json`, the vectors, the
174/// register views, `Ext`, `Handle`) have no domain.
175#[derive(Clone, Copy, PartialEq, Eq, Debug)]
176pub enum NumericDomain {
177    /// Non-negative integers in `0 ..= 2^bits - 1`.
178    Unsigned {
179        /// Width of the representation.
180        bits: u32,
181    },
182    /// Two's-complement integers, one of whose bits is the sign.
183    Signed {
184        /// Width of the representation, sign bit included.
185        bits: u32,
186    },
187    /// An IEEE 754 binary float.
188    Float {
189        /// Significand bits, the implicit leading one included: the
190        /// largest integer represented exactly is `2^mantissa`.
191        mantissa: u32,
192        /// Exponent bits, which fix the magnitude range.
193        exponent: u32,
194    },
195}
196
197impl NumericDomain {
198    /// Whether every value of this domain is a value of `other` —
199    /// that is, whether a conversion into `other` is lossless.
200    ///
201    /// Integers fit by counting the bits each spends on magnitude: an
202    /// unsigned domain needs a signed one strictly wider, a signed
203    /// domain never fits an unsigned one. An integer fits a float
204    /// when its magnitude bits fit the float's significand, which is
205    /// why `U64 → F64` does not: 64 magnitude bits do not fit 53, and
206    /// the values above `2^53` round. A float fits a wider float when
207    /// both its significand and its exponent do.
208    pub fn fits_in(self, other: Self) -> bool {
209        use NumericDomain::{Float, Signed, Unsigned};
210        match (self, other) {
211            (Unsigned { bits: a }, Unsigned { bits: b }) => a <= b,
212            (Unsigned { bits: a }, Signed { bits: b }) => a < b,
213            (Signed { bits: a }, Signed { bits: b }) => a <= b,
214            (Signed { .. }, Unsigned { .. }) => false,
215            (Unsigned { bits }, Float { mantissa, .. }) => bits <= mantissa,
216            (Signed { bits }, Float { mantissa, .. }) => bits - 1 <= mantissa,
217            (Float { .. }, Unsigned { .. } | Signed { .. }) => false,
218            (
219                Float {
220                    mantissa: m1,
221                    exponent: e1,
222                },
223                Float {
224                    mantissa: m2,
225                    exponent: e2,
226                },
227            ) => m1 <= m2 && e1 <= e2,
228        }
229    }
230}
231
232impl PortType {
233    /// Every port type, once.
234    ///
235    /// A test that must hold for *all* types can walk this rather than
236    /// name the ones its author thought of, so a mapping such as the
237    /// value↔slot writers is checked complete rather than complete for
238    /// the types some program happened to use.
239    ///
240    /// [`Self::every_variant_is_listed`] keeps this honest — it is an
241    /// exhaustive `match`, so adding a variant without adding it here
242    /// fails to compile rather than quietly shrinking every sweep that
243    /// walks this list.
244    pub const ALL: &'static [PortType] = &[
245        PortType::U64,
246        PortType::F64,
247        PortType::U32,
248        PortType::I32,
249        PortType::I64,
250        PortType::F32,
251        PortType::U8,
252        PortType::I8,
253        PortType::U16,
254        PortType::I16,
255        PortType::F16,
256        PortType::U128,
257        PortType::I128,
258        PortType::Reg128,
259        PortType::RegI8x16,
260        PortType::RegI16x8,
261        PortType::RegI32x4,
262        PortType::RegI64x2,
263        PortType::RegF16x8,
264        PortType::RegF32x4,
265        PortType::RegF64x2,
266        PortType::Bool,
267        PortType::Str,
268        PortType::Bytes,
269        PortType::Json,
270        PortType::Ext,
271        PortType::Handle,
272        PortType::VecF32,
273        PortType::VecI32,
274        PortType::VecF64,
275        PortType::VecI64,
276        PortType::VecF16,
277        PortType::VecI16,
278        PortType::VecI8,
279        PortType::Dyn,
280    ];
281
282    /// `true` for every variant, by an exhaustive match: the compiler
283    /// refuses this function when a variant is added, and the test
284    /// beside it checks [`Self::ALL`] carries the one that was added.
285    #[doc(hidden)]
286    pub fn every_variant_is_listed(self) -> bool {
287        match self {
288            PortType::U64
289            | PortType::F64
290            | PortType::U32
291            | PortType::I32
292            | PortType::I64
293            | PortType::F32
294            | PortType::U8
295            | PortType::I8
296            | PortType::U16
297            | PortType::I16
298            | PortType::F16
299            | PortType::U128
300            | PortType::I128
301            | PortType::Reg128
302            | PortType::RegI8x16
303            | PortType::RegI16x8
304            | PortType::RegI32x4
305            | PortType::RegI64x2
306            | PortType::RegF16x8
307            | PortType::RegF32x4
308            | PortType::RegF64x2
309            | PortType::Bool
310            | PortType::Str
311            | PortType::Bytes
312            | PortType::Json
313            | PortType::Ext
314            | PortType::Handle
315            | PortType::VecF32
316            | PortType::VecI32
317            | PortType::VecF64
318            | PortType::VecI64
319            | PortType::VecF16
320            | PortType::VecI16
321            | PortType::VecI8
322            | PortType::Dyn => Self::ALL.contains(&self),
323        }
324    }
325
326    /// The numbers this type can carry, for the types that carry
327    /// numbers. `None` for every other type.
328    ///
329    /// This is what decides whether a conversion between two types
330    /// keeps the value, so that the answer is read off the types
331    /// themselves rather than kept in a list of pairs beside them.
332    pub fn numeric_domain(self) -> Option<NumericDomain> {
333        use NumericDomain::{Float, Signed, Unsigned};
334        Some(match self {
335            Self::Bool => Unsigned { bits: 1 },
336            Self::U8 => Unsigned { bits: 8 },
337            Self::U16 => Unsigned { bits: 16 },
338            Self::U32 => Unsigned { bits: 32 },
339            Self::U64 => Unsigned { bits: 64 },
340            Self::U128 => Unsigned { bits: 128 },
341            Self::I8 => Signed { bits: 8 },
342            Self::I16 => Signed { bits: 16 },
343            Self::I32 => Signed { bits: 32 },
344            Self::I64 => Signed { bits: 64 },
345            Self::I128 => Signed { bits: 128 },
346            Self::F16 => Float {
347                mantissa: 11,
348                exponent: 5,
349            },
350            Self::F32 => Float {
351                mantissa: 24,
352                exponent: 8,
353            },
354            Self::F64 => Float {
355                mantissa: 53,
356                exponent: 11,
357            },
358            Self::Str
359            | Self::Bytes
360            | Self::Json
361            | Self::Ext
362            | Self::Handle
363            | Self::Reg128
364            | Self::RegI8x16
365            | Self::RegI16x8
366            | Self::RegI32x4
367            | Self::RegI64x2
368            | Self::RegF16x8
369            | Self::RegF32x4
370            | Self::RegF64x2
371            | Self::VecF32
372            | Self::VecI32
373            | Self::VecF64
374            | Self::VecI64
375            | Self::VecF16
376            | Self::VecI16
377            | Self::VecI8
378            | Self::Dyn => return None,
379        })
380    }
381
382    /// The canonical lowercase keyword for this `PortType`.
383    ///
384    /// This is the single source of truth for the str↔PortType
385    /// mapping used by every synthesizer and parser in the
386    /// workspace — synthesized polydat source (`extern <name>:
387    /// <keyword>`), the workload-author `{name:<keyword>}` lvalue
388    /// spec, and reverse parsing via [`Self::from_keyword`].
389    /// Inverse of [`Self::from_keyword`].
390    ///
391    /// Exhaustive over the enum — adding a new `PortType` variant
392    /// is a compile error here, forcing the addition of its
393    /// canonical keyword and the round-trip closure to update.
394    pub fn to_keyword(&self) -> &'static str {
395        match self {
396            Self::U64 => "u64",
397            Self::F64 => "f64",
398            Self::U32 => "u32",
399            Self::I32 => "i32",
400            Self::I64 => "i64",
401            Self::F32 => "f32",
402            Self::U8 => "u8",
403            Self::I8 => "i8",
404            Self::U16 => "u16",
405            Self::I16 => "i16",
406            Self::F16 => "f16",
407            Self::U128 => "u128",
408            Self::I128 => "i128",
409            Self::Reg128 => "reg128",
410            Self::RegI8x16 => "reg_i8x16",
411            Self::RegI16x8 => "reg_i16x8",
412            Self::RegI32x4 => "reg_i32x4",
413            Self::RegI64x2 => "reg_i64x2",
414            Self::RegF16x8 => "reg_f16x8",
415            Self::RegF32x4 => "reg_f32x4",
416            Self::RegF64x2 => "reg_f64x2",
417            Self::Bool => "bool",
418            Self::Str => "str",
419            Self::Bytes => "bytes",
420            Self::Json => "json",
421            Self::Ext => "ext",
422            Self::Handle => "handle",
423            Self::VecF32 => "vec_f32",
424            Self::VecI32 => "vec_i32",
425            Self::VecF64 => "vec_f64",
426            Self::VecI64 => "vec_i64",
427            Self::VecF16 => "vec_f16",
428            Self::VecI16 => "vec_i16",
429            Self::VecI8 => "vec_i8",
430            Self::Dyn => "dyn",
431        }
432    }
433
434    /// Parse a polydat type keyword into a `PortType`.
435    ///
436    /// Inverse of [`Self::to_keyword`]: accepts every keyword
437    /// that `to_keyword` emits, plus a small set of legacy aliases
438    /// (`"String"`, `"Json"`, `"Ext"`) that survive in older
439    /// hand-written workload source. Returns `None` for any
440    /// unrecognized keyword so callers can surface a loud
441    /// diagnostic rather than silently coercing to a default.
442    ///
443    /// Used by the DSL `extern <name>: <keyword>` parser
444    /// (`polydat-core/src/dsl/compile.rs`). Round-trips cleanly with
445    /// any source `to_keyword` emits.
446    pub fn from_keyword(name: &str) -> Option<Self> {
447        match name {
448            "u64" => Some(Self::U64),
449            "f64" => Some(Self::F64),
450            "u32" => Some(Self::U32),
451            "i32" => Some(Self::I32),
452            "i64" => Some(Self::I64),
453            "f32" => Some(Self::F32),
454            "u8" => Some(Self::U8),
455            "i8" => Some(Self::I8),
456            "u16" => Some(Self::U16),
457            "i16" => Some(Self::I16),
458            "f16" => Some(Self::F16),
459            "u128" => Some(Self::U128),
460            "i128" => Some(Self::I128),
461            "reg128" => Some(Self::Reg128),
462            "reg_i8x16" => Some(Self::RegI8x16),
463            "reg_i16x8" => Some(Self::RegI16x8),
464            "reg_i32x4" => Some(Self::RegI32x4),
465            "reg_i64x2" => Some(Self::RegI64x2),
466            "reg_f16x8" => Some(Self::RegF16x8),
467            "reg_f32x4" => Some(Self::RegF32x4),
468            "reg_f64x2" => Some(Self::RegF64x2),
469            "bool" => Some(Self::Bool),
470            "str" | "Str" | "String" => Some(Self::Str),
471            "bytes" => Some(Self::Bytes),
472            "json" | "Json" => Some(Self::Json),
473            "ext" | "Ext" => Some(Self::Ext),
474            "handle" => Some(Self::Handle),
475            "vec_f32" => Some(Self::VecF32),
476            "vec_i32" => Some(Self::VecI32),
477            "vec_f64" => Some(Self::VecF64),
478            "vec_i64" => Some(Self::VecI64),
479            "vec_f16" => Some(Self::VecF16),
480            "vec_i16" => Some(Self::VecI16),
481            "vec_i8" => Some(Self::VecI8),
482            "dyn" => Some(Self::Dyn),
483            _ => None,
484        }
485    }
486
487    /// Workload-author-facing parser for the `{name:<keyword>}`
488    /// lvalue-spec surface. Strict subset of [`Self::from_keyword`]
489    /// — `handle` and `ext` are rejected because they're
490    /// internal-only types a workload author should never assert.
491    ///
492    /// Returns `None` for any unrecognized name; the caller
493    /// surfaces the unknown spec as a workload-shape diagnostic.
494    pub fn from_workload_name(name: &str) -> Option<Self> {
495        match Self::from_keyword(name)? {
496            Self::Handle | Self::Ext => None,
497            pt => Some(pt),
498        }
499    }
500}