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 /// The forms of a dataset facet's records, fixed when a program is
151 /// built: the inventory a [`PortType::Fragment`] wire's values
152 /// index. For a predicate facet, every distinct predicate form with
153 /// its template and count, and the layout its conditions bind
154 /// against; for a record facet, the layout, which is its one form.
155 /// A constant.
156 Forms,
157 /// One record of a dataset facet as structure, for a host to bind
158 /// without parsing text: the [`PortType::Forms`] it belongs to, the
159 /// index of its form there, and the record's ordinal. What a host
160 /// prepares once per form and binds per cycle.
161 Fragment,
162 /// The base positions a query's predicate admits, as a set that
163 /// answers membership and is not read until it is asked.
164 AdmittedRows,
165 /// Any value, as written: the slot of an input whose type may vary
166 /// over a kernel's lifetime (input_variance.md). Only a converter
167 /// node reads it, turning the value into the type its consumers
168 /// read; no other port has this type, and no value is typed `Dyn`.
169 Dyn,
170}
171
172/// A port type displays as its keyword ([`PortType::to_keyword`]), so
173/// source synthesized through `Display`, such as `extern x: {ty}`,
174/// parses back to the same type.
175impl fmt::Display for PortType {
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 f.write_str(self.to_keyword())
178 }
179}
180
181/// The set of numbers a scalar port type can carry, described by the
182/// properties that decide whether one of them holds every value of
183/// another: how many bits the representation has, and how it spends
184/// them.
185///
186/// `Bool` is the one-bit unsigned domain, which is what the type
187/// system already says of it — it widens to `U64` as 1 and 0.
188/// Non-scalar types (`Str`, `Bytes`, `Json`, the vectors, the
189/// register views, `Ext`, `Handle`) have no domain.
190#[derive(Clone, Copy, PartialEq, Eq, Debug)]
191pub enum NumericDomain {
192 /// Non-negative integers in `0 ..= 2^bits - 1`.
193 Unsigned {
194 /// Width of the representation.
195 bits: u32,
196 },
197 /// Two's-complement integers, one of whose bits is the sign.
198 Signed {
199 /// Width of the representation, sign bit included.
200 bits: u32,
201 },
202 /// An IEEE 754 binary float.
203 Float {
204 /// Significand bits, the implicit leading one included: the
205 /// largest integer represented exactly is `2^mantissa`.
206 mantissa: u32,
207 /// Exponent bits, which fix the magnitude range.
208 exponent: u32,
209 },
210}
211
212impl NumericDomain {
213 /// Whether every value of this domain is a value of `other` —
214 /// that is, whether a conversion into `other` is lossless.
215 ///
216 /// Integers fit by counting the bits each spends on magnitude: an
217 /// unsigned domain needs a signed one strictly wider, a signed
218 /// domain never fits an unsigned one. An integer fits a float
219 /// when its magnitude bits fit the float's significand, which is
220 /// why `U64 → F64` does not: 64 magnitude bits do not fit 53, and
221 /// the values above `2^53` round. A float fits a wider float when
222 /// both its significand and its exponent do.
223 pub fn fits_in(self, other: Self) -> bool {
224 use NumericDomain::{Float, Signed, Unsigned};
225 match (self, other) {
226 (Unsigned { bits: a }, Unsigned { bits: b }) => a <= b,
227 (Unsigned { bits: a }, Signed { bits: b }) => a < b,
228 (Signed { bits: a }, Signed { bits: b }) => a <= b,
229 (Signed { .. }, Unsigned { .. }) => false,
230 (Unsigned { bits }, Float { mantissa, .. }) => bits <= mantissa,
231 (Signed { bits }, Float { mantissa, .. }) => bits - 1 <= mantissa,
232 (Float { .. }, Unsigned { .. } | Signed { .. }) => false,
233 (
234 Float {
235 mantissa: m1,
236 exponent: e1,
237 },
238 Float {
239 mantissa: m2,
240 exponent: e2,
241 },
242 ) => m1 <= m2 && e1 <= e2,
243 }
244 }
245}
246
247impl PortType {
248 /// Every port type, once.
249 ///
250 /// A test that must hold for *all* types can walk this rather than
251 /// name the ones its author thought of, so a mapping such as the
252 /// value↔slot writers is checked complete rather than complete for
253 /// the types some program happened to use.
254 ///
255 /// [`Self::every_variant_is_listed`] keeps this honest — it is an
256 /// exhaustive `match`, so adding a variant without adding it here
257 /// fails to compile rather than quietly shrinking every sweep that
258 /// walks this list.
259 pub const ALL: &'static [PortType] = &[
260 PortType::U64,
261 PortType::F64,
262 PortType::U32,
263 PortType::I32,
264 PortType::I64,
265 PortType::F32,
266 PortType::U8,
267 PortType::I8,
268 PortType::U16,
269 PortType::I16,
270 PortType::F16,
271 PortType::U128,
272 PortType::I128,
273 PortType::Reg128,
274 PortType::RegI8x16,
275 PortType::RegI16x8,
276 PortType::RegI32x4,
277 PortType::RegI64x2,
278 PortType::RegF16x8,
279 PortType::RegF32x4,
280 PortType::RegF64x2,
281 PortType::Bool,
282 PortType::Str,
283 PortType::Bytes,
284 PortType::Json,
285 PortType::Ext,
286 PortType::Handle,
287 PortType::VecF32,
288 PortType::VecI32,
289 PortType::VecF64,
290 PortType::VecI64,
291 PortType::VecF16,
292 PortType::VecI16,
293 PortType::VecI8,
294 PortType::Forms,
295 PortType::Fragment,
296 PortType::AdmittedRows,
297 PortType::Dyn,
298 ];
299
300 /// `true` for every variant, by an exhaustive match: the compiler
301 /// refuses this function when a variant is added, and the test
302 /// beside it checks [`Self::ALL`] carries the one that was added.
303 #[doc(hidden)]
304 pub fn every_variant_is_listed(self) -> bool {
305 match self {
306 PortType::U64
307 | PortType::F64
308 | PortType::U32
309 | PortType::I32
310 | PortType::I64
311 | PortType::F32
312 | PortType::U8
313 | PortType::I8
314 | PortType::U16
315 | PortType::I16
316 | PortType::F16
317 | PortType::U128
318 | PortType::I128
319 | PortType::Reg128
320 | PortType::RegI8x16
321 | PortType::RegI16x8
322 | PortType::RegI32x4
323 | PortType::RegI64x2
324 | PortType::RegF16x8
325 | PortType::RegF32x4
326 | PortType::RegF64x2
327 | PortType::Bool
328 | PortType::Str
329 | PortType::Bytes
330 | PortType::Json
331 | PortType::Ext
332 | PortType::Handle
333 | PortType::VecF32
334 | PortType::VecI32
335 | PortType::VecF64
336 | PortType::VecI64
337 | PortType::VecF16
338 | PortType::VecI16
339 | PortType::VecI8
340 | PortType::Forms
341 | PortType::Fragment
342 | PortType::AdmittedRows
343 | PortType::Dyn => Self::ALL.contains(&self),
344 }
345 }
346
347 /// The numbers this type can carry, for the types that carry
348 /// numbers. `None` for every other type.
349 ///
350 /// This is what decides whether a conversion between two types
351 /// keeps the value, so that the answer is read off the types
352 /// themselves rather than kept in a list of pairs beside them.
353 pub fn numeric_domain(self) -> Option<NumericDomain> {
354 use NumericDomain::{Float, Signed, Unsigned};
355 Some(match self {
356 Self::Bool => Unsigned { bits: 1 },
357 Self::U8 => Unsigned { bits: 8 },
358 Self::U16 => Unsigned { bits: 16 },
359 Self::U32 => Unsigned { bits: 32 },
360 Self::U64 => Unsigned { bits: 64 },
361 Self::U128 => Unsigned { bits: 128 },
362 Self::I8 => Signed { bits: 8 },
363 Self::I16 => Signed { bits: 16 },
364 Self::I32 => Signed { bits: 32 },
365 Self::I64 => Signed { bits: 64 },
366 Self::I128 => Signed { bits: 128 },
367 Self::F16 => Float {
368 mantissa: 11,
369 exponent: 5,
370 },
371 Self::F32 => Float {
372 mantissa: 24,
373 exponent: 8,
374 },
375 Self::F64 => Float {
376 mantissa: 53,
377 exponent: 11,
378 },
379 Self::Str
380 | Self::Bytes
381 | Self::Json
382 | Self::Ext
383 | Self::Handle
384 | Self::Reg128
385 | Self::RegI8x16
386 | Self::RegI16x8
387 | Self::RegI32x4
388 | Self::RegI64x2
389 | Self::RegF16x8
390 | Self::RegF32x4
391 | Self::RegF64x2
392 | Self::VecF32
393 | Self::VecI32
394 | Self::VecF64
395 | Self::VecI64
396 | Self::VecF16
397 | Self::VecI16
398 | Self::VecI8
399 | Self::Forms
400 | Self::Fragment
401 | Self::AdmittedRows
402 | Self::Dyn => return None,
403 })
404 }
405
406 /// The canonical lowercase keyword for this `PortType`.
407 ///
408 /// This is the single source of truth for the str↔PortType
409 /// mapping used by every synthesizer and parser in the
410 /// workspace — synthesized polydat source (`extern <name>:
411 /// <keyword>`), the workload-author `{name:<keyword>}` lvalue
412 /// spec, and reverse parsing via [`Self::from_keyword`].
413 /// Inverse of [`Self::from_keyword`].
414 ///
415 /// Exhaustive over the enum — adding a new `PortType` variant
416 /// is a compile error here, forcing the addition of its
417 /// canonical keyword and the round-trip closure to update.
418 pub fn to_keyword(&self) -> &'static str {
419 match self {
420 Self::U64 => "u64",
421 Self::F64 => "f64",
422 Self::U32 => "u32",
423 Self::I32 => "i32",
424 Self::I64 => "i64",
425 Self::F32 => "f32",
426 Self::U8 => "u8",
427 Self::I8 => "i8",
428 Self::U16 => "u16",
429 Self::I16 => "i16",
430 Self::F16 => "f16",
431 Self::U128 => "u128",
432 Self::I128 => "i128",
433 Self::Reg128 => "reg128",
434 Self::RegI8x16 => "reg_i8x16",
435 Self::RegI16x8 => "reg_i16x8",
436 Self::RegI32x4 => "reg_i32x4",
437 Self::RegI64x2 => "reg_i64x2",
438 Self::RegF16x8 => "reg_f16x8",
439 Self::RegF32x4 => "reg_f32x4",
440 Self::RegF64x2 => "reg_f64x2",
441 Self::Bool => "bool",
442 Self::Str => "str",
443 Self::Bytes => "bytes",
444 Self::Json => "json",
445 Self::Ext => "ext",
446 Self::Handle => "handle",
447 Self::VecF32 => "vec_f32",
448 Self::VecI32 => "vec_i32",
449 Self::VecF64 => "vec_f64",
450 Self::VecI64 => "vec_i64",
451 Self::VecF16 => "vec_f16",
452 Self::VecI16 => "vec_i16",
453 Self::VecI8 => "vec_i8",
454 Self::Forms => "forms",
455 Self::Fragment => "fragment",
456 Self::AdmittedRows => "admitted_rows",
457 Self::Dyn => "dyn",
458 }
459 }
460
461 /// Parse a polydat type keyword into a `PortType`.
462 ///
463 /// Inverse of [`Self::to_keyword`]: accepts exactly the keywords
464 /// `to_keyword` emits, one per type. Returns `None` for any other
465 /// name so callers can surface a loud diagnostic rather than
466 /// silently coercing to a default; for a spelling polydat retired,
467 /// such as `String`, [`Self::retired_keyword`] names the keyword
468 /// that replaced it.
469 ///
470 /// Used by the DSL `extern <name>: <keyword>` parser
471 /// (`polydat-core/src/dsl/compile.rs`). Round-trips cleanly with
472 /// any source `to_keyword` emits.
473 pub fn from_keyword(name: &str) -> Option<Self> {
474 match name {
475 "u64" => Some(Self::U64),
476 "f64" => Some(Self::F64),
477 "u32" => Some(Self::U32),
478 "i32" => Some(Self::I32),
479 "i64" => Some(Self::I64),
480 "f32" => Some(Self::F32),
481 "u8" => Some(Self::U8),
482 "i8" => Some(Self::I8),
483 "u16" => Some(Self::U16),
484 "i16" => Some(Self::I16),
485 "f16" => Some(Self::F16),
486 "u128" => Some(Self::U128),
487 "i128" => Some(Self::I128),
488 "reg128" => Some(Self::Reg128),
489 "reg_i8x16" => Some(Self::RegI8x16),
490 "reg_i16x8" => Some(Self::RegI16x8),
491 "reg_i32x4" => Some(Self::RegI32x4),
492 "reg_i64x2" => Some(Self::RegI64x2),
493 "reg_f16x8" => Some(Self::RegF16x8),
494 "reg_f32x4" => Some(Self::RegF32x4),
495 "reg_f64x2" => Some(Self::RegF64x2),
496 "bool" => Some(Self::Bool),
497 "str" => Some(Self::Str),
498 "bytes" => Some(Self::Bytes),
499 "json" => Some(Self::Json),
500 "ext" => Some(Self::Ext),
501 "handle" => Some(Self::Handle),
502 "vec_f32" => Some(Self::VecF32),
503 "vec_i32" => Some(Self::VecI32),
504 "vec_f64" => Some(Self::VecF64),
505 "vec_i64" => Some(Self::VecI64),
506 "vec_f16" => Some(Self::VecF16),
507 "vec_i16" => Some(Self::VecI16),
508 "vec_i8" => Some(Self::VecI8),
509 "forms" => Some(Self::Forms),
510 "fragment" => Some(Self::Fragment),
511 "admitted_rows" => Some(Self::AdmittedRows),
512 "dyn" => Some(Self::Dyn),
513 _ => None,
514 }
515 }
516
517 /// The keyword that replaced `name`, when `name` is a type
518 /// spelling polydat accepted before 0.10.0 and no longer does:
519 /// `String` and `Str` (now `str`), `Json` (now `json`) and `Ext`
520 /// (now `ext`). `None` for any other name, keywords included.
521 ///
522 /// The parser uses it to refuse a retired spelling with the
523 /// keyword to write instead; a host that parses type names
524 /// itself, through [`Self::from_keyword`], can do the same.
525 ///
526 /// ```
527 /// use polydat_grammar::PortType;
528 ///
529 /// assert_eq!(PortType::retired_keyword("String"), Some("str"));
530 /// assert_eq!(PortType::retired_keyword("str"), None);
531 /// assert_eq!(PortType::from_keyword("String"), None);
532 /// ```
533 pub fn retired_keyword(name: &str) -> Option<&'static str> {
534 match name {
535 "String" | "Str" => Some("str"),
536 "Json" => Some("json"),
537 "Ext" => Some("ext"),
538 _ => None,
539 }
540 }
541
542 /// The diagnostic for a retired type spelling: "`String` is no
543 /// longer a type keyword; write `str`", or `None` when `name` is
544 /// not one ([`Self::retired_keyword`]).
545 pub fn retired_keyword_message(name: &str) -> Option<String> {
546 Self::retired_keyword(name)
547 .map(|keyword| format!("`{name}` is no longer a type keyword; write `{keyword}`"))
548 }
549
550 /// Workload-author-facing parser for the `{name:<keyword>}`
551 /// lvalue-spec surface. Strict subset of [`Self::from_keyword`]
552 /// — `handle`, `ext` and the dataset types `forms`, `fragment`
553 /// and `admitted_rows` are rejected because they're internal-only
554 /// types a workload author should never assert.
555 ///
556 /// Returns `None` for any unrecognized name; the caller
557 /// surfaces the unknown spec as a workload-shape diagnostic.
558 pub fn from_workload_name(name: &str) -> Option<Self> {
559 match Self::from_keyword(name)? {
560 Self::Handle | Self::Ext | Self::Forms | Self::Fragment | Self::AdmittedRows => None,
561 pt => Some(pt),
562 }
563 }
564}