relate_executor/exec/procedures/contract.rs
1//! The `CALL` contract vocabulary: the static clause shape ([`CallSpec`])
2//! and its one runtime contract, the argument-value matching predicates,
3//! and the void-procedure unit-row rule. (The declared-type vocabulary's
4//! canonical home is `crate::procedure_registry`, beside the type strings
5//! it interprets; the name classification lives in the module root,
6//! beside the resolution that consumes it.)
7
8use relate_core::{Error, Result, Value};
9use relate_ir::{CallArgs, Expr, YieldItems};
10use relate_names::SmallName;
11
12use crate::ctx::ExecCtx;
13use crate::procedure_registry::ProcSignature;
14use crate::row::Row;
15
16pub(crate) fn call_args_match(proc_val: &Value, given: &Value) -> bool {
17 // `eq_non_null` already covers the Int/Float cross-comparison with the
18 // exact rule (`relate_model::canonical_key::eq_i64_f64`); a separate
19 // `as f64` fallback here would reintroduce the lossy cast.
20 proc_val.eq_non_null(given) || (proc_val.is_null() && given.is_null())
21}
22
23/// The one typed required-STRING argument reader the CALL paths share:
24/// one declared argument, by explicit position or implicit
25/// parameter/row column, a STRING or the typed rejection — the procedure
26/// name rendered through the clause's carrier on the error branches
27/// alone, so the per-row read path allocates nothing.
28pub(crate) fn string_arg(
29 ctx: ExecCtx<'_>,
30 row: &Row,
31 source: &CallArgs,
32 index: usize,
33 arg_name: &str,
34 name: &SmallName,
35) -> Result<String> {
36 // The required form over the one optional reader: absent/null adds the
37 // required-argument rejection.
38 match optional_string_arg(ctx, row, source, index, arg_name, name)? {
39 Some(value) => Ok(value),
40 None => name.with_str(|name| {
41 Err(Error::invalid_number_of_arguments(format!(
42 "{name} argument `{arg_name}` is required"
43 )))
44 }),
45 }
46}
47
48/// The optional counterpart of [`string_arg`]: one declared argument,
49/// absent or null answering `None`, a STRING `Some` — every other type
50/// the one typed rejection. The format's decode stays with its caller.
51pub(crate) fn optional_string_arg(
52 ctx: ExecCtx<'_>,
53 row: &Row,
54 source: &CallArgs,
55 index: usize,
56 arg_name: &str,
57 name: &SmallName,
58) -> Result<Option<String>> {
59 match call_arg_value(&ctx, row, source, index, arg_name)? {
60 None | Some(Value::Null) => Ok(None),
61 Some(Value::String(value)) => Ok(Some(value.to_string())),
62 Some(_) => name.with_str(|name| {
63 Err(Error::invalid_argument_type(format!(
64 "{name} argument `{arg_name}` expects STRING"
65 )))
66 }),
67 }
68}
69
70/// Resolve one declared CALL argument through the call's one passing-mode
71/// value: the explicit positional expression evaluated against the driving
72/// row, or the implicit parameter/row-column value. The one per-argument
73/// resolver the generic binder and the `db.ontology.*` readers share, so
74/// the policy is spelled once.
75pub(crate) fn call_arg_value(
76 ctx: &ExecCtx<'_>,
77 row: &Row,
78 source: &CallArgs,
79 index: usize,
80 arg_name: &str,
81) -> Result<Option<Value>> {
82 match source {
83 CallArgs::Explicit(args) => args
84 .get(index)
85 .map(|expr| crate::eval::eval(ctx.graph, row, expr, ctx.params))
86 .transpose(),
87 CallArgs::Implicit => Ok(ctx
88 .params
89 .get(arg_name)
90 .cloned()
91 .or_else(|| row.get(arg_name).cloned())),
92 }
93}
94
95/// Static shape of a `CALL` clause (name, arguments, yields, optionality).
96#[derive(Clone, Copy)]
97pub(crate) struct CallSpec<'a> {
98 /// The clause's own name, carried as the clause carries it: rendered
99 /// to text through `SmallName::with_str` at the handful of read sites
100 /// (classification, contract errors), never allocated per clause and
101 /// never held by a source — the binding owns its copy in the metadata.
102 pub name: &'a SmallName,
103 /// The call's one passing-mode value — the IR's owned [`CallArgs`],
104 /// lowered once by the front end — borrowed for the call's run, so
105 /// no consumer re-encodes the mode as a bool beside a bare slice.
106 pub source: &'a CallArgs,
107 pub yield_items: &'a YieldItems,
108 pub optional: bool,
109 pub where_clause: Option<&'a Expr>,
110}
111
112impl<'a> CallSpec<'a> {
113 /// The one runtime `CALL` contract every dispatch path reads: the
114 /// implicit-passing-mode backstop, then the arity, over the
115 /// (required, total) pair the call's signature declares — the generic
116 /// registry path passes its resolved pair, the diverted executors the
117 /// classification's own signature's. Every path consults the same two
118 /// predicates through this one method, never a hand-rebuilt arity half
119 /// (stellar round 2, F-2-26). The verdict alone: paths that resolve
120 /// arguments by name (the generic binder, the ontology executor) check
121 /// this and never read a positional slice — the scans read theirs
122 /// through [`Self::check_diverted_positional`].
123 pub(crate) fn check_contract(&self, required: usize, total: usize) -> Result<()> {
124 check_implicit_passing_mode(
125 self.source.is_explicit(),
126 required,
127 self.yield_items.has_yield(),
128 )?;
129 if let CallArgs::Explicit(args) = self.source {
130 self.name
131 .with_str(|name| check_explicit_arity(name, required, total, args.len()))?;
132 }
133 Ok(())
134 }
135
136 /// The positional slice a value-taking executor reads: the explicit
137 /// list, its length the contract validated — or `None` for the
138 /// paren-less form, which by the grammar has no positional list at
139 /// all, its arguments resolving by name (the generic binder's
140 /// missing-name rejection; the facade states the same policy at
141 /// compile time). `None` is the mode's own fact, never an empty
142 /// slice a caller must re-interpret.
143 pub(crate) fn positional(&self) -> Option<&'a [Expr]> {
144 match self.source {
145 CallArgs::Explicit(args) => Some(args),
146 CallArgs::Implicit => None,
147 }
148 }
149
150 /// The diverted-name contract — [`Self::check_contract`] over the
151 /// classification's own signature (the one registry fetch
152 /// [`divert_call`] already made). The `db.ontology.*` divert reads
153 /// this at its resolution site: its executor resolves arguments
154 /// by name, so the paren-less form carries no positional arity
155 /// there (the runtime contract the generic path enforces, from the
156 /// ONE registry signature).
157 pub(crate) fn check_diverted_contract(&self, signature: &ProcSignature) -> Result<()> {
158 self.check_contract(signature.required_args(), signature.args.len())
159 }
160
161 /// The diverted scan executors' contract — the vector and fulltext
162 /// `db.index.*.query*` calls, whose scans read their arguments
163 /// positionally and resolve no names: [`Self::check_diverted_contract`]'s
164 /// pair plus the positional form itself, so a paren-less call —
165 /// which passes no list — answers the arity rejection exactly like
166 /// a short explicit one (`expected 3, got 0`), never a positional
167 /// read off an empty slice (stellar round 2, F-2-43). Answers the
168 /// validated positional slice.
169 pub(crate) fn check_diverted_positional(
170 &self,
171 signature: &ProcSignature,
172 ) -> Result<&'a [Expr]> {
173 // The one pair derivation ([`Self::check_diverted_contract`]), then
174 // the positional form itself: the implicit form is rejected here
175 // directly, not by a fabricated arity — these scan executors read
176 // their arguments positionally and resolve no names, so the
177 // paren-less form can never supply them (the arity rejection over
178 // the empty list the grammar passes, unconditionally).
179 self.check_diverted_contract(signature)?;
180 self.positional().ok_or_else(|| {
181 self.name.with_str(|name| {
182 Error::invalid_number_of_arguments(arity_detail(name, signature.args.len(), 0))
183 })
184 })
185 }
186}
187
188/// The registry-driven explicit-arity check — one half of the runtime
189/// `CALL` contract ([`CallSpec::check_contract`]), which every dispatch
190/// path (the generic registry path, the ontology divert, the vector and
191/// fulltext scans) reads: an explicit call passes between `required`
192/// and `total` arguments. (The facade's compile-time `validate_calls`
193/// already enforces the same contract.)
194pub fn check_explicit_arity(name: &str, required: usize, total: usize, given: usize) -> Result<()> {
195 if given < required || given > total {
196 return Err(Error::invalid_number_of_arguments(arity_detail(
197 name, total, given,
198 )));
199 }
200 Ok(())
201}
202
203/// The one spelling of the arity rejection's detail — read by the explicit
204/// check and by the diverted scans' paren-less rejection, so the two can
205/// never drift.
206fn arity_detail(name: &str, total: usize, given: usize) -> String {
207 format!("{name} expected {total}, got {given}")
208}
209
210/// The passing-mode backstop — the other half of the runtime `CALL`
211/// contract ([`CallSpec::check_contract`]): an in-query implicit
212/// call — a `CALL` with a YIELD, in a clause pipeline — cannot pass
213/// arguments; the procedure's arguments resolve only in a standalone unit
214/// call. `required_args` is the caller's registry truth: the number of
215/// declared parameters *without a default* (LABS-389: a procedure whose
216/// parameters all carry defaults is callable implicitly). (The facade's
217/// compile-time `validate_calls` enforces the same contract before
218/// execution; this is the executor-side backstop.)
219pub fn check_implicit_passing_mode(
220 explicit: bool,
221 required_args: usize,
222 has_yield: bool,
223) -> Result<()> {
224 if !explicit && required_args > 0 && has_yield {
225 return Err(Error::syntax(
226 "InvalidArgumentPassingMode: in-query CALL cannot pass arguments implicitly",
227 ));
228 }
229 Ok(())
230}
231
232/// The void-procedure policy in one spelling: an OPTIONAL call with no
233/// return columns over no input rows pads one unit row (its own row,
234/// answered as data); over rows, the per-row handler runs. The pad and
235/// the handler are independent — the loop is empty-safe exactly when the
236/// pad fires — so nothing guards one with the other.
237pub(crate) fn pad_or_each(
238 rows: &[Row],
239 optional: bool,
240 mut each: impl FnMut(&Row) -> Result<()>,
241) -> Result<Option<Row>> {
242 let pad = (rows.is_empty() && optional).then(Row::new);
243 for row in rows {
244 each(row)?;
245 }
246 Ok(pad)
247}