vyre-foundation 0.7.2

Foundation layer: IR, type system, memory model, wire format. Zero application semantics. Part of the vyre GPU compiler.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Canonical semantic operation registration and derived catalog views.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::LazyLock;

use crate::dialect_lookup::Signature;
use crate::ir::{BufferAccess, Program};
use crate::program_caps::{scan as scan_capabilities, RequiredCapabilities};

/// Deterministic fixture input cases. One case contains declaration-ordered buffers.
pub type OperationFixtures = fn() -> Vec<Vec<Vec<u8>>>;
/// One immutable semantic record used by validation, inlining, conformance,
/// documentation, and target-facet joins.
#[derive(Clone, Copy, Debug)]
pub struct SemanticOperation {
    /// Stable operation identifier.
    pub id: &'static str,
    /// Semantic schema version.
    pub semantic_version: u32,
    /// Explicit callable signature when the operation is used through `Expr::Call`.
    pub signature: Option<&'static Signature>,
    /// Semantic tier.
    pub tier: OperationTier,
    /// Derived dialect/category namespace.
    pub category: Option<&'static str>,
    /// Optional neutral program builder.
    pub build: Option<fn() -> Program>,
    /// Deterministic fixture inputs.
    pub test_inputs: Option<OperationFixtures>,
    /// Deterministic fixture outputs.
    pub expected_output: Option<OperationFixtures>,
    /// Algebraic or semantic law identifiers.
    pub laws: &'static [&'static str],
    /// Numerical comparison policy.
    pub tolerance: TolerancePolicy,
}

impl SemanticOperation {
    /// Build the canonical program and stamp its stable operation identity.
    #[must_use]
    pub fn program(self) -> Option<Program> {
        self.build.map(|build| build().with_entry_op_id(self.id))
    }

    /// Derive target-neutral capability requirements from the canonical program.
    #[must_use]
    pub fn required_capabilities(self) -> Option<RequiredCapabilities> {
        self.program().map(|program| scan_capabilities(&program))
    }

    /// Derive target-neutral effects from the canonical program.
    #[must_use]
    pub fn effects(self) -> Option<OperationEffects> {
        self.program()
            .map(|program| OperationEffects::from_program(&program))
    }

    /// Return the coarse category.
    #[must_use]
    pub const fn category(self) -> Option<&'static str> {
        self.category
    }

    /// Return the permitted f32 drift in ULPs.
    #[must_use]
    pub const fn tolerance(self) -> u32 {
        self.tolerance.f32_ulp
    }
}

/// Coarse semantic tier used by catalog and conformance consumers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OperationTier {
    /// Foundation IR or built-in operation.
    Foundation,
    /// Hardware-facing semantic intrinsic.
    Intrinsic,
    /// Reusable backend-neutral primitive.
    Primitive,
    /// Library composition over typed IR.
    Library,
    /// Runtime-owned semantic operation.
    Runtime,
    /// External extension operation.
    External,
    /// Identifier does not match an accepted semantic namespace.
    Unknown,
}

impl OperationTier {
    /// Stable operation-matrix spelling.
    #[must_use]
    pub const fn matrix_value(self) -> &'static str {
        match self {
            Self::Foundation => "foundation_ir",
            Self::Intrinsic => "intrinsic",
            Self::Primitive => "primitive",
            Self::Library => "libs",
            Self::Runtime => "runtime",
            Self::External => "external",
            Self::Unknown => "unknown",
        }
    }
}

/// Classify one operation identity by its canonical namespace.
#[must_use]
pub fn classify_operation_id(id: &str) -> OperationTier {
    if id.starts_with("vyre-intrinsics::hardware::") {
        OperationTier::Intrinsic
    } else if id.starts_with("vyre-primitives::") {
        OperationTier::Primitive
    } else if id.starts_with("vyre-libs::") {
        OperationTier::Library
    } else if id.starts_with("core.") || id.starts_with("io.") || id.starts_with("mem.") {
        OperationTier::Runtime
    } else if id
        .split_once("::")
        .is_some_and(|(crate_name, _)| !crate_name.is_empty() && !crate_name.starts_with("vyre-"))
    {
        OperationTier::External
    } else {
        OperationTier::Unknown
    }
}

