Skip to main content

no_mistakes_postgres_engine/embedded/helpers/program/exec/
mod.rs

1//! Runs a lowered helper against the abstract arguments of one call.
2//!
3//! Tests that depend only on known values are decided; tests on unknown
4//! scalars fork the path into both alternatives (at most
5//! [`MAX_EMBEDDED_SQL_VARIANTS`] live paths). A path that throws ends. Every
6//! unsupported construct, unresolvable callee or read of a caller-owned
7//! builder fails the whole run, so the call stays `Dynamic`.
8
9mod call;
10mod expr;
11mod forms;
12mod loops;
13mod ops;
14mod sql;
15mod stmt;
16mod val;
17
18use super::{Param, Program};
19use crate::embedded::helpers::SiteArg;
20use crate::embedded::walk::resolve::functions::provenance::RecoveredSql;
21use crate::embedded::MAX_EMBEDDED_SQL_VARIANTS;
22use std::path::Path as FsPath;
23use val::{empty_sql, Obj, Path, Text, Val};
24
25/// Deepest chain of helper-calls-helper that is followed.
26pub const MAX_CALL_DEPTH: u8 = 8;
27
28/// What a helper call produced on one path.
29#[derive(Clone, PartialEq, Eq)]
30pub enum Ret {
31    /// Nothing, or a scalar that is not SQL.
32    Void,
33    /// A string the helper built, with provenance when it wrote it.
34    Str(String, Option<RecoveredSql>),
35    /// A fresh builder.
36    Sql(RecoveredSql),
37    /// The builder the caller passed at this parameter index.
38    Param(usize),
39}
40
41#[derive(Clone, PartialEq, Eq)]
42pub struct Outcome {
43    pub ret: Ret,
44    /// Text appended to each parameter that received a builder.
45    pub suffixes: Vec<(usize, RecoveredSql)>,
46}
47
48/// Result of asking for a helper by name.
49pub enum Callee {
50    /// No program of that name: it may still be an ignorable non-SQL function.
51    Unresolved,
52    /// A program exists but could not be run for these arguments.
53    Failed,
54    Done(Vec<Outcome>),
55}
56
57/// Looks helpers up in the module being executed (and beyond, for imports).
58pub trait Callees {
59    fn call(&mut self, name: &str, args: &[SiteArg]) -> Callee;
60}
61
62pub(super) struct Machine<'a> {
63    pub(super) stamp: Option<&'a FsPath>,
64    pub(super) callees: &'a mut dyn Callees,
65    pub(super) params: Vec<String>,
66}
67
68/// Every alternative outcome of `program` called with `args`, or `None`.
69/// `stamp` is the module recorded as the origin of the program's own text
70/// (`None` when it is the executor's own module).
71pub fn run(
72    program: &Program,
73    args: &[SiteArg],
74    stamp: Option<&FsPath>,
75    callees: &mut dyn Callees,
76) -> Option<Vec<Outcome>> {
77    let mut machine = Machine {
78        stamp,
79        callees,
80        params: program.params.iter().map(|p| p.name.clone()).collect(),
81    };
82    let mut path = Path::new();
83    let mut builders = Vec::new();
84    for (index, param) in program.params.iter().enumerate() {
85        let value = match args.get(index) {
86            Some(SiteArg::Builder) => {
87                if !param.builder {
88                    return None;
89                }
90                let value = path.new_builder(empty_sql(), Some(index));
91                if let Val::Sql(id) = value {
92                    builders.push((index, id));
93                }
94                value
95            }
96            Some(SiteArg::Undefined) | None => default_value(&mut machine, param, &mut path)?,
97            Some(arg) => arg_value(arg),
98        };
99        path.bind(&param.name, value);
100    }
101    let paths = machine.block(&program.body, vec![path])?;
102    let mut outcomes = Vec::new();
103    for path in paths {
104        let outcome = machine.outcome(path, &builders)?;
105        if !outcomes.contains(&outcome) {
106            outcomes.push(outcome);
107        }
108    }
109    (outcomes.len() <= MAX_EMBEDDED_SQL_VARIANTS).then_some(outcomes)
110}
111
112fn default_value(machine: &mut Machine<'_>, param: &Param, path: &mut Path) -> Option<Val> {
113    let Some(default) = &param.default else {
114        return Some(Val::Undef);
115    };
116    let mut results = machine.eval(default, path.clone())?;
117    let (next, value) = results.pop().filter(|_| results.is_empty())?;
118    *path = next;
119    Some(value)
120}
121
122fn arg_value(arg: &SiteArg) -> Val {
123    match arg {
124        SiteArg::Literal(literal) => Val::Str(Text {
125            value: literal.text.clone(),
126            prov: None,
127        }),
128        SiteArg::Bool(value) => Val::Bool(*value),
129        SiteArg::Null => Val::Null,
130        SiteArg::Undefined => Val::Undef,
131        SiteArg::Object(props) => Val::Obj(Obj {
132            props: props
133                .iter()
134                .map(|(key, value)| (key.clone(), arg_value(value)))
135                .collect(),
136            open: false,
137        }),
138        SiteArg::Array(items) => Val::Arr(items.iter().map(arg_value).collect()),
139        SiteArg::Scalar | SiteArg::Builder => Val::Unknown,
140    }
141}