Skip to main content

vyre_libs/
lib.rs

1//! # vyre-libs  -  Category A composition ecosystem
2//!
3//! `vyre-libs` is the library layer that sits ON TOP of `vyre-ops`.
4//!
5//! Almost every function is a **pure Category A composition**: it returns a
6//! [`vyre::Program`] built entirely from existing vyre IR primitives. The
7//! sole exception is the `math::atomic` family, which are **Category B**
8//! (`Category::Intrinsic`) because they require the backend to own the
9//! `Expr::Atomic` target builder emitter arm (F-IR-35).
10//!
11//! This is the ML/DSP/cryptographic ecosystem layer. Examples:
12//!
13//! ```ignore
14//! use vyre_libs::nn::linear;
15//! let program = linear(/* input_buf */ "x", /* weights */ "w", /* bias */ "b");
16//! // `program` is a standard vyre::Program you dispatch against any backend.
17//! ```
18//!
19//! ## Why a single `vyre-libs` crate, not five?
20//!
21//! The initial proposal suggested `vyre-nn`, `vyre-math`, `vyre-match`,
22//! `vyre-crypto`, `vyre-graph-stitch` as five standalone crates. That
23//! is the right endpoint  -  each becomes its own crates.io identity
24//! with its own community  -  but the migration cost at 0.6 is wrong.
25//! This crate starts as one, with public modules for each domain; when
26//! a module has its own consumer base + maturity, it promotes to a
27//! dedicated crate without breaking downstream code (the
28//! `vyre-libs::nn` path moves to `vyre-nn::` via a re-export shim).
29//!
30//! `vyre-graph-stitch` was deliberately omitted  -  "logical linker for
31//! emitted graphs" is a `vyre-foundation` concern (IR composition),
32//! not a library crate.
33//!
34//! ## Region wrapping
35//!
36//! Every public composition wraps its body in a
37//! [`vyre::ir::Node::Region`] with a stable generator name. The
38//! optimizer treats Regions as atomic by default (preserves
39//! debuggability + source-mapping); explicit inline passes can unroll
40//! them. This is LLVM's function-vs-always-inline split at IR level.
41//!
42//! ## Feature flags
43//!
44//! Each domain lives behind a feature flag so minimal consumers pay
45//! for only what they use:
46//!
47//! - `math` (default)  -  linear algebra, scans, broadcasts
48//! - `nn` (default, implies `math`)  -  neural-net primitives
49//! - `matching` (default)  -  regex, DFA, substring, multi-pattern
50//! - `crypto` (default)  -  hashing, MAC, checksums
51//!
52//! Turn defaults off with `default-features = false` and cherry-pick
53//! what you need.
54
55// P1.11 (closed): `OpEntry` is now POD over `&'static str` + `fn(...)`,
56// so stdlib auto-traits give us `Send + Sync` for free. No `unsafe`
57// anywhere in vyre-libs  -  `forbid` catches any future regression.
58#![forbid(unsafe_code)]
59#![deny(missing_docs)]
60#![allow(
61    clippy::too_many_arguments,
62    clippy::needless_range_loop,
63    clippy::double_must_use,
64    clippy::items_after_test_module,
65    clippy::assertions_on_constants,
66    clippy::overly_complex_bool_expr,
67    clippy::filter_map_bool_then
68)]
69// P3.3 nested-dialect reshape: each sub-dialect's single op file
70// shares the sub-dialect's module name (e.g. `math/broadcast/broadcast.rs`).
71// That's the intended shape for community packs that add second/
72// third ops to the same sub-dialect later; the lint would fight
73// the architectural decision.
74#![allow(clippy::module_inception)]
75
76/// Build a trap-only program for registry fixtures or infallible composition wrappers.
77#[allow(dead_code)]
78pub(crate) fn invalid_program(
79    op_id: &'static str,
80    message: impl Into<String>,
81) -> vyre::ir::Program {
82    let message = message.into();
83    vyre::ir::Program::wrapped(
84        Vec::new(),
85        [1, 1, 1],
86        vec![region::wrap_anonymous(
87            op_id,
88            vec![vyre::ir::Node::trap(vyre::ir::Expr::u32(0), message)],
89        )],
90    )
91}
92
93/// Region builder  -  the shared helper every composition routes through.
94pub mod region;
95
96/// Domain-neutral byte-range ordering predicates. Previously lived inside
97/// `vyre-libs::security::topology`; hoisted out so non-security callers
98/// (a downstream analyzer's `Before`/`After` predicates, future dialects) do not pull the
99/// security dialect through the import graph. See CRITIQUE_VISION_ALIGNMENT_2026-04-23 V5.
100pub mod range_ordering;
101
102/// `TensorRef`  -  typed buffer-argument wrapper used by every Cat-A
103/// composition for dtype + shape + name-uniqueness validation.
104pub mod tensor_ref;
105
106pub use tensor_ref::{check_dtype, check_shape, check_unique_names, TensorRef, TensorRefError};
107
108/// Shared builder helpers every Cat-A composition reuses.
109pub mod builder;
110mod substrate_catalog;
111
112pub use builder::{check_tensors, BuildOptions};
113
114pub mod buffer_names;
115
116/// `ProgramDescriptor`  -  introspection surface for Cat-A Programs.
117pub mod descriptor;
118
119pub use descriptor::{BufferDescriptor, ProgramDescriptor};
120
121/// Compatibility alias metadata for public shim paths.
122pub mod compat_aliases;
123
124#[cfg(feature = "math-linalg")]
125pub use math::{matmul_bias_tiled, matmul_tiled, MatmulBias, MatmulBiasTiled, MatmulTiled};
126
127/// Universal op harness  -  auto-testing infrastructure for every composition.
128///
129/// Each composition registers an `OpEntry` via
130/// `inventory::submit!`. The harness discovers all entries at test
131/// time and runs validation, wire round-trip, CSE stability, and
132/// reference interpreter tests automatically.
133///
134/// Hidden from docs.rs  -  external consumers of vyre-libs don't need
135/// this module's surface; it exists for internal test infrastructure
136/// only. Kept `pub` so `inventory::submit!` can reference `OpEntry`
137/// from per-op source files at crate-root scope.
138#[doc(hidden)]
139pub mod harness;
140
141/// Math dialect  -  linear algebra, scans, broadcasting.
142#[cfg(any(
143    feature = "math-linalg",
144    feature = "math-scan",
145    feature = "math-broadcast"
146))]
147pub mod math;
148
149/// Logical dialect  -  element-wise boolean composition.
150#[cfg(feature = "logical")]
151pub mod logical;
152
153/// Neural-network dialect  -  activation, normalization, attention, linear.
154#[cfg(any(
155    feature = "nn-activation",
156    feature = "nn-linear",
157    feature = "nn-norm",
158    feature = "nn-attention"
159))]
160pub mod nn;
161
162/// Pattern-scanning dialect  -  substring, DFA, Aho-Corasick, rule
163/// dispatch, secfinding generation. Renamed from `matching` per
164/// ROADMAP T032 (SEPARATION_AUDIT S7)  -  "scan" reflects the actual
165/// semantic surface (not just substring matching). The original
166/// `matching` name is kept as a deprecated alias for backwards
167/// compatibility.
168#[cfg(any(
169    feature = "matching-substring",
170    feature = "matching-dfa",
171    feature = "matching-nfa"
172))]
173pub mod scan;
174
175/// Backwards-compat alias for [`scan`]. New code should use
176/// `vyre_libs::scan::*`. Alias metadata lives in
177/// [`compat_aliases::MATCHING_ALIAS`] so internal audits and public docs
178/// agree on the canonical owner.
179#[cfg(any(
180    feature = "matching-substring",
181    feature = "matching-dfa",
182    feature = "matching-nfa"
183))]
184#[deprecated(
185    since = "0.4.1",
186    note = "use `vyre_libs::scan` instead  -  the `matching` name is kept as a transition alias only"
187)]
188pub mod matching;
189
190/// Decode / decompression compositions  -  base64, hex, DEFLATE (stored),
191/// more coming. Pairs with `vyre-libs::matching::dfa` in the fused
192/// decode→scan pipeline (Innovation I.1).
193#[cfg(feature = "decode")]
194pub mod decode;
195
196/// Hash / checksum dialect  -  FNV-1a-32, FNV-1a-64, CRC-32, Adler-32,
197/// BLAKE3 compression. Consolidated from the former `vyre-libs::crypto`
198/// module per Migration 3. Every op lives here as a pure Cat-A
199/// composition over existing IR primitives (no dedicated target builder emitter
200/// arm required, per the intrinsic-vs-library rule).
201#[cfg(feature = "hash")]
202pub mod hash;
203
204/// Text-processing compositions for the GPU C parser pipeline
205/// (Phase L1+): byte classification, UTF-8 validation, line index.
206pub mod text;
207
208/// Representation sub-dialect: bit-packing and unpacking.
209pub mod representation;
210
211/// GPU parser infrastructure (Phase L3+): bracket matching, DFA
212/// lexer driver, LR(1) table walker. Grammar tables are generated
213/// host-side by `downstream analyzer-grammar-gen` and loaded as ReadOnly buffers.
214pub mod parsing;
215
216/// Front-end-agnostic borrow-check engine: the neutral `BorrowFacts` IR and the
217/// dataflow analysis over it. Producers (the Rust front-end now, a rustc adapter
218/// later) lower to `BorrowFacts`; the engine never depends on any front-end,
219/// which is what lets the borrow checker eventually run standalone.
220pub mod borrowck;
221
222/// Packed AST walks (`ast_walk_*` catalog ops).
223pub mod graph;
224
225/// GPU-native compiler middle-end (CFG and ELF emission helpers) for the C pipeline.
226#[cfg(feature = "c-parser")]
227pub mod compiler;
228
229#[cfg(feature = "c-parser")]
230pub use compiler::{
231    cfg::c11_build_cfg_and_gotos, object_writer::opt_lower_elf,
232    regalloc::opt_x86_64_register_allocation, stack_layout::opt_stack_layout_generation,
233    types_layout::c11_compute_alignments,
234};
235
236/// Security / taint compositions for static program analysis.
237/// Every op registers via `inventory::submit!` and lives under a
238/// stable op id. The implementations compose graph and dataflow
239/// primitives so downstream analyzers lower to one production GPU-facing
240/// surface.
241#[cfg(feature = "security")]
242pub mod security;
243
244/// GPU-accelerated visual effects  -  blur, shadow, filter chain,
245/// gradient, compositing, and glass material. Tier 3 compositions
246/// over `math::conv1d` (Tier 2.5) and bare IR expressions. The
247/// Molten web engine's visual effect substrate.
248#[cfg(feature = "visual")]
249pub mod visual;
250
251/// Compatibility facade for GPU dataflow compositions.
252/// This path remains for older `vyre-libs::dataflow::*` consumers and must
253/// not grow a parallel dataflow implementation tree.
254pub mod dataflow;
255
256mod primitive_catalog;
257
258pub use dataflow::{Soundness, SoundnessTagged};
259
260// vyre-libs::hardware removed (audit 2026-04-21 BLOCKER-1/6).
261// Canonical Cat-C intrinsics live exclusively in the `vyre-intrinsics`
262// crate; library compositions of atomic / clamp / lzcnt / tzcnt ops
263// live in `vyre-libs::math::*` (which uses `Expr::Atomic`, `Expr::min`,
264// `Expr::max`, `Expr::popcount` directly per library-tiers.md).
265//
266// vyre-libs::crypto removed (audit 2026-04-21 BLOCKER-3). Deprecated
267// shim deleted in favor of the canonical path at `vyre-libs::hash`.
268//
269// vyre-libs::composite removed (audit 2026-04-21 BLOCKER-3). The three
270// hash ops that lived there (adler32, crc32, fnv1a64) are canonical at
271// `vyre-libs::hash::*`.
272
273/// Rule-engine dialect  -  typed conditions, formulas, and program builder used
274/// by detection rule compilers.
275#[cfg(feature = "rule")]
276pub mod rule;
277
278/// Vector-widened string interning. CHD perfect hash
279/// over Tier-B label families  -  60k+ function-name strings reduce
280/// to one subgroup-shuffle + one DRAM load on the GPU.
281#[cfg(feature = "intern")]
282pub mod intern;
283
284/// Operation contract presets used by catalog entries.
285pub mod contracts;
286/// Type-signature constants shared across op definitions.
287pub mod signatures;
288/// Re-exports every type-signature constant at the crate root for convenient access.
289pub use signatures::{
290    BOOL_OUTPUTS, BYTES_TO_BYTES_INPUTS, BYTES_TO_BYTES_OUTPUTS, BYTES_TO_U32_OUTPUTS,
291    F32_F32_F32_INPUTS, F32_F32_INPUTS, F32_INPUTS, F32_OUTPUTS, I32_OUTPUTS, U32_INPUTS,
292    U32_OUTPUTS, U32_U32_INPUTS,
293};
294/// Pre-sweep shader snapshot migration entries, collected via inventory.
295/// `pub(crate)` because the registry is an internal pre-sweep tool  -
296/// downstream dialects do not submit through this path.
297pub(crate) mod test_migration;
298/// Test support components for vyre-libs.
299pub mod test_support;
300
301/// Driver-tier observability re-export so vyre-libs consumers can
302/// snapshot substrate counters + decision histograms without taking a
303/// direct vyre-driver dependency.
304pub mod observability {
305    pub use vyre_driver::observability::{BackendObservabilityProvider, DriverObservability};
306}
307
308/// Re-export the small set of vyre types every composition function
309/// returns. Consumers can `use vyre_libs::prelude::*` and get the API
310/// plus the types it returns.
311pub mod prelude {
312    pub use vyre::ir::{BufferAccess, BufferDecl, DataType, Expr, Node, Program};
313    pub use vyre::{BackendError, DispatchConfig};
314    pub use vyre_foundation::ir::model::expr::GeneratorRef;
315
316    // P2.1 / P2.2: the typed-tensor API + shared builder primitives.
317    // Every Cat-A op ships with a TensorRef-accepting builder; the
318    // prelude exposes the full construction surface so `use
319    // vyre_libs::prelude::*;` is enough to author a new Cat-A op.
320    pub use crate::builder::{check_tensors, BuildOptions};
321    pub use crate::tensor_ref::{
322        check_dtype, check_shape, check_unique_names, TensorRef, TensorRefError,
323    };
324
325    // Region wrapper  -  every composition emits its body through this.
326    pub use crate::region::{wrap, wrap_anonymous, wrap_child};
327
328    // Built-in Cat-A builders (gated on the relevant feature flags so
329    // minimum-footprint consumers don't pay for the ones they skip).
330    #[cfg(feature = "decode")]
331    pub use crate::decode::{base64_decode, hex_decode, inflate, ziftsieve_gpu};
332    #[cfg(feature = "crypto-blake3")]
333    pub use crate::hash::blake3_compress;
334    #[cfg(feature = "crypto-fnv")]
335    pub use crate::hash::fnv1a32;
336    #[cfg(feature = "logical")]
337    pub use crate::logical::{and, nand, nor, or, xor};
338    #[cfg(feature = "math-broadcast")]
339    pub use crate::math::broadcast;
340    #[cfg(feature = "math-scan")]
341    pub use crate::math::scan_prefix_sum;
342    #[cfg(feature = "math-algebra")]
343    pub use crate::math::{
344        bool_semiring_matmul, lattice_join, lattice_meet, semiring_min_plus_mul, sketch_mix,
345        try_bool_semiring_matmul, try_lattice_join, try_lattice_meet, try_semiring_min_plus_mul,
346        try_sketch_mix,
347    };
348    #[cfg(feature = "math-linalg")]
349    pub use crate::math::{dot, matmul, matmul_tiled, Matmul, MatmulTiled};
350    #[cfg(feature = "math-succinct")]
351    pub use crate::math::{rank1_query, rank1_superblocks, try_rank1_query, try_rank1_superblocks};
352    #[cfg(feature = "nn-linear")]
353    pub use crate::nn::linear;
354    #[cfg(feature = "nn-activation")]
355    pub use crate::nn::relu;
356    #[cfg(feature = "nn-attention")]
357    pub use crate::nn::{attention, softmax, Attention, Softmax};
358    #[cfg(feature = "nn-norm")]
359    pub use crate::nn::{layer_norm, LayerNorm};
360    #[cfg(feature = "matching-substring")]
361    pub use crate::scan::substring_search;
362    #[cfg(feature = "matching-dfa")]
363    pub use crate::scan::{aho_corasick, dfa_compile, CompiledDfa, DfaCompileError};
364}
365
366#[cfg(all(test, feature = "matching-substring"))]
367mod compat_alias_tests {
368    use vyre::ir::Node;
369
370    #[test]
371    #[allow(deprecated)]
372    fn legacy_matching_public_path_preserves_old_id_and_registry_metadata() {
373        let program =
374            crate::matching::substring::substring_search("haystack", "needle", "matches", 8, 3);
375        let [Node::Region { generator, .. }] = program.entry() else {
376            panic!("expected legacy substring search to emit one region");
377        };
378
379        assert_eq!(
380            generator.as_str(),
381            crate::scan::substring::LEGACY_MATCHING_SUBSTRING_OP_ID
382        );
383        assert_eq!(
384            crate::compat_aliases::MATCHING_SUBSTRING_ALIAS.canonical_path,
385            "vyre_libs::scan::substring"
386        );
387        assert_eq!(
388            crate::compat_aliases::MATCHING_SUBSTRING_ALIAS.deprecated_path,
389            "vyre_libs::matching::substring"
390        );
391    }
392}