/// Semantic memory and synchronization effects derived from an operation program.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct OperationEffects {
    /// The operation reads caller-visible storage.
    pub reads: bool,
    /// The operation writes caller-visible storage.
    pub writes: bool,
    /// The operation contains atomic memory effects.
    pub atomics: bool,
    /// The operation requires intra- or inter-workgroup synchronization.
    pub synchronizes: bool,
}

impl OperationEffects {
    /// Derive neutral effects from the canonical program declaration and statistics.
    #[must_use]
    pub fn from_program(program: &Program) -> Self {
        let mut effects = Self::default();
        for buffer in program.buffers() {
            match buffer.access() {
                BufferAccess::ReadOnly => effects.reads = true,
                BufferAccess::ReadWrite => {
                    effects.reads = true;
                    effects.writes = true;
                }
                BufferAccess::WriteOnly => effects.writes = true,
                _ => {
                    effects.reads = true;
                    effects.writes = true;
                }
            }
        }
        let stats = program.stats();
        effects.atomics = stats.atomic_op_count > 0;
        effects.synchronizes = stats.has_node_barrier() || stats.distributed_collectives();
        effects
    }
}

/// Numerical comparison policy owned by the semantic operation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TolerancePolicy {
    /// Maximum accepted f32 drift measured in ULPs.
    pub f32_ulp: u32,
}

impl TolerancePolicy {
    /// Exact byte identity.
    pub const EXACT: Self = Self { f32_ulp: 0 };

    /// Construct an f32 ULP tolerance.
    #[must_use]
    pub const fn f32_ulp(maximum: u32) -> Self {
        Self { f32_ulp: maximum }
    }
}

/// One semantic operation identity and all target-neutral catalog policy.
pub struct OperationRegistration {
    /// Stable operation identifier.
    pub id: &'static str,
    /// Semantic schema version.
    pub semantic_version: u32,
    /// Optional explicitly declared signature. When absent, [`Self::program`] is authoritative.
    pub signature: Option<Signature>,
    /// Semantic tier.
    pub tier: OperationTier,
    /// Coarse taxonomy category.
    pub category: Option<&'static str>,
    /// Optional neutral program builder.
    pub build: Option<fn() -> Program>,
    /// Deterministic fixture inputs.
    pub test_inputs: Option<OperationFixtures>,
    /// Optional deterministic fixture outputs or reference-oracle projection.
    pub expected_output: Option<OperationFixtures>,
    /// Algebraic or semantic law identifiers.
    pub laws: &'static [&'static str],
    /// Numerical comparison policy.
    pub tolerance: TolerancePolicy,
}

impl OperationRegistration {
    /// Construct a neutral operation registration with exact comparison policy.
    #[must_use]
    pub const fn new(
        id: &'static str,
        tier: OperationTier,
        build: Option<fn() -> Program>,
        test_inputs: Option<OperationFixtures>,
        expected_output: Option<OperationFixtures>,
    ) -> Self {
        Self {
            id,
            semantic_version: 1,
            signature: None,
            tier,
            category: None,
            build,
            test_inputs,
            expected_output,
            laws: &[],
            tolerance: TolerancePolicy::EXACT,
        }
    }

    /// Construct a library-composition registration.
    #[must_use]
    pub const fn library(
        id: &'static str,
        build: fn() -> Program,
        test_inputs: Option<OperationFixtures>,
        expected_output: Option<OperationFixtures>,
    ) -> Self {
        Self::new(
            id,
            OperationTier::Library,
            Some(build),
            test_inputs,
            expected_output,
        )
    }

    /// Construct a reusable primitive registration.
    #[must_use]
    pub const fn primitive(
        id: &'static str,
        build: fn() -> Program,
        test_inputs: Option<OperationFixtures>,
        expected_output: Option<OperationFixtures>,
    ) -> Self {
        Self::new(
            id,
            OperationTier::Primitive,
            Some(build),
            test_inputs,
            expected_output,
        )
    }

