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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum PortType {
45    /// 64-bit unsigned integer. The primary numeric type.
46    U64,
47    /// 64-bit IEEE 754 float. Used for math, distributions, noise.
48    F64,
49    /// 32-bit unsigned integer. Widens to U64 automatically.
50    U32,
51    /// 32-bit signed integer. Widens to I64 automatically.
52    I32,
53    /// 64-bit signed integer.
54    I64,
55    /// 32-bit IEEE 754 float. Widens to F64 automatically.
56    F32,
57    /// 8-bit unsigned integer (cranelift I8 lane, unsigned
58    /// interpretation). Zero-extended in `Value::U64`; widens to
59    /// U64 automatically.
60    U8,
61    /// 8-bit signed integer (cranelift I8 lane, signed
62    /// interpretation). Sign-extended in `Value::I64`; widens to
63    /// I64 automatically.
64    I8,
65    /// 16-bit unsigned integer (cranelift I16 lane, unsigned
66    /// interpretation). Zero-extended in `Value::U64`; widens to
67    /// U64 automatically.
68    U16,
69    /// 16-bit signed integer (cranelift I16 lane, signed
70    /// interpretation). Sign-extended in `Value::I64`; widens to
71    /// I64 automatically.
72    I16,
73    /// 16-bit IEEE 754-2008 binary16 float (cranelift F16).
74    /// Carried as its bit pattern in `Value::U64` (low 16 bits),
75    /// the same stuffing convention as `F32`; widens to F32/F64
76    /// automatically (every f16 is exactly representable in both).
77    F16,
78    /// 128-bit unsigned integer (cranelift I128, unsigned
79    /// interpretation). Real `Value::U128` two-limb carrier — a
80    /// 128-bit value cannot ride a 64-bit slot. Rides two
81    /// consecutive u64 slots (a limb pair) on the compiled engines.
82    U128,
83    /// 128-bit signed integer (cranelift I128, signed
84    /// interpretation). Same carrier story as `U128`.
85    I128,
86    /// 128-bit SIMD register word, raw view — the full word as
87    /// algorithm-defined buffer state (heterogeneous lane
88    /// roles). Free bitcast to/from every lane-typed view.
89    Reg128,
90    /// Register word viewed as 16 × i8 lanes.
91    RegI8x16,
92    /// Register word viewed as 8 × i16 lanes.
93    RegI16x8,
94    /// Register word viewed as 4 × i32 lanes.
95    RegI32x4,
96    /// Register word viewed as 2 × i64 lanes.
97    RegI64x2,
98    /// Register word viewed as 8 × f16 lanes.
99    RegF16x8,
100    /// Register word viewed as 4 × f32 lanes.
101    RegF32x4,
102    /// Register word viewed as 2 × f64 lanes.
103    RegF64x2,
104    /// Boolean (true/false). Widens to U64 (1/0).
105    Bool,
106    /// Heap-allocated string. Any type auto-converts to Str.
107    Str,
108    /// Raw byte buffer.
109    Bytes,
110    /// Structured JSON value.
111    Json,
112    /// Adapter-contributed reflected type (e.g., CQL UUID).
113    Ext,
114    /// Type-erased Arc handle to a resolved resource (dataset,
115    /// prepared statement, ...). The producer node populates an
116    /// `Arc<dyn Any + Send + Sync>`; the consumer node downcasts to
117    /// the concrete type via `Value::as_handle::<T>()`.
118    Handle,
119    /// Typed `f32` vector slice (`Arc<[f32]>`). Bound natively by
120    /// adapters that understand `[f32]` (CQL `vector<float, N>`).
121    VecF32,
122    /// Typed `i32` vector slice (`Arc<[i32]>`).
123    VecI32,
124    /// Typed `f64` vector slice (`Arc<[f64]>`). Bound natively
125    /// for CQL `vector<double, N>`.
126    VecF64,
127    /// Typed `i64` vector slice (`Arc<[i64]>`). Bound natively
128    /// for CQL `vector<bigint, N>`.
129    VecI64,
130    /// Typed half-precision float vector (`Arc<[half::f16]>`).
131    /// Bound natively for CQL `vector<half_float, N>`-style
132    /// columns; stays at f16 on the wire so embeddings stored
133    /// as 16-bit floats don't widen to f32 at the boundary.
134    VecF16,
135    /// Typed `i16` vector slice (`Arc<[i16]>`). Bound natively
136    /// for CQL `vector<smallint, N>`.
137    VecI16,
138    /// Typed `i8` vector slice (`Arc<[i8]>`). Completes the
139    /// cranelift lane family; CQL `vector<tinyint, N>`.
140    VecI8,
141}
142
143impl fmt::Display for PortType {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        match self {
146            PortType::U64 => write!(f, "u64"),
147            PortType::F64 => write!(f, "f64"),
148            PortType::U32 => write!(f, "u32"),
149            PortType::I32 => write!(f, "i32"),
150            PortType::I64 => write!(f, "i64"),
151            PortType::F32 => write!(f, "f32"),
152            PortType::U8 => write!(f, "u8"),
153            PortType::I8 => write!(f, "i8"),
154            PortType::U16 => write!(f, "u16"),
155            PortType::I16 => write!(f, "i16"),
156            PortType::F16 => write!(f, "f16"),
157            PortType::U128 => write!(f, "u128"),
158            PortType::I128 => write!(f, "i128"),
159            PortType::Reg128 => write!(f, "reg128"),
160            PortType::RegI8x16 => write!(f, "reg_i8x16"),
161            PortType::RegI16x8 => write!(f, "reg_i16x8"),
162            PortType::RegI32x4 => write!(f, "reg_i32x4"),
163            PortType::RegI64x2 => write!(f, "reg_i64x2"),
164            PortType::RegF16x8 => write!(f, "reg_f16x8"),
165            PortType::RegF32x4 => write!(f, "reg_f32x4"),
166            PortType::RegF64x2 => write!(f, "reg_f64x2"),
167            PortType::Bool => write!(f, "bool"),
168            PortType::Str => write!(f, "String"),
169            PortType::Bytes => write!(f, "bytes"),
170            PortType::Json => write!(f, "json"),
171            PortType::Ext => write!(f, "ext"),
172            PortType::Handle => write!(f, "handle"),
173            PortType::VecF32 => write!(f, "vec_f32"),
174            PortType::VecI32 => write!(f, "vec_i32"),
175            PortType::VecF64 => write!(f, "vec_f64"),
176            PortType::VecI64 => write!(f, "vec_i64"),
177            PortType::VecF16 => write!(f, "vec_f16"),
178            PortType::VecI16 => write!(f, "vec_i16"),
179            PortType::VecI8 => write!(f, "vec_i8"),
180        }
181    }
182}
183
184impl PortType {
185    /// The canonical lowercase keyword for this `PortType`.
186    ///
187    /// This is the single source of truth for the str↔PortType
188    /// mapping used by every synthesizer and parser in the
189    /// workspace — synthesized polydat source (`extern <name>:
190    /// <keyword>`), the workload-author `{name:<keyword>}` lvalue
191    /// spec, and reverse parsing via [`Self::from_keyword`].
192    /// Inverse of [`Self::from_keyword`].
193    ///
194    /// Exhaustive over the enum — adding a new `PortType` variant
195    /// is a compile error here, forcing the addition of its
196    /// canonical keyword and the round-trip closure to update.
197    pub fn to_keyword(&self) -> &'static str {
198        match self {
199            Self::U64 => "u64",
200            Self::F64 => "f64",
201            Self::U32 => "u32",
202            Self::I32 => "i32",
203            Self::I64 => "i64",
204            Self::F32 => "f32",
205            Self::U8 => "u8",
206            Self::I8 => "i8",
207            Self::U16 => "u16",
208            Self::I16 => "i16",
209            Self::F16 => "f16",
210            Self::U128 => "u128",
211            Self::I128 => "i128",
212            Self::Reg128 => "reg128",
213            Self::RegI8x16 => "reg_i8x16",
214            Self::RegI16x8 => "reg_i16x8",
215            Self::RegI32x4 => "reg_i32x4",
216            Self::RegI64x2 => "reg_i64x2",
217            Self::RegF16x8 => "reg_f16x8",
218            Self::RegF32x4 => "reg_f32x4",
219            Self::RegF64x2 => "reg_f64x2",
220            Self::Bool => "bool",
221            Self::Str => "str",
222            Self::Bytes => "bytes",
223            Self::Json => "json",
224            Self::Ext => "ext",
225            Self::Handle => "handle",
226            Self::VecF32 => "vec_f32",
227            Self::VecI32 => "vec_i32",
228            Self::VecF64 => "vec_f64",
229            Self::VecI64 => "vec_i64",
230            Self::VecF16 => "vec_f16",
231            Self::VecI16 => "vec_i16",
232            Self::VecI8 => "vec_i8",
233        }
234    }
235
236    /// Parse a polydat type keyword into a `PortType`.
237    ///
238    /// Inverse of [`Self::to_keyword`]: accepts every keyword
239    /// that `to_keyword` emits, plus a small set of legacy aliases
240    /// (`"String"`, `"Json"`, `"Ext"`) that survive in older
241    /// hand-written workload source. Returns `None` for any
242    /// unrecognized keyword so callers can surface a loud
243    /// diagnostic rather than silently coercing to a default.
244    ///
245    /// Used by the DSL `extern <name>: <keyword>` parser
246    /// (`polydat-core/src/dsl/compile.rs`). Round-trips cleanly with
247    /// any source `to_keyword` emits.
248    pub fn from_keyword(name: &str) -> Option<Self> {
249        match name {
250            "u64" => Some(Self::U64),
251            "f64" => Some(Self::F64),
252            "u32" => Some(Self::U32),
253            "i32" => Some(Self::I32),
254            "i64" => Some(Self::I64),
255            "f32" => Some(Self::F32),
256            "u8" => Some(Self::U8),
257            "i8" => Some(Self::I8),
258            "u16" => Some(Self::U16),
259            "i16" => Some(Self::I16),
260            "f16" => Some(Self::F16),
261            "u128" => Some(Self::U128),
262            "i128" => Some(Self::I128),
263            "reg128" => Some(Self::Reg128),
264            "reg_i8x16" => Some(Self::RegI8x16),
265            "reg_i16x8" => Some(Self::RegI16x8),
266            "reg_i32x4" => Some(Self::RegI32x4),
267            "reg_i64x2" => Some(Self::RegI64x2),
268            "reg_f16x8" => Some(Self::RegF16x8),
269            "reg_f32x4" => Some(Self::RegF32x4),
270            "reg_f64x2" => Some(Self::RegF64x2),
271            "bool" => Some(Self::Bool),
272            "str" | "Str" | "String" => Some(Self::Str),
273            "bytes" => Some(Self::Bytes),
274            "json" | "Json" => Some(Self::Json),
275            "ext" | "Ext" => Some(Self::Ext),
276            "handle" => Some(Self::Handle),
277            "vec_f32" => Some(Self::VecF32),
278            "vec_i32" => Some(Self::VecI32),
279            "vec_f64" => Some(Self::VecF64),
280            "vec_i64" => Some(Self::VecI64),
281            "vec_f16" => Some(Self::VecF16),
282            "vec_i16" => Some(Self::VecI16),
283            "vec_i8" => Some(Self::VecI8),
284            _ => None,
285        }
286    }
287
288    /// Workload-author-facing parser for the `{name:<keyword>}`
289    /// lvalue-spec surface. Strict subset of [`Self::from_keyword`]
290    /// — `handle` and `ext` are rejected because they're
291    /// internal-only types a workload author should never assert.
292    ///
293    /// Returns `None` for any unrecognized name; the caller
294    /// surfaces the unknown spec as a workload-shape diagnostic.
295    pub fn from_workload_name(name: &str) -> Option<Self> {
296        match Self::from_keyword(name)? {
297            Self::Handle | Self::Ext => None,
298            pt => Some(pt),
299        }
300    }
301}