Skip to main content

decl_lang/qengine/
qeval.rs

1//! Query entry points using shared programs and the value layer's slot graph.
2use crate::ast::{Expr, TypeAst};
3use crate::engine::{Engine, RootSrc};
4use crate::semantics::*;
5use std::rc::Rc;
6
7/// Compatibility with callers that handle a query capability fallback.
8#[derive(Debug)]
9pub struct Unsupported(pub String);
10
11/// The settled values and diagnostics of a query evaluation.
12pub struct QReport {
13    /// no error diagnostic was produced
14    pub ok: bool,
15    /// each output, serialized as canonical JSON text
16    pub outputs: Vec<(String, String)>,
17    /// evaluation and validation diagnostics
18    pub diagnostics: Vec<Diag>,
19}
20
21type RootSpec = (String, TypeAst, Rc<Expr>, Rc<Env>);
22
23/// Evaluate a single module using shared programs and retained reference rounds.
24pub fn qevaluate(env: Rc<Env>) -> Result<QReport, Unsupported> {
25    let roots: Vec<RootSpec> = env
26        .outputs
27        .borrow()
28        .iter()
29        .map(|(n, t, e)| (n.clone(), t.clone(), e.clone(), env.clone()))
30        .collect();
31    let (report, _eng) = eval_rounds(&env, &roots, &[], &[], true)?;
32    Ok(report)
33}
34
35/// A bound input document for the universe: its name, raw value, and the
36/// module scope that declares it.
37pub struct BoundSpec {
38    /// the input's name
39    pub name: String,
40    /// the document, as the JSON reader gives it
41    pub raw: Value,
42    /// the scope that declares the input
43    pub menv: Rc<Env>,
44}
45
46/// Evaluate a whole multi-module universe (§8.8): every module's outputs are
47/// roots, each bound in its own module scope into the entry module's universe;
48/// bound input documents are roots too. Returns the report and the settled
49/// round's value layer (its roots populated and forced) so the caller can
50/// serialize through it exactly as `run_universe` does.
51pub fn qevaluate_universe(
52    mods: &[Rc<Env>],
53    entry: &Rc<Env>,
54    binds: &[BoundSpec],
55) -> Result<(QReport, Rc<Engine>), Unsupported> {
56    run_universe(mods, entry, binds, true)
57}
58
59/// Evaluate module values and diagnostics, optionally serializing the outputs.
60/// Module consumers render selected roots themselves; building every root's
61/// JSON here would allocate a second output only to discard it.
62pub(crate) fn run_universe(
63    mods: &[Rc<Env>],
64    entry: &Rc<Env>,
65    binds: &[BoundSpec],
66    serialize_outputs: bool,
67) -> Result<(QReport, Rc<Engine>), Unsupported> {
68    let roots: Vec<RootSpec> = mods
69        .iter()
70        .flat_map(|m| {
71            m.outputs
72                .borrow()
73                .iter()
74                .map(|(n, t, e)| (n.clone(), t.clone(), e.clone(), m.clone()))
75                .collect::<Vec<_>>()
76        })
77        .collect();
78    eval_rounds(entry, &roots, binds, mods, serialize_outputs)
79}
80
81/// The rounds driver shared by the single-module and universe entries: bind the
82/// bound inputs and roots through shared programs, forcing through the value
83/// layer's rounds machinery until `$referrers` settles. `hook_mods` are
84/// the module scopes whose elaboration hooks (a const in a type position, a
85/// unit factor) point at each round's value layer — every module for a
86/// universe, none for a single module (as `run_universe` and `run_pipeline` do).
87fn eval_rounds(
88    entry: &Rc<Env>,
89    roots: &[RootSpec],
90    binds: &[BoundSpec],
91    hook_mods: &[Rc<Env>],
92    serialize_outputs: bool,
93) -> Result<(QReport, Rc<Engine>), Unsupported> {
94    let bind = |eng: &Rc<Engine>| {
95        for m in hook_mods {
96            eng.install_hooks(m, true);
97        }
98        // a bound input document is a root of the universe, available before the
99        // outputs that read it (§9.2); it binds through the value layer
100        for b in binds {
101            let decl = b.menv.inputs.borrow().get(&b.name).cloned();
102            let Some((ty_ast, _)) = decl else { continue };
103            let sc = Scope::new(&b.name, Some(b.menv.clone()));
104            match b.menv.resolve(&ty_ast, None) {
105                Ok(rt) => eng.bind_root(&b.name, RootSrc::Doc(b.raw.clone()), &rt, &sc),
106                Err(e) => entry.report(Diag::error(e, b.name.clone(), None)),
107            }
108        }
109        for (name, ty_ast, expr, menv) in roots {
110            if !eng.should_bind_root(name) {
111                continue;
112            }
113            let Ok(rt) = menv.resolve(ty_ast, None) else {
114                continue;
115            };
116            eng.bind_root(
117                name,
118                RootSrc::Expr(expr),
119                &rt,
120                &Scope::new(name, Some(menv.clone())),
121            );
122        }
123    };
124    let eng = Engine::evaluate_query(entry, &bind);
125    eng.validate_all("");
126    let diags = sort_diags(entry.diagnostics_vec()); // §6.7
127    entry.diag_set(diags.clone());
128    let ok = !diags.iter().any(|d| d.severity == "error");
129    let outputs = if ok && serialize_outputs {
130        roots
131            .iter()
132            .filter_map(|(n, _, _, _)| {
133                entry
134                    .root(n)
135                    .map(|v| (n.clone(), eng.serialize(&v, n, false)))
136            })
137            .collect()
138    } else {
139        vec![]
140    };
141    Ok((
142        QReport {
143            ok,
144            outputs,
145            diagnostics: diags,
146        },
147        eng,
148    ))
149}