    /// Attach an explicit signature.
    #[must_use]
    pub const fn with_signature(mut self, signature: Signature) -> Self {
        self.signature = Some(signature);
        self
    }

    /// Attach a coarse category.
    #[must_use]
    pub const fn with_category(mut self, category: &'static str) -> Self {
        self.category = Some(category);
        self
    }

    /// Attach semantic law identifiers.
    #[must_use]
    pub const fn with_laws(mut self, laws: &'static [&'static str]) -> Self {
        self.laws = laws;
        self
    }

    /// Return the coarse category.
    #[must_use]
    pub const fn category(&self) -> Option<&'static str> {
        self.category
    }

    /// Return the permitted f32 drift in ULPs.
    #[must_use]
    pub const fn tolerance(&self) -> u32 {
        self.tolerance.f32_ulp
    }

    /// Attach the numerical tolerance policy.
    #[must_use]
    pub const fn with_tolerance(mut self, tolerance: TolerancePolicy) -> Self {
        self.tolerance = tolerance;
        self
    }

    /// Build the canonical program and stamp its stable operation identity.
    #[must_use]
    pub fn program(&self) -> Option<Program> {
        self.build.map(|build| build().with_entry_op_id(self.id))
    }

    /// Derive target-neutral capability requirements from the canonical program.
    #[must_use]
    pub fn required_capabilities(&self) -> Option<RequiredCapabilities> {
        self.program().map(|program| scan_capabilities(&program))
    }

    /// Derive target-neutral effects from the canonical program.
    #[must_use]
    pub fn effects(&self) -> Option<OperationEffects> {
        self.program()
            .map(|program| OperationEffects::from_program(&program))
    }
}
impl From<&'static OperationRegistration> for SemanticOperation {
    fn from(registration: &'static OperationRegistration) -> Self {
        Self {
            id: registration.id,
            semantic_version: registration.semantic_version,
            signature: registration.signature.as_ref(),
            tier: registration.tier,
            category: registration.category,
            build: registration.build,
            test_inputs: registration.test_inputs,
            expected_output: registration.expected_output,
            laws: registration.laws,
            tolerance: registration.tolerance,
        }
    }
}

inventory::collect!(OperationRegistration);

/// Catalog validation failure.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum OperationRegistryError {
    /// Two linked registrations claimed one stable identity.
    #[error("duplicate operation registration `{id}`; keep exactly one semantic owner")]
    DuplicateId {
        /// Duplicated stable operation id.
        id: &'static str,
    },
    /// A registration used the reserved zero semantic version.
    #[error("operation `{id}` uses semantic version zero; use a positive schema version")]
    InvalidVersion {
        /// Invalid operation id.
        id: &'static str,
    },
    /// A registration supplied neither a neutral program nor an explicit signature.
    #[error("operation `{id}` supplies neither a neutral program nor an explicit signature")]
    MissingSemantics {
        /// Incomplete operation id.
        id: &'static str,
    },
    /// Registration tier does not match its canonical namespace.
    #[error(
        "operation `{id}` declares tier {declared:?}, but its canonical namespace classifies as {classified:?}"
    )]
    InvalidTier {
        /// Invalid operation id.
        id: &'static str,
        /// Tier supplied by the registration.
        declared: OperationTier,
        /// Tier derived from the canonical namespace.
        classified: OperationTier,
    },
}

/// Immutable validated view over every linked semantic operation registration.
pub struct OperationRegistry {
    ordered: Vec<&'static OperationRegistration>,
    by_id: BTreeMap<&'static str, &'static OperationRegistration>,
}

