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    pub use crate::ir_inner::model::types::{
102        AtomicOp, BinOp, BufferAccess, Convention, DataType, OpSignature, UnOp,
103    };
104    pub use crate::memory_model;
105    pub use crate::memory_model::MemoryOrdering;
106    pub use crate::optimizer::passes::fusion_cse::{cse, dce};
107    pub use crate::optimizer::pre_lowering::optimize;
108    pub use crate::serial::text;
109    pub use crate::transform::inline::{inline_calls, inline_calls_with_resolver, OpResolver};
110    pub use crate::validate::depth::{
111        LimitState, DEFAULT_MAX_CALL_DEPTH, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_NODE_COUNT,
112    };
113    pub use crate::validate::validate::validate;
114    pub use crate::validate::validation_error::ValidationError;
115}
116
117// Audit cleanup A12 (2026-04-30): grouped 13 loose `pub mod` decls into
118// 4 logical subdirs. Back-compat `pub use` aliases below preserve the
119// historical `vyre_foundation::<file>::*` paths so external callers
120// don't break during the transition.
121
122/// Runtime / evaluation surface (cpu_op, cpu_references, ir_eval,
123/// match_result, memory_model, perf, program_caps).
124pub mod runtime;
125
126/// Dispatch surface (dialect_lookup, extension, extern_registry).
127pub mod dispatch;
128
129/// Algebraic-laws surface (algebraic_law_registry, composition).
130pub mod algebra;
131
132/// Static-analysis surface (graph_view).
133pub mod analysis;
134
135// ---- Back-compat re-exports (old `vyre_foundation::<file>` paths) -----
136pub use algebra::algebraic_law_registry;
137pub use algebra::algebraic_law_registry::{
138    has_law, is_associative, is_commutative, laws_for_op, AlgebraicLaw, AlgebraicLawRegistration,
139};
140pub use analysis::graph_view;
141pub use dispatch::dialect_lookup;
142pub use dispatch::extern_registry;
143pub use runtime::memory_model;
144pub use runtime::memory_model::MemoryOrdering;
145
146/// Endian-fixed encode/decode helpers for `Expr::Opaque` / `Node::Opaque` payloads.
147pub mod opaque_payload;
148
149/// Packed AST (VAST) wire layout + host-side tree walks (`docs/parsing-and-frontends.md`).
150pub mod vast;
151
152pub use analysis::graph_view::{
153    from_graph, to_graph, DataEdge, DataflowKind, EdgeKind, GraphNode, GraphValidateError,
154    NodeGraph,
155};
156pub use dispatch::dialect_lookup::{
157    dialect_lookup, install_dialect_lookup, intern_string, AttrSchema, AttrType, Category,
158    DialectLookup, InternedOpId, LoweringCtx, LoweringTable, NativeModule, NativeModuleBuilder,
159    OpDef, PrimaryBinaryBuilder, PrimaryTextBuilder, ReferenceKind, SecondaryTextBuilder,
160    Signature, TextModule, TypedParam,
161};
162pub use dispatch::extern_registry::{
163    all_ops as all_extern_ops, dialects as extern_dialects,
164    ops_in_dialect as extern_ops_in_dialect, verify as verify_extern_registry, ExternDialect,
165    ExternOp, ExternVerifyError,
166};
167
168// V7-API-017: `ir_inner` is intentionally private — the public surface
169// re-exports through `pub mod ir` above. The internal name is pinned by
170// the `vyre_macros::vyre_ast_registry!` proc-macro, which emits literal
171// `crate::ir_inner::model::*` paths for the generated decoder cascades.
172// Renaming `ir_inner` to `ir` requires a coordinated proc-macro rewrite
173// + every dialect that uses `vyre_ast_registry!` recompiling against the
174// new path. Tracked for the next semver-major.
175mod ir_inner {
176    pub mod model;
177}
178// composition / cpu_op / cpu_references / extension / ir_eval / match_result
179// / perf / program_caps relocated in audit cleanup A12 (2026-04-30) — they
180// now live under runtime/, dispatch/, algebra/, analysis/. Back-compat
181// re-exports for external `vyre_foundation::<file>::*` paths land further
182// up via `pub use runtime::memory_model;` etc.
183pub use algebra::composition;
184pub use dispatch::extension;
185pub use runtime::cpu_op;
186pub use runtime::cpu_references;
187pub(crate) use runtime::ir_eval;
188pub use runtime::match_result;
189pub use runtime::match_result::ByteRange;
190pub use runtime::perf;
191
192/// Host-side IR engine helpers (prefix arrays, token filters).
193pub mod engine;
194/// Legacy lower helpers (transition surface pending driver-tier extraction).
195pub mod lower;
196/// Pass-orchestration optimizer framework.
197pub mod optimizer;
198/// Binary wire format + canonical text serialization.
199pub mod serial;
200/// IR → IR passes: inline, cse, dce, parallelism, compiler primitives.
201pub mod transform;
202/// Structural + semantic validation of vyre `Program`s.
203pub mod validate;
204/// Visitor traits + blanket adapters routing Expr/Node variants.
205pub mod visit;
206
207/// Self-substrate primitives that the optimizer + scheduler call into.
208/// Moved in-tree from vyre-libs to break a cross-workspace dep cycle.
209pub mod pass_substrate;
210
211/// Program → substrate-neutral execution planning for fusion, readback,
212/// provenance, autotune, and accuracy guard decisions.
213pub mod execution_plan;
214/// Program → required-capability analysis (used by backends and conform
215/// harnesses to skip ops whose lowering needs a capability the backend
216/// does not advertise, without maintaining hardcoded exempt lists).
217/// Relocated to `runtime/` in audit cleanup A12 (2026-04-30).
218pub use runtime::program_caps;
219
220/// Unified error type for validation, wire format, lowering, and execution.
221pub mod error;
222pub use error::{Error, Result};
223
224/// Test utilities shared across optimizer and transform test suites.
225/// `pub(crate)` because they are an internal contract — no consumer
226/// outside vyre-foundation should depend on these helpers.
227#[cfg(test)]
228pub(crate) mod test_util;