Skip to main content

vyre_foundation/
lib.rs

1//! vyre-foundation  -  substrate-neutral compiler foundation.
2//!
3//! Defines the vyre IR (`Expr`, `Node`, `Program`), the type system, the
4//! memory model, the wire format, visitor traits, and extension resolvers.
5//! Every other vyre crate depends on this one; this crate depends only on
6//! `vyre-spec`, `vyre-macros`, and lightweight third-party data crates.
7//! It never knows about concrete driver APIs, a dialect, or a backend.
8
9// Foundation owns the IR arena (`ir_inner::model::arena`), which uses two
10// `unsafe` blocks to extend bumpalo lifetimes inside a single arena owner.
11// Every other unsafe usage is forbidden by `check_lib_rs_headers.sh`.
12#![allow(unsafe_code)]
13#![allow(
14    clippy::duplicate_mod,
15    clippy::too_many_arguments,
16    clippy::double_must_use,
17    clippy::module_inception,
18    clippy::should_implement_trait,
19    clippy::type_complexity
20)]
21
22extern crate self as vyre;
23
24/// Structured optimizer diagnostics surfaced to IDEs and CI annotators.
25///
26/// Lightweight diagnostic type used by foundation optimizer passes.
27///
28/// Drivers embed these into their richer diagnostic surface; foundation
29/// only needs a human-readable message plus an optional pass/op location
30/// so that pass-scheduling errors can be rendered without pulling in
31/// driver-tier dependencies.
32pub mod diagnostics {
33
34    /// Error-level diagnostic with an optional location hint.
35    #[derive(Debug, Clone)]
36    pub struct Diagnostic {
37        /// Human-readable diagnostic message.
38        pub message: String,
39        /// Optional op/pass location the diagnostic refers to.
40        pub location: Option<OpLocation>,
41    }
42
43    impl Diagnostic {
44        /// Build an error-level diagnostic with no location.
45        #[must_use]
46        pub fn error(msg: impl Into<String>) -> Self {
47            Self {
48                message: msg.into(),
49                location: None,
50            }
51        }
52
53        /// Attach an op/pass location to this diagnostic.
54        #[must_use]
55        pub fn with_location(mut self, loc: OpLocation) -> Self {
56            self.location = Some(loc);
57            self
58        }
59    }
60
61    /// Location handle pointing at a specific pass or op id.
62    #[derive(Debug, Clone)]
63    pub struct OpLocation {
64        /// Stable pass or op identifier.
65        pub op_id: String,
66    }
67
68    impl OpLocation {
69        /// Construct a location hint from an op id.
70        #[must_use]
71        pub fn op(op_id: impl Into<String>) -> Self {
72            Self {
73                op_id: op_id.into(),
74            }
75        }
76    }
77}
78
79pub mod ir {
80    //! The vyre intermediate representation.
81    /// Backend-neutral literal evaluation for optimizer passes and lowerings.
82    pub mod eval {
83        // Audit cleanup A16 (2026-04-30): replaced `pub use crate::ir_eval::*`
84        // wildcard with explicit named re-exports per
85        // organization_contracts::foundation_wildcard_pub_reexports_are_baselined.
86        pub use crate::runtime::ir_eval::{
87            fold_binary_literal, fold_cast_literal, fold_fma_literal, fold_literal_tree,
88            fold_unary_literal,
89        };
90    }
91    pub use crate::ir_inner::model;
92    pub use crate::ir_inner::model::arena::{ArenaProgram, ExprArena, ExprRef};
93    pub use crate::ir_inner::model::expr::{Expr, ExprNode, Ident};
94    pub use crate::ir_inner::model::node::{Node, NodeExtension};
95    pub use crate::ir_inner::model::node_kind::{
96        EvalError, InterpCtx, NodeId, NodeStorage, OpId, RegionId, Value, VarId,
97    };
98    pub use crate::ir_inner::model::program::{
99        BufferDecl, CacheLocality, LinearType, MemoryHints, MemoryKind, Program, ShapePredicate,
100    };
101    /// Per-Node-variant bit-position constants for `ProgramStats::node_kinds_present`.
102    /// Compose with `ProgramStats::has_any_node_kind` for O(1) `analyze_impl` gates.
103    pub mod stats {
104        pub use crate::ir_inner::model::program::{
105            NODE_KIND_ALL_GATHER, NODE_KIND_ALL_REDUCE, NODE_KIND_ASSIGN, NODE_KIND_ASYNC_LOAD,
106            NODE_KIND_ASYNC_STORE, NODE_KIND_ASYNC_WAIT, NODE_KIND_BARRIER, NODE_KIND_BLOCK,
107            NODE_KIND_BROADCAST, NODE_KIND_EXPRESSION_BEARING_MASK, NODE_KIND_IF,
108            NODE_KIND_INDIRECT_DISPATCH, NODE_KIND_LET, NODE_KIND_LOOP, NODE_KIND_OPAQUE,
109            NODE_KIND_REDUCE_SCATTER, NODE_KIND_REGION, NODE_KIND_RESUME, NODE_KIND_RETURN,
110            NODE_KIND_STORE, NODE_KIND_TRAP,
111        };
112    }
113    pub use crate::ir_inner::model::program::ProgramStats;
114    pub use crate::ir_inner::model::types::{
115        AtomicOp, BinOp, BufferAccess, CollectiveOp, CommGroup, Convention, DataType, OpSignature,
116        UnOp,
117    };
118    pub use crate::memory_model;
119    pub use crate::memory_model::MemoryOrdering;
120    pub use crate::optimizer::passes::fusion_cse::{cse, dce};
121    pub use crate::optimizer::pre_lowering::optimize;
122    pub use crate::serial::text;
123    pub use crate::transform::inline::{inline_calls, inline_calls_with_resolver, OpResolver};
124    pub use crate::validate::depth::{
125        LimitState, DEFAULT_MAX_CALL_DEPTH, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_NODE_COUNT,
126    };
127    pub use crate::validate::validate::validate;
128    pub use crate::validate::validation_error::ValidationError;
129}
130
131// Audit cleanup A12 (2026-04-30): grouped 13 loose `pub mod` decls into
132// 4 logical subdirs. Back-compat `pub use` aliases below preserve the
133// historical `vyre_foundation::<file>::*` paths so external callers
134// don't break during the transition.
135
136/// Runtime / evaluation surface (cpu_op, cpu_references, ir_eval,
137/// match_result, memory_model, perf, program_caps).
138pub mod runtime;
139
140/// Dispatch surface (dialect_lookup, extension, extern_registry).
141pub mod dispatch;
142
143/// Algebraic-laws surface (algebraic_law_registry, composition).
144pub mod algebra;
145
146/// Static-analysis surface (graph_view).
147pub mod analysis;
148
149/// Substrate-neutral allocation reservation arithmetic shared by hot paths.
150pub mod allocation;
151
152// ---- Back-compat re-exports (old `vyre_foundation::<file>` paths) -----
153pub use algebra::algebraic_law_registry;
154pub use algebra::algebraic_law_registry::{
155    has_law, is_associative, is_commutative, laws_for_op, AlgebraicLaw, AlgebraicLawRegistration,
156};
157pub use analysis::graph_view;
158pub use dispatch::dialect_lookup;
159pub use dispatch::extern_registry;
160pub use runtime::memory_model;
161pub use runtime::memory_model::MemoryOrdering;
162
163/// Endian-fixed encode/decode helpers for `Expr::Opaque` / `Node::Opaque` payloads.
164pub mod opaque_payload;
165
166/// Packed AST (VAST) wire layout + host-side tree walks (`docs/parsing-and-frontends.md`).
167pub mod vast;
168
169pub use analysis::graph_view::{
170    from_graph, to_graph, DataEdge, DataflowKind, EdgeKind, GraphNode, GraphValidateError,
171    NodeGraph,
172};
173pub use dispatch::dialect_lookup::{
174    dialect_lookup, install_dialect_lookup, intern_string, AttrSchema, AttrType, Category,
175    DialectLookup, InternedOpId, LoweringCtx, LoweringTable, NativeModule, NativeModuleBuilder,
176    OpDef, PrimaryBinaryBuilder, PrimaryTextBuilder, ReferenceKind, SecondaryTextBuilder,
177    Signature, TextModule, TypedParam,
178};
179pub use dispatch::extern_registry::{
180    all_ops as all_extern_ops, dialects as extern_dialects,
181    ops_in_dialect as extern_ops_in_dialect, verify as verify_extern_registry, ExternDialect,
182    ExternOp, ExternVerifyError,
183};
184
185// V7-API-017: `ir_inner` is intentionally private  -  the public surface
186// re-exports through `pub mod ir` above. The internal name is pinned by
187// the `vyre_macros::vyre_ast_registry!` proc-macro, which emits literal
188// `crate::ir_inner::model::*` paths for the generated decoder cascades.
189// Renaming `ir_inner` to `ir` requires a coordinated proc-macro rewrite
190// + every dialect that uses `vyre_ast_registry!` recompiling against the
191// new path. Tracked for the next semver-major.
192mod ir_inner {
193    pub mod model;
194}
195// composition / cpu_op / cpu_references / extension / ir_eval / match_result
196// / perf / program_caps relocated in audit cleanup A12 (2026-04-30)  -  they
197// now live under runtime/, dispatch/, algebra/, analysis/. Back-compat
198// re-exports for external `vyre_foundation::<file>::*` paths land further
199// up via `pub use runtime::memory_model;` etc.
200pub use algebra::composition;
201pub use dispatch::extension;
202pub use runtime::cpu_op;
203pub use runtime::cpu_references;
204pub(crate) use runtime::ir_eval;
205pub use runtime::match_result;
206pub use runtime::match_result::ByteRange;
207pub use runtime::perf;
208
209/// Host-side IR engine helpers (prefix arrays, token filters).
210pub mod engine;
211/// Legacy lower helpers (transition surface pending driver-tier extraction).
212pub mod lower;
213/// Pass-orchestration optimizer framework.
214pub mod optimizer;
215/// Binary wire format + canonical text serialization.
216pub mod serial;
217/// IR → IR passes: inline, cse, dce, parallelism, compiler primitives.
218pub mod transform;
219/// Structural + semantic validation of vyre `Program`s.
220pub mod validate;
221/// Visitor traits + blanket adapters routing Expr/Node variants.
222pub mod visit;
223
224/// Self-substrate primitives that the optimizer + scheduler call into.
225/// Moved in-tree from vyre-libs to break a cross-workspace dep cycle.
226pub mod pass_substrate;
227
228/// Program → substrate-neutral execution planning for fusion, readback,
229/// provenance, autotune, and accuracy guard decisions.
230pub mod execution_plan;
231/// Program → required-capability analysis (used by backends and conform
232/// harnesses to skip ops whose lowering needs a capability the backend
233/// does not advertise, without maintaining hardcoded exempt lists).
234/// Relocated to `runtime/` in audit cleanup A12 (2026-04-30).
235pub use runtime::program_caps;
236
237/// Unified error type for validation, wire format, lowering, and execution.
238pub mod error;
239pub use error::{Error, Result};
240
241/// Soundness lattice for dataflow primitives. Canonical home  -  dataflow
242/// engines and composition crates consume from here per the LEGO discipline
243/// (consumers always
244/// calls vyre, vyre never calls anything else).
245pub mod soundness;
246
247/// Test utilities shared across optimizer and transform test suites.
248/// `pub(crate)` because they are an internal contract  -  no consumer
249/// outside vyre-foundation should depend on these helpers.
250#[cfg(test)]
251pub(crate) mod test_util;