impl OperationRegistry {
    fn build() -> Result<Self, OperationRegistryError> {
        let mut ordered = inventory::iter::<OperationRegistration>
            .into_iter()
            .collect::<Vec<_>>();
        ordered.sort_unstable_by_key(|entry| entry.id);
        let mut by_id = BTreeMap::new();
        for entry in &ordered {
            if entry.semantic_version == 0 {
                return Err(OperationRegistryError::InvalidVersion { id: entry.id });
            }
            if entry.build.is_none() && entry.signature.is_none() {
                return Err(OperationRegistryError::MissingSemantics { id: entry.id });
            }
            let classified = classify_operation_id(entry.id);
            if classified == OperationTier::Unknown || classified != entry.tier {
                return Err(OperationRegistryError::InvalidTier {
                    id: entry.id,
                    declared: entry.tier,
                    classified,
                });
            }
            if by_id.insert(entry.id, *entry).is_some() {
                return Err(OperationRegistryError::DuplicateId { id: entry.id });
            }
        }
        Ok(Self { ordered, by_id })
    }

    /// Return the process-wide validated semantic operation registry.
    #[must_use]
    pub fn global() -> &'static Self {
        static REGISTRY: LazyLock<OperationRegistry> = LazyLock::new(|| {
            OperationRegistry::build()
                .unwrap_or_else(|error| panic!("invalid semantic operation registry: {error}"))
        });
        &REGISTRY
    }

    /// Resolve one stable operation identity.
    #[must_use]
    pub fn get(&self, id: &str) -> Option<SemanticOperation> {
        self.by_id.get(id).copied().map(SemanticOperation::from)
    }

    /// Iterate registrations in stable operation-id order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = SemanticOperation> + '_ {
        self.ordered.iter().copied().map(SemanticOperation::from)
    }
}

/// Validated target identity carried by target-owned facet registrations.
///
/// Linked target owners construct borrowed identities at declaration time.
/// Deserialized manifests retain owned identities without leaking storage.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TargetId(Cow<'static, str>);

impl TargetId {
    /// Construct a borrowed target identity from an owner-defined stable spelling.
    ///
    /// # Errors
    ///
    /// Empty or whitespace-padded identities are rejected.
    pub const fn new(id: &'static str) -> Result<Self, &'static str> {
        if id.is_empty() || has_surrounding_ascii_whitespace(id.as_bytes()) {
            return Err("target identity must be non-empty and contain no surrounding whitespace");
        }
        Ok(Self(Cow::Borrowed(id)))
    }

    /// Construct an owned target identity from persisted or caller-supplied data.
    ///
    /// # Errors
    ///
    /// Empty or whitespace-padded identities are rejected.
    pub fn from_owned(id: String) -> Result<Self, &'static str> {
        if id.is_empty() || has_surrounding_ascii_whitespace(id.as_bytes()) {
            return Err("target identity must be non-empty and contain no surrounding whitespace");
        }
        Ok(Self(Cow::Owned(id)))
    }

    /// Return the stable owner-defined spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }

    /// Construct a validated borrowed target identity for a compile-time constant.
    ///
    /// # Panics
    ///
    /// Panics when the identity is empty or has surrounding whitespace.
    #[must_use]
    pub const fn expect_valid(id: &'static str) -> Self {
        if id.is_empty() || has_surrounding_ascii_whitespace(id.as_bytes()) {
            panic!("target identity must be non-empty and contain no surrounding whitespace");
        }
        Self(Cow::Borrowed(id))
    }
}

impl serde::Serialize for TargetId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> serde::Deserialize<'de> for TargetId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let id = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::from_owned(id).map_err(serde::de::Error::custom)
    }
}

impl std::fmt::Display for TargetId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl PartialEq<&str> for TargetId {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

const fn has_surrounding_ascii_whitespace(bytes: &[u8]) -> bool {
    matches!(bytes.first(), Some(byte) if byte.is_ascii_whitespace())
        || matches!(bytes.last(), Some(byte) if byte.is_ascii_whitespace())
}

/// Derived target-specific capability keyed by canonical semantic operation id.
///
/// Concrete drivers submit one backend registration containing their validated
/// target identity, compiler, materializer, and supported-operation set. The
/// shared driver joins that record with [`OperationRegistry`] to produce this
/// read-only view without a second operation submission.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TargetOperationFacet {
    /// Canonical semantic operation id.
    pub operation_id: &'static str,
    /// Validated target identity from the concrete driver's registration.
    pub target_id: TargetId,
    /// Target facet schema version.
    pub version: u32,
}