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 feature = "math-algebra",
147 feature = "math-succinct"
148))]
149pub mod math;
150
151/// Logical dialect - element-wise boolean composition.
152#[cfg(feature = "logical")]
153pub mod logical;
154
155/// Neural-network dialect - activation, normalization, attention, linear.
156#[cfg(any(
157 feature = "nn-activation",
158 feature = "nn-linear",
159 feature = "nn-norm",
160 feature = "nn-attention"
161))]
162pub mod nn;
163
164/// Pattern-scanning dialect - substring, DFA, Aho-Corasick, rule
165/// dispatch, secfinding generation. Renamed from `matching` per
166/// ROADMAP T032 (SEPARATION_AUDIT S7) - "scan" reflects the actual
167/// semantic surface (not just substring matching). The original
168/// `matching` name is kept as a deprecated alias for backwards
169/// compatibility.
170#[cfg(any(
171 feature = "matching-substring",
172 feature = "matching-dfa",
173 feature = "matching-nfa"
174))]
175pub mod scan;
176
177/// Backwards-compat alias for [`scan`]. New code should use
178/// `vyre_libs::scan::*`. Alias metadata lives in
179/// [`compat_aliases::MATCHING_ALIAS`] so internal audits and public docs
180/// agree on the canonical owner.
181#[cfg(any(
182 feature = "matching-substring",
183 feature = "matching-dfa",
184 feature = "matching-nfa"
185))]
186#[deprecated(
187 since = "0.4.1",
188 note = "use `vyre_libs::scan` instead - the `matching` name is kept as a transition alias only"
189)]
190pub mod matching;
191
192/// Decode / decompression compositions - base64, hex, DEFLATE (stored),
193/// more coming. Pairs with `vyre-libs::matching::dfa` in the fused
194/// decode→scan pipeline (Innovation I.1).
195#[cfg(feature = "decode")]
196pub mod decode;
197
198/// Hash / checksum dialect - FNV-1a-32, FNV-1a-64, CRC-32, Adler-32,
199/// BLAKE3 compression. Consolidated from the former `vyre-libs::crypto`
200/// module per Migration 3. Every op lives here as a pure Cat-A
201/// composition over existing IR primitives (no dedicated target builder emitter
202/// arm required, per the intrinsic-vs-library rule).
203#[cfg(feature = "hash")]
204pub mod hash;
205
206/// Text-processing compositions for the GPU C parser pipeline
207/// (Phase L1+): byte classification, UTF-8 validation, line index.
208pub mod text;
209
210/// Representation sub-dialect: bit-packing and unpacking.
211pub mod representation;
212
213/// GPU parser infrastructure (Phase L3+): bracket matching, DFA
214/// lexer driver, LR(1) table walker. Grammar tables are generated
215/// host-side by `downstream analyzer-grammar-gen` and loaded as ReadOnly buffers.
216pub mod parsing;
217
218/// Front-end-agnostic borrow-check engine: the neutral `BorrowFacts` IR and the
219/// dataflow analysis over it. Producers (the Rust front-end now, a rustc adapter
220/// later) lower to `BorrowFacts`; the engine never depends on any front-end,
221/// which is what lets the borrow checker eventually run standalone.
222pub mod borrowck;
223
224/// Packed AST walks (`ast_walk_*` catalog ops).
225pub mod graph;
226
227/// GPU-native compiler middle-end (CFG and ELF emission helpers) for the C pipeline.
228#[cfg(feature = "c-parser")]
229pub mod compiler;
230
231#[cfg(feature = "c-parser")]
232pub use compiler::{
233 cfg::c11_build_cfg_and_gotos, object_writer::opt_lower_elf,
234 regalloc::opt_x86_64_register_allocation, stack_layout::opt_stack_layout_generation,
235 types_layout::c11_compute_alignments,
236};
237
238/// Security / taint compositions for static program analysis.
239/// Every op registers via `inventory::submit!` and lives under a
240/// stable op id. The implementations compose graph and dataflow
241/// primitives so downstream analyzers lower to one production GPU-facing
242/// surface.
243#[cfg(feature = "security")]
244pub mod security;
245
246/// GPU-accelerated visual effects - blur, shadow, filter chain,
247/// gradient, compositing, and glass material. Tier 3 compositions
248/// over `math::conv1d` (Tier 2.5) and bare IR expressions. The
249/// Molten web engine's visual effect substrate.
250#[cfg(feature = "visual")]
251pub mod visual;
252
253/// Compatibility facade for GPU dataflow compositions.
254/// This path remains for older `vyre-libs::dataflow::*` consumers and must
255/// not grow a parallel dataflow implementation tree.
256pub mod dataflow;
257
258pub use borrowck::{analyze as analyze_borrow_facts, ConflictKind};
259#[cfg(feature = "c-parser")]
260pub(crate) use compiler::atomic_collect::atomic_collect_u32;
261#[cfg(any(
262 feature = "math-linalg",
263 feature = "math-scan",
264 feature = "math-broadcast"
265))]
266pub(crate) use math::elementwise::{f32_elementwise_mul, F32MulRhs};
267pub use dataflow::{
268 validate_dynamic_pipeline, DynamicPrimitiveSoundness, DynamicSoundnessViolation,
269 PrecisionContract, SharedFactHeader, SharedFactKind, Soundness, SoundnessTagged,
270};
271#[cfg(feature = "nn-linear-4bit")]
272pub(crate) use math::linalg::{
273 plan_matmul_kernel, F32MatmulMode, MatmulFallbackReason, MatmulKernelCapabilities,
274 MatmulKernelPath, MatmulKernelPlan, MatrixShape,
275};
276#[cfg(feature = "matching-substring")]
277pub(crate) use scan::substring::{substring_search_with_op_id, LEGACY_MATCHING_SUBSTRING_OP_ID};
278
279// vyre-libs::hardware removed (audit 2026-04-21 BLOCKER-1/6).
280// Canonical Cat-C intrinsics live exclusively in the `vyre-intrinsics`
281// crate; library compositions of atomic / clamp / lzcnt / tzcnt ops
282// live in `vyre-libs::math::*` (which uses `Expr::Atomic`, `Expr::min`,
283// `Expr::max`, `Expr::popcount` directly per library-tiers.md).
284//
285// vyre-libs::crypto removed (audit 2026-04-21 BLOCKER-3). Deprecated
286// shim deleted in favor of the canonical path at `vyre-libs::hash`.
287//
288// vyre-libs::composite removed (audit 2026-04-21 BLOCKER-3). The three
289// hash ops that lived there (adler32, crc32, fnv1a64) are canonical at
290// `vyre-libs::hash::*`.
291
292/// Rule-engine dialect - typed conditions, formulas, and program builder used
293/// by detection rule compilers.
294#[cfg(feature = "rule")]
295pub mod rule;
296
297/// Vector-widened string interning. CHD perfect hash
298/// over Tier-B label families - 60k+ function-name strings reduce
299/// to one subgroup-shuffle + one DRAM load on the GPU.
300#[cfg(feature = "intern")]
301pub mod intern;
302
303/// Operation contract presets used by catalog entries.
304pub mod contracts;
305/// Type-signature constants shared across op definitions.
306pub mod signatures;
307/// Re-exports every type-signature constant at the crate root for convenient access.
308pub use signatures::{
309 BOOL_OUTPUTS, BYTES_TO_BYTES_INPUTS, BYTES_TO_BYTES_OUTPUTS, BYTES_TO_U32_OUTPUTS,
310 F32_F32_F32_INPUTS, F32_F32_INPUTS, F32_INPUTS, F32_OUTPUTS, I32_OUTPUTS, U32_INPUTS,
311 U32_OUTPUTS, U32_U32_INPUTS,
312};
313/// Making this crate's ops resolvable in the current process.
314pub mod dialect_init;
315/// Pre-sweep shader snapshot migration entries, collected via inventory.
316/// `pub(crate)` because the registry is an internal pre-sweep tool -
317/// downstream dialects do not submit through this path.
318pub(crate) mod test_migration;
319/// Test support components for vyre-libs.
320pub mod test_support;
321
322/// Driver-tier observability re-export so vyre-libs consumers can
323/// snapshot substrate counters + decision histograms without taking a
324/// direct vyre-driver dependency.
325pub mod observability {
326 pub use vyre_driver::observability::{BackendObservabilityProvider, DriverObservability};
327}
328
329/// Re-export the small set of vyre types every composition function
330/// returns. Consumers can `use vyre_libs::prelude::*` and get the API
331/// plus the types it returns.
332pub mod prelude {
333 pub use vyre::ir::{BufferAccess, BufferDecl, DataType, Expr, Node, Program};
334 pub use vyre::{BackendError, DispatchConfig};
335 pub use vyre_foundation::ir::model::expr::GeneratorRef;
336
337 // P2.1 / P2.2: the typed-tensor API + shared builder primitives.
338 // Every Cat-A op ships with a TensorRef-accepting builder; the
339 // prelude exposes the full construction surface so `use
340 // vyre_libs::prelude::*;` is enough to author a new Cat-A op.
341 pub use crate::builder::{check_tensors, BuildOptions};
342 pub use crate::tensor_ref::{
343 check_dtype, check_shape, check_unique_names, TensorRef, TensorRefError,
344 };
345
346 // Region wrapper - every composition emits its body through this.
347 pub use crate::region::{wrap, wrap_anonymous, wrap_child};
348
349 // Built-in Cat-A builders (gated on the relevant feature flags so
350 // minimum-footprint consumers don't pay for the ones they skip).
351 #[cfg(feature = "decode")]
352 pub use crate::decode::{base64_decode, hex_decode, inflate, ziftsieve_gpu};
353 #[cfg(feature = "crypto-blake3")]
354 pub use crate::hash::blake3_compress;
355 #[cfg(feature = "crypto-fnv")]
356 pub use crate::hash::fnv1a32;
357 #[cfg(feature = "logical")]
358 pub use crate::logical::{and, nand, nor, or, xor};
359 #[cfg(feature = "math-broadcast")]
360 pub use crate::math::broadcast;
361 #[cfg(feature = "math-scan")]
362 pub use crate::math::scan_prefix_sum;
363 #[cfg(feature = "math-algebra")]
364 pub use crate::math::{
365 bool_semiring_matmul, lattice_join, lattice_meet, semiring_min_plus_mul, sketch_mix,
366 try_bool_semiring_matmul, try_lattice_join, try_lattice_meet, try_semiring_min_plus_mul,
367 try_sketch_mix,
368 };
369 #[cfg(feature = "math-linalg")]
370 pub use crate::math::{dot, matmul, matmul_tiled, Matmul, MatmulTiled};
371 #[cfg(feature = "math-succinct")]
372 pub use crate::math::{rank1_query, rank1_superblocks, try_rank1_query, try_rank1_superblocks};
373 #[cfg(feature = "nn-linear")]
374 pub use crate::nn::linear;
375 #[cfg(feature = "nn-activation")]
376 pub use crate::nn::relu;
377 #[cfg(feature = "nn-attention")]
378 pub use crate::nn::{attention, softmax, Attention, Softmax};
379 #[cfg(feature = "nn-norm")]
380 pub use crate::nn::{layer_norm, LayerNorm};
381 #[cfg(feature = "matching-substring")]
382 pub use crate::scan::substring_search;
383 #[cfg(feature = "matching-dfa")]
384 pub use crate::scan::{aho_corasick, dfa_compile, CompiledDfa, DfaCompileError};
385}
386
387#[cfg(all(test, feature = "matching-substring"))]
388mod compat_alias_tests {
389 use vyre::ir::Node;
390
391 #[test]
392 #[allow(deprecated)]
393 fn legacy_matching_public_path_preserves_old_id_and_registry_metadata() {
394 let program =
395 crate::matching::substring::substring_search("haystack", "needle", "matches", 8, 3);
396 let [Node::Region { generator, .. }] = program.entry() else {
397 panic!("expected legacy substring search to emit one region");
398 };
399
400 assert_eq!(
401 generator.as_str(),
402 crate::scan::substring::LEGACY_MATCHING_SUBSTRING_OP_ID
403 );
404 assert_eq!(
405 crate::compat_aliases::MATCHING_SUBSTRING_ALIAS.canonical_path,
406 "vyre_libs::scan::substring"
407 );
408 assert_eq!(
409 crate::compat_aliases::MATCHING_SUBSTRING_ALIAS.deprecated_path,
410 "vyre_libs::matching::substring"
411 );
412 }
413}