polydat_core/lib.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! # polydat-core
5//!
6//! The Polydat runtime: the value model, the graph compiler, the
7//! execution engines, the kernels, the comprehension runtime, the node
8//! macro's support surface, the nodes the compiler synthesizes
9//! (adapters, passthroughs, constants, assertions, tile rendering)
10//! together with the nodes that stay with the runtime (formatting,
11//! JSON, data files, diagnostics, context, logging, and the
12//! `vectordata` accessors), and the numeric bodies the native
13//! lowerings share with the node library.
14//!
15//! A program declares typed inputs and a graph of named functions; the
16//! compiler produces a kernel whose named outputs are pulled on demand.
17//! The same inputs always yield the same outputs, on any thread, any
18//! host, and any engine, with no state carried between evaluations.
19//!
20//! Most programs depend on the `polydat` facade, which re-exports this
21//! crate together with the node library (`polydat-nodes`) and the
22//! language (`polydat-grammar`) at the paths they always had. Depend on
23//! `polydat-core` directly to assemble your own node set without the
24//! standard library linked, or to build a tool that needs the compiler
25//! and engines alone.
26//!
27//! ## Quick start
28//!
29//! The runtime compiles any program whose functions are linked. The
30//! standard functions such as `hash` live in `polydat-nodes` and
31//! register at link time, so a program that calls them needs that
32//! crate linked as well:
33//!
34//! ```rust,ignore
35//! use polydat_core::dsl::compile_polydat_with;
36//! use polydat_core::{Engine, Provenance};
37//!
38//! let mut kernel = compile_polydat_with(
39//! r#"
40//! input cycle: u64
41//! id := mod(hash(cycle), 1000)
42//! "#,
43//! Engine::Closures(Provenance::PushPull),
44//! )?;
45//!
46//! kernel.set_inputs(&[7]);
47//! assert!(kernel.pull("id").as_u64() < 1000);
48//! ```
49//!
50//! For programmatic construction, [`compile::assembly::PolydatAssembler`]
51//! wires boxed nodes by name and compiles the result the same way.
52//!
53//! ## Engines
54//!
55//! One program compiles to any of four engines and gives the same
56//! values on each; the host names one with [`Engine`], and
57//! [`Engine::default`] is the fastest the build has.
58//!
59//! - [`Engine::Interpreter`]: boxed nodes over typed value buffers,
60//! with as much of the graph fused into native cones as its
61//! [`JitMode`] allows.
62//! - [`Engine::Closures`]: one generated closure per node over a flat
63//! slot buffer.
64//! - [`Engine::Native`]: Cranelift machine code where a node has a
65//! lowering and the node's closure elsewhere. Needs the `jit`
66//! feature.
67//! - [`Engine::PureNative`]: Cranelift machine code and nothing else,
68//! calling a node's kit where it has no lowering and refusing the
69//! program when a node has neither.
70//! A host asks for it to learn whether its program is fully native.
71//! Needs the `jit` feature.
72//!
73//! [`Provenance`] chooses how much re-evaluation a changed input
74//! triggers; it is an optimization and never changes a result. Every
75//! engine accepts every program the interpreter accepts and drives it
76//! through the one [`Kernel`] trait.
77//!
78//! ## Program and state
79//!
80//! ```text
81//! inputs (u64 tuple, cursors, externs)
82//! │
83//! ▼
84//! ┌──────────────────────────────────┐
85//! │ KernelProgram immutable, Arc │ shared by every thread
86//! │ nodes · wiring · outputs · consts│
87//! └───────────────┬──────────────────┘
88//! │ create_kernel()
89//! ▼
90//! ┌──────────────────────────────────┐
91//! │ Kernel one per thread │ no locks, no shared writes
92//! │ slot buffers · provenance masks │
93//! └───────────────┬──────────────────┘
94//! ▼
95//! pull("id") → Value
96//! ```
97//!
98//! A [`KernelProgram`] is the compiled, immutable half, shared by
99//! reference; a [`Kernel`] is one thread's private state over it.
100//! Outputs are owned by their provenance: a value stands until an
101//! input that reaches it is written.
102//!
103//! ## Cargo features
104//!
105//! - **`jit`** (default): the native engine, on Cranelift.
106//! - **`vectordata`**: vector-dataset access nodes for ML/AI-oriented
107//! workloads.
108//!
109//! ## Modules
110//!
111//! - [`ast`]: the value model and node contract: [`ast::Value`],
112//! the [`ast::PolydatNode`] trait, [`ast::Port`].
113//! - [`dsl`]: compiling Polydat source:
114//! [`dsl::compile_polydat_with`] for a chosen engine,
115//! [`dsl::compile_polydat_kernel`] for the default, and
116//! [`dsl::compile_polydat`] for the interpreter kernel; the node
117//! registry, factories, and compile events.
118//! - [`compile`]: graph construction and the engines:
119//! [`compile::assembly`] (the assembler and adapter insertion),
120//! [`compile::fusion`], [`compile::closures`], [`compile::hybrid`]
121//! (the native engine's kernel), `compile::jit` (Cranelift lowering,
122//! feature-gated), [`compile::select`] (engine and provenance
123//! selection).
124//! - [`kernel`]: the runtime: the [`Kernel`] and [`KernelProgram`]
125//! traits, the interpreter's [`kernel::PolydatProgram`] and
126//! [`kernel::PolydatState`], shared cells, scopes, subcontexts,
127//! traversal activation.
128//! - [`iteration`]: comprehensions, cursors, partitions, and the
129//! coordinate algebra.
130//! - [`library`]: the nodes the compiler synthesizes (adapters via
131//! [`library::polyfill`], passthroughs, constants, assertions, tile
132//! rendering via [`library::tile_render`]) together with the nodes
133//! that stay with the runtime: formatting, JSON, data files,
134//! diagnostics, context/environment, logging, and the `vectordata`
135//! accessors; plus the library-internal support
136//! ([`library::support`]). Every other node is in `polydat-nodes`.
137//! - [`numeric`]: the numeric bodies shared by the node library and the
138//! native lowerings.
139//! - [`tile`]: Polytile at the host boundary.
140//! - [`binder`], [`derive_support`], [`resource`], [`audit`]: the typed
141//! binding contracts, the `#[polydat_node]` macro's support surface,
142//! the host resource bridge, and the log sink.
143//! - [`viz`]: AST and graph visualization, re-exported from the grammar.
144//!
145//! The narrative documentation lives in the repository under
146//! `crates/polydat/docs/`, organized by the
147//! [documentation index](https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/README.md);
148//! the [runtime model](https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/runtime_model.md),
149//! the [graph compiler](https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/graph_compiler.md),
150//! and the [engines](https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/design/engines.md)
151//! design documents are the ones to read first.
152
153// Unit tests use round-number float literals (`3.14`, `1.57`,
154// `2.71`, …) as arbitrary fixture data. clippy's `approx_constant`
155// is a deny-by-default correctness lint that reads those as
156// fat-fingered `std::f*::consts::*` — true for production code,
157// noise for test data. Scope the allowance to `cfg(test)` so the
158// lint still guards real code.
159#![cfg_attr(test, allow(clippy::approx_constant))]
160#![warn(missing_docs)]
161
162// Let the `#[polydat_node]` macro's emitted `polydat::...` paths
163// resolve when the macro is invoked from INSIDE the polydat crate
164// itself (the library's own nodes). External callers don't need this — they
165// reference `polydat` via the regular crate-name lookup.
166extern crate self as polydat;
167
168pub mod ast;
169pub mod binder;
170pub mod compile;
171pub mod convert;
172pub mod dsl;
173pub mod iteration;
174pub mod kernel;
175pub mod library;
176pub mod numeric;
177pub use polydat_grammar::viz;
178
179/// Polytile at the host boundary (polytile.md §5.6): build a tile from
180/// template text, from structural JSON text, or from a parsed JSON
181/// value, then add it to a program with [`tile::add_tiles`].
182///
183/// A host tile reaches a kernel the way every other host intention
184/// does, as a transform over the parsed program:
185///
186/// ```no_run
187/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
188/// use polydat_core::dsl::{CompileOptions, compile_ast_with_engine, parse_polydat};
189/// use polydat_core::tile::{Span, TileOptions, add_tiles, tile_from_text};
190///
191/// let tile = tile_from_text(
192/// "greeting",
193/// "text",
194/// "hi ${who}",
195/// &TileOptions::default(),
196/// Span { line: 1, col: 1 },
197/// )?;
198/// let source = "input cycle: u64\nwho := \"world\"\n";
199/// let mut program = parse_polydat(source)?;
200/// add_tiles(&mut program, vec![tile])?;
201/// let kernel = compile_ast_with_engine(
202/// &program,
203/// source,
204/// &CompileOptions::default(),
205/// None,
206/// polydat_core::Engine::default(),
207/// )?;
208/// # let _ = kernel;
209/// # Ok(())
210/// # }
211/// ```
212///
213/// There is no `compile_with_tiles`, deliberately. Adding tiles is one
214/// rewrite among the ones a host may want, and a dedicated entry point
215/// would be the only one that could not be combined with another. From
216/// `add_tiles` on, the tile is a `tile` statement like any the author
217/// wrote, and the program's own typing and engine selection apply to
218/// it unchanged.
219pub mod tile {
220 pub use crate::dsl::ast::{TileBodyKind, TileDef, TileOptions, TilePiece};
221 pub use crate::dsl::lexer::Span;
222 pub use crate::dsl::tile::{parse_template, render_template};
223 pub use crate::dsl::tile_structural::{
224 ENCODINGS, template_text_from_value, tile_from_json_text, tile_from_json_value,
225 tile_from_text,
226 };
227 /// Add host-built tiles to a parsed program; see
228 /// [`transform::add_tiles`](crate::dsl::transform::add_tiles).
229 pub use crate::dsl::transform::add_tiles;
230}
231
232// Dependency-inverted resource-accessor bridge. A
233// type-erased trait + process-global install point by which a
234// kernel node reaches a live, host-owned resource by fingerprint,
235// without polydat depending on the host runtime.
236pub mod resource;
237
238// Proc-macro trait surface (library_catalog.md, "Registration"). The `polydat-derive`
239// crate emits paths like `polydat::derive_support::Wire` /
240// `Const` that resolve here.
241pub mod derive_support;
242
243// `Const<T>` wrapper re-exported at crate root
244// for ergonomic use in `#[polydat_node]` function signatures.
245pub use derive_support::Const;
246
247/// The slot surface of a compiled kernel: the extended API, opt-in at
248/// the import, over and above the `Kernel` trait every engine answers.
249pub use compile::SlotKernel;
250/// How much of the interpreter's graph is fused into native cones:
251/// what `Engine::Interpreter` carries.
252pub use compile::cone::JitMode;
253/// The engine a host chooses and the one error of every constructor
254/// that takes it (docs/design/engines.md §3.5).
255pub use compile::select::{Engine, EnginePlan, KernelError, Provenance};
256/// One kernel API for every engine, and the one error a write to a
257/// declared slot can fail with. `WriteError` sits beside `KernelError`
258/// at the root because they are the pair a host handles: one for
259/// building a kernel, one for writing to it.
260pub use kernel::{Kernel, KernelProgram, ProgramId, WriteError};
261
262// Panic reporting renders one full diagnostic: host runtimes with
263// their own panic reporting declare it so the eval-panic hook
264// prints a short notice instead of the full diagnostic.
265pub use kernel::set_panic_reporting_downstream;
266
267// Re-export the `#[polydat_node]` attribute so
268// library callers can write `#[polydat::polydat_node]` without
269// a separate `use polydat_derive::polydat_node;` line.
270pub use polydat_derive::polydat_node;
271
272// Re-export `inventory` so the macro's emitted
273// `::polydat::inventory::submit!` path resolves at every call
274// site without users having to add `inventory` to their own
275// dependencies.
276pub use inventory;
277
278/// Re-exported for `#[polydat_node]`-generated Phase-2 buffer
279/// casts on `half::f16`-typed wires (the generated code spells
280/// `polydat::half::f16`, which `extern crate self as polydat`
281/// resolves inside this crate too).
282pub use half;
283
284/// The resource-accessor bridge at the crate root: the host implements
285/// `polydat::ResourceAccessor` and installs it into a program tree's
286/// `polydat::ResourceScope`, which nodes reach through their build
287/// context.
288pub use resource::{ResourceAccessor, ResourceScope, ScopeJoinError};
289
290/// Host-log sink bridge — the sanctioned public path for installing
291/// a leveled log sink into the kernel (`set_log_fn`) and for emitting
292/// through it (`warn` / `info` / …). The activity runner installs its
293/// `observer::log` here so polydat's cycle-time data-source audit lines
294/// land in `session.log`. A host with no `log` logger of its own can
295/// install `audit::LogBridge` to route vectordata's `log` records into
296/// the same channel. This is the one public entry point for the
297/// audit channel; the implementation lives under `library::support`,
298/// which is library-internal and must not be reached directly.
299pub use library::support::audit;