Skip to main content

oxilite_synalog/
lib.rs

1//! Synalog over oxilite: the Datalog-family language for AI agents, as an optional second rule
2//! dialect beside `oxilite-datalog`.
3//!
4//! [Synalog](https://github.com/SynaLinks/synalog) (a Rust rewrite of Logica) has named
5//! arguments, full expressions, head aggregation, functors, `@OrderBy`/`@Limit` and a verifier
6//! whose errors are written for a model to read. It compiles to SQL. This crate uses its parser,
7//! verifier and compiler unchanged, two ways:
8//!
9//! - on its own: [`check`] and [`compile_for_engine`], for any engine Synalog supports;
10//! - over the triple store: [`compile`] / [`prepare`] present the store as relational tables —
11//!   `triples(subject, predicate, object, kind, datatype, lang, graph)` plus the predicate and
12//!   class tables a program declares — and make the SQL run on every backend, D1 included.
13//!
14//! ```text
15//! # @table parent <http://example.org/parent>
16//!
17//! @Recursive(Ancestor, 10);
18//! Ancestor(x:, y:) distinct :- parent(subject: x, object: y);
19//! Ancestor(x:, y:) distinct :- Ancestor(x:, y: m), parent(subject: m, object: y);
20//!
21//! Adult(name:) distinct :- triples(subject: p, predicate: "http://example.org/age", object: age),
22//!                          triples(subject: p, predicate: "http://example.org/name", object: name),
23//!                          age >= 18;
24//! ```
25//!
26// @lat: [[architecture#Synalog frontend]]
27#![forbid(unsafe_code)]
28
29pub mod error;
30pub mod exec;
31#[cfg(feature = "json")]
32pub mod json;
33pub mod rewrite;
34pub mod tables;
35
36pub use error::{Result, SynalogError};
37pub use exec::{SynalogJob, SynalogResult};
38pub use oxilite_core::sql::SqlValue;
39/// The language crate, for callers that need its full API.
40pub use synalog;
41pub use tables::Table;
42
43use oxilite_core::sql::Capabilities;
44use std::collections::HashMap;
45use std::panic::{catch_unwind, AssertUnwindSafe};
46use synalog::compiler::universe::{LogicaProgram, Pagination};
47use synalog::parser::Json;
48
49/// The engines [`compile_for_engine`] accepts.
50pub const ENGINES: &[&str] = synalog::compiler::dialects::SUPPORTED_ENGINES;
51
52/// Options for running a program on the store. The scope defaults match SPARQL's: the default
53/// graph only, no inferences, the current state.
54#[derive(Debug, Clone, Default)]
55pub struct Options {
56    /// Read every graph rather than only the default graph.
57    pub union_default_graph: bool,
58    /// Also read materialized inferences (`quads_inf`).
59    pub include_inferred: bool,
60    /// At most this many rows (combined with the program's `@Limit` by taking the smaller).
61    pub limit: Option<u64>,
62    /// Skip this many rows.
63    pub offset: Option<u64>,
64    /// Tables declared in code, beside the program's `# @table` / `# @class` pragmas.
65    pub tables: Vec<Table>,
66    /// Read the store as it was at this version (`HEAD~1`, `#42`, `@2026-09-01T00:00:00Z`).
67    /// The store resolves it to [`Self::as_of_tick`] before compiling.
68    pub as_of: Option<String>,
69    /// The resolved tick of the version read.
70    pub as_of_tick: Option<i64>,
71}
72
73/// A program compiled for the store.
74#[derive(Debug, Clone)]
75pub struct Compiled {
76    /// The one statement to run.
77    pub sql: String,
78    /// The predicate's head columns, in order.
79    pub columns: Vec<String>,
80    /// The store tables the statement reads.
81    pub tables: Vec<String>,
82}
83
84/// Runs Synalog code, turning a panic into an error: an agent's program must not abort the host.
85fn guarded<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {
86    catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|panic| {
87        let why = panic
88            .downcast_ref::<&str>()
89            .map(|s| (*s).to_owned())
90            .or_else(|| panic.downcast_ref::<String>().cloned())
91            .unwrap_or_else(|| "unknown cause".into());
92        Err(SynalogError::Compile(format!(
93            "the Synalog compiler failed: {why}"
94        )))
95    })
96}
97
98/// Parses and verifies a program.
99fn parse_checked(src: &str) -> Result<Json> {
100    guarded(|| {
101        let parsed = synalog::parser::parse_file(src, None, &[])
102            .map_err(|e| SynalogError::Parse(e.to_string()))?;
103        let checked = synalog::verifier::validate(&parsed);
104        if !checked.is_valid() {
105            return Err(SynalogError::Verify(
106                checked.errors.iter().map(ToString::to_string).collect(),
107            ));
108        }
109        Ok(parsed)
110    })
111}
112
113/// Runs the Synalog verifier: `Ok` when the program is valid, else every error it reports.
114pub fn check(src: &str) -> Result<()> {
115    parse_checked(src).map(|_| ())
116}
117
118/// Compiles one predicate for one engine, exactly as Synalog does: the dialect without a store.
119pub fn compile_for_engine(
120    src: &str,
121    predicate: &str,
122    engine: &str,
123    limit: Option<u64>,
124    offset: Option<u64>,
125) -> Result<String> {
126    if !ENGINES.contains(&engine) {
127        return Err(SynalogError::unsupported(format!(
128            "engine `{engine}`; Synalog supports {}",
129            ENGINES.join(", ")
130        )));
131    }
132    let parsed = parse_checked(src)?;
133    guarded(|| {
134        let program = program(&parsed, engine)?;
135        defined(&program, predicate)?;
136        program
137            .formatted_predicate_sql_with_pagination(predicate, &Pagination { limit, offset })
138            .map_err(|e| SynalogError::Compile(e.to_string()))
139    })
140}
141
142fn program(parsed: &Json, engine: &str) -> Result<LogicaProgram> {
143    LogicaProgram::new_with_engine(parsed, HashMap::new(), HashMap::new(), Some(engine))
144        .map_err(|e| SynalogError::Compile(e.to_string()))
145}
146
147fn defined(program: &LogicaProgram, predicate: &str) -> Result<()> {
148    if program.defined_predicates().contains(predicate) {
149        return Ok(());
150    }
151    let mut defined = program.user_defined_predicates();
152    defined.sort();
153    Err(SynalogError::UnknownPredicate {
154        predicate: predicate.to_owned(),
155        defined,
156    })
157}
158
159/// Compiles one predicate to a statement over the store's tables.
160pub fn compile(
161    src: &str,
162    predicate: &str,
163    caps: &Capabilities,
164    options: &Options,
165) -> Result<Compiled> {
166    if options.as_of.is_some() && options.as_of_tick.is_none() {
167        return Err(SynalogError::unsupported(
168            "as_of must be resolved to a tick by the store before compiling",
169        ));
170    }
171    if options.as_of_tick.is_some() && options.include_inferred {
172        return Err(SynalogError::unsupported(
173            "inferences describe the current state only; they cannot be combined with as_of",
174        ));
175    }
176    let mut declared = tables::pragmas(src)?;
177    declared.extend(options.tables.iter().cloned());
178    tables::validate(&declared)?;
179
180    let parsed = parse_checked(src)?;
181    let (raw, columns) = guarded(|| {
182        let program = program(&parsed, "sqlite")?;
183        defined(&program, predicate)?;
184        let pagination = Pagination {
185            limit: options.limit,
186            offset: options.offset,
187        };
188        let sql = program
189            .formatted_predicate_sql_with_pagination(predicate, &pagination)
190            .map_err(|e| SynalogError::Compile(e.to_string()))?;
191        Ok((sql, program.predicate_columns(predicate)))
192    })?;
193    let body = rewrite::portable(&raw)?;
194    let (sql, tables) = tables::inject(&body, &declared, options);
195    rewrite::check_limits(&sql, caps)?;
196    Ok(Compiled {
197        sql,
198        columns,
199        tables,
200    })
201}
202
203/// Compiles a predicate into a job that runs it.
204pub fn prepare(
205    src: &str,
206    predicate: &str,
207    caps: &Capabilities,
208    options: &Options,
209) -> Result<SynalogJob> {
210    Ok(SynalogJob::new(compile(src, predicate, caps, options)?))
211}