Skip to main content

bynk_ts/
predicate.rs

1//! The `PredKind` → TypeScript runtime-check mapping and the TypeScript string-literal
2//! escaper it depends on. Moved here from `bynk-emit`'s `emitter` (crate-hygiene A2,
3//! `design/archive/retired-tracks.md` §5) so the language server can build the same
4//! condition without depending on the emitter; behaviour is unchanged.
5
6use crate::program::{TsBinaryOp, TsExpr, TsLit};
7use bynk_syntax::ast::{BaseType, PredKind};
8
9/// Escapes a string for embedding in a TypeScript double-quoted string literal.
10/// The one definition: the printer's `TsLit::Str`, `bynk-emit`'s `escape_ts_string`
11/// and `bynk-check`'s wire defaults all splice into generated TypeScript and must
12/// never disagree.
13pub fn escape_ts_literal(s: &str) -> String {
14    let mut out = String::with_capacity(s.len());
15    for c in s.chars() {
16        match c {
17            '\\' => out.push_str("\\\\"),
18            '"' => out.push_str("\\\""),
19            '\n' => out.push_str("\\n"),
20            '\t' => out.push_str("\\t"),
21            '\r' => out.push_str("\\r"),
22            // #2619: `\0`, other control characters and the JS line terminators
23            // U+2028/U+2029 print as `\u{…}` escapes (valid in strings and templates).
24            c if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') => {
25                out.push_str(&format!("\\u{{{:X}}}", c as u32));
26            }
27            c => out.push(c),
28        }
29    }
30    out
31}
32
33/// #2622: a coefficient as a signed `bigint` literal body: no leading zeros
34/// (`007n` is not valid TypeScript) and no negative zero.
35pub fn decimal_signed_coef(coef: &str) -> String {
36    let (neg, mag) = match coef.strip_prefix('-') {
37        Some(rest) => (true, rest),
38        None => (false, coef),
39    };
40    let mag = mag.trim_start_matches('0');
41    let mag = if mag.is_empty() { "0" } else { mag };
42    let sign = if neg && mag != "0" { "-" } else { "" };
43    format!("{sign}{mag}")
44}
45
46/// #661 (Decision D)/#70 review: the one `PredKind` → runtime-check mapping,
47/// shared by the owner-side check (`emit::emit_pred_check`, over a `value`
48/// binding) and the boundary-side inline check
49/// (`serialisation::emit_inline_pred_check`, over a `json` binding) — the
50/// two used to hand-roll this mapping independently, pinned identical only by
51/// a comment, so amending one (e.g. the `Matches` regex's `^(?:…)$` anchoring)
52/// could silently drift from the other. `receiver` is the bound name the
53/// generated condition reads (`value` or `json`); the returned message is the
54/// same either side of the boundary by construction.
55///
56/// #1471: `cond` is a real [`crate::TsExpr`], not opaque text — the
57/// blocker (`crate::TsBinaryOp` had no `>=`/`<=`) is resolved by that
58/// enum's own new `GreaterThanEq`/`LessThanEq` variants. Both real callers
59/// wrap the returned expression in their own `Unary::Not`/`Paren` unchanged;
60/// only this function's own arms changed, from `format!`ing condition text
61/// to building the equivalent node tree.
62///
63/// Review of #1336: both real callers (`emit::emit_pred_check`,
64/// `serialisation::emit_inline_pred_check`) splice the returned `message`
65/// straight into a TypeScript string literal **unescaped** — safe today only
66/// because every arm's own message is either static English text or already
67/// `escape_ts_literal`-escaped (the `Matches` arm's own pattern). A future arm
68/// returning raw, unescaped text (a predicate carrying a user-supplied string
69/// operand, say) would emit a malformed or injectable literal at both call
70/// sites, and nothing in the existing fixture corpus would catch it. This
71/// invariant must match at every arm added here, not just the ones that exist
72/// today — return plain text or already-`escape_ts_literal`-escaped text only.
73/// `msg` stays exactly this opaque `String`, unchanged by #1471: only the
74/// `cond` side of the pair became a real node (see the `Matches` arm below
75/// for why the message keeps its own already-escaped copy of the pattern
76/// separate from the condition's raw, unescaped one).
77pub fn pred_condition_and_message(pred: &PredKind, receiver: &str) -> (crate::TsExpr, String) {
78    pred_condition_and_message_for(pred, receiver, None)
79}
80
81/// #2622: the condition a `Decimal` value must satisfy for `pred`, over the
82/// `{ coefficient, scale }` object (no runtime import). #2955: built as a real
83/// [`TsExpr`] like every other arm (#1471), not `format!`-ed text; the explicit
84/// [`TsExpr::Paren`]s reproduce the pre-#2955 text byte for byte.
85fn decimal_pred_condition(pred: &PredKind, recv: &TsExpr) -> Option<(TsExpr, String)> {
86    let coefficient = || decimal_member(recv, "coefficient");
87    match pred {
88        PredKind::NonNegative => Some((
89            binary(TsBinaryOp::GreaterThanEq, coefficient(), bigint("0")),
90            "must be non-negative".to_string(),
91        )),
92        PredKind::Positive => Some((
93            binary(TsBinaryOp::GreaterThan, coefficient(), bigint("0")),
94            "must be positive".to_string(),
95        )),
96        PredKind::InRangeD(a, b) => Some((
97            decimal_range_expr(recv, a, b),
98            format!(
99                "must be in range [{}, {}]",
100                bynk_syntax::decimal::render(&a.coef, a.scale),
101                bynk_syntax::decimal::render(&b.coef, b.scale)
102            ),
103        )),
104        PredKind::Matches(_)
105        | PredKind::InRange(..)
106        | PredKind::InRangeF(..)
107        | PredKind::MinLength(_)
108        | PredKind::MaxLength(_)
109        | PredKind::Length(_)
110        | PredKind::NonEmpty
111        | PredKind::IsoDate
112        | PredKind::Cron => None,
113    }
114}
115
116fn binary(op: TsBinaryOp, left: TsExpr, right: TsExpr) -> TsExpr {
117    TsExpr::Binary {
118        op,
119        left: Box::new(left),
120        right: Box::new(right),
121    }
122}
123
124fn paren(e: TsExpr) -> TsExpr {
125    TsExpr::Paren(Box::new(e))
126}
127
128/// A `bigint` literal: `digits` plus the `n` suffix.
129fn bigint(digits: &str) -> TsExpr {
130    TsExpr::bigint(digits)
131}
132
133/// `(recv).property`.
134fn decimal_member(recv: &TsExpr, property: &str) -> TsExpr {
135    TsExpr::Member {
136        object: Box::new(paren(recv.clone())),
137        property: property.to_string(),
138    }
139}
140
141/// `10n ** globalThis.BigInt(exponent)`.
142fn pow10(exponent: TsExpr) -> TsExpr {
143    binary(
144        TsBinaryOp::Exp,
145        bigint("10"),
146        TsExpr::Call {
147            callee: Box::new(TsExpr::Ident("globalThis.BigInt".to_string())),
148            args: vec![exponent],
149        },
150    )
151}
152
153/// `lo <= recv <= hi` over `Decimal` objects, comparing at a common scale with
154/// `bigint` arithmetic so the check needs no helper import.
155fn decimal_range_expr(
156    recv: &TsExpr,
157    lo: &bynk_syntax::ast::DecimalBound,
158    hi: &bynk_syntax::ast::DecimalBound,
159) -> TsExpr {
160    let bound = |op, b: &bynk_syntax::ast::DecimalBound| {
161        let scaled_recv = binary(
162            TsBinaryOp::Mul,
163            decimal_member(recv, "coefficient"),
164            pow10(TsExpr::Lit(TsLit::Num(b.scale.to_string()))),
165        );
166        let scaled_bound = binary(
167            TsBinaryOp::Mul,
168            paren(bigint(&decimal_signed_coef(&b.coef))),
169            pow10(decimal_member(recv, "scale")),
170        );
171        paren(binary(op, scaled_recv, scaled_bound))
172    };
173    paren(binary(
174        TsBinaryOp::And,
175        bound(TsBinaryOp::GreaterThanEq, lo),
176        bound(TsBinaryOp::LessThanEq, hi),
177    ))
178}
179
180/// The `Decimal` range check as printed text — for `bynk-emit`'s `lower.rs`, which still
181/// assembles its refinement guard from text.
182pub fn decimal_range_condition(
183    recv: &str,
184    lo: &bynk_syntax::ast::DecimalBound,
185    hi: &bynk_syntax::ast::DecimalBound,
186) -> String {
187    crate::print_expr(&decimal_range_expr(
188        &TsExpr::Ident(recv.to_string()),
189        lo,
190        hi,
191    ))
192}
193
194/// [`pred_condition_and_message`] knowing the receiver's base type: a
195/// `Decimal` is an object, so its numeric predicates are not `recv > 0`.
196pub fn pred_condition_and_message_for(
197    pred: &PredKind,
198    receiver: &str,
199    base: Option<BaseType>,
200) -> (crate::TsExpr, String) {
201    pred_condition_and_message_over(pred, &TsExpr::Ident(receiver.to_string()), base)
202}
203
204/// [`pred_condition_and_message_for`] over a receiver that is itself an expression
205/// (a field read, an indexed element, a temporary), not just a name.
206pub fn pred_condition_and_message_over(
207    pred: &PredKind,
208    receiver: &TsExpr,
209    base: Option<BaseType>,
210) -> (crate::TsExpr, String) {
211    if (base == Some(BaseType::Decimal) || matches!(pred, PredKind::InRangeD(..)))
212        && let Some((cond, msg)) = decimal_pred_condition(pred, receiver)
213    {
214        return (cond, msg);
215    }
216
217    let recv = || receiver.clone();
218    // #3949: a `String` predicate counts code points, as the compile-time check
219    // and OpenAPI's `maxLength` do, not UTF-16 code units (`.length`).
220    let recv_length = || TsExpr::Call {
221        callee: Box::new(TsExpr::Ident("__bynkCodePointLength".to_string())),
222        args: vec![recv()],
223    };
224    let num = |n: String| TsExpr::Lit(TsLit::Num(n));
225    let cmp = |op, left, right| TsExpr::Binary {
226        op,
227        left: Box::new(left),
228        right: Box::new(right),
229    };
230
231    match pred {
232        PredKind::NonNegative => (
233            cmp(TsBinaryOp::GreaterThanEq, recv(), num("0".to_string())),
234            "must be non-negative".to_string(),
235        ),
236        PredKind::Positive => (
237            cmp(TsBinaryOp::GreaterThan, recv(), num("0".to_string())),
238            "must be positive".to_string(),
239        ),
240        PredKind::InRange(a, b) => {
241            let (a, b) = (a.value, b.value);
242            (
243                cmp(
244                    TsBinaryOp::And,
245                    cmp(TsBinaryOp::GreaterThanEq, recv(), num(a.to_string())),
246                    cmp(TsBinaryOp::LessThanEq, recv(), num(b.to_string())),
247                ),
248                format!("must be in range [{a}, {b}]"),
249            )
250        }
251        PredKind::InRangeF(a, b) => {
252            let (a, b) = (&a.lexeme, &b.lexeme);
253            (
254                cmp(
255                    TsBinaryOp::And,
256                    cmp(TsBinaryOp::GreaterThanEq, recv(), num(a.clone())),
257                    cmp(TsBinaryOp::LessThanEq, recv(), num(b.clone())),
258                ),
259                format!("must be in range [{a}, {b}]"),
260            )
261        }
262        // Handled above (a `Decimal` base); not reachable for another base.
263        PredKind::InRangeD(..) => unreachable!("decimal predicates return early"),
264        PredKind::NonEmpty => (
265            cmp(TsBinaryOp::GreaterThan, recv_length(), num("0".to_string())),
266            "must be non-empty".to_string(),
267        ),
268        // #2867: the runtime helper owns the calendar; callers `note_predicate`.
269        PredKind::IsoDate => (
270            TsExpr::Call {
271                callee: Box::new(TsExpr::Ident("__bynkIsIsoDate".to_string())),
272                args: vec![recv()],
273            },
274            "must be a calendar date (YYYY-MM-DD)".to_string(),
275        ),
276        // #3873: the runtime helper owns the schedule grammar; callers `note_predicate`.
277        PredKind::Cron => (
278            TsExpr::Call {
279                callee: Box::new(TsExpr::Ident("__bynkIsCron".to_string())),
280                args: vec![recv()],
281            },
282            "must be a valid cron schedule".to_string(),
283        ),
284        PredKind::MinLength(n) => (
285            cmp(TsBinaryOp::GreaterThanEq, recv_length(), num(n.to_string())),
286            format!("length must be at least {n}"),
287        ),
288        PredKind::MaxLength(n) => (
289            cmp(TsBinaryOp::LessThanEq, recv_length(), num(n.to_string())),
290            format!("length must be at most {n}"),
291        ),
292        PredKind::Length(n) => (
293            cmp(TsBinaryOp::StrictEq, recv_length(), num(n.to_string())),
294            format!("length must be exactly {n}"),
295        ),
296        PredKind::Matches(pat) => {
297            // The condition's own `RegExp` source uses `pat` raw, not
298            // `escaped` — `TsLit::Str`'s printer already applies the exact
299            // same escaping as `escape_ts_literal`
300            // (`bynk_check::wire_default::escape_ts_literal`, kept
301            // deliberately identical — see `bynk-ts/src/printer.rs`'s own
302            // `render_lit`), so escaping `pat` here too would double-escape
303            // it, same bug class `msg`'s own doc above already argues
304            // against. `escaped` is still needed for `msg`, which is opaque
305            // text spliced with no further escaping.
306            let escaped = escape_ts_literal(pat);
307            let pattern = cmp(
308                TsBinaryOp::Add,
309                cmp(
310                    TsBinaryOp::Add,
311                    TsExpr::Lit(TsLit::Str("^(?:".to_string())),
312                    TsExpr::Lit(TsLit::Str(pat.clone())),
313                ),
314                TsExpr::Lit(TsLit::Str(")$".to_string())),
315            );
316            let regexp = TsExpr::New {
317                callee: Box::new(TsExpr::Ident("globalThis.RegExp".to_string())),
318                args: vec![pattern],
319            };
320            let test_call = TsExpr::Call {
321                callee: Box::new(TsExpr::Member {
322                    object: Box::new(regexp),
323                    property: "test".to_string(),
324                }),
325                args: vec![recv()],
326            };
327            (test_call, format!("must match /{escaped}/"))
328        }
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::{
335        decimal_range_condition, decimal_signed_coef, pred_condition_and_message_for,
336        pred_condition_and_message_over,
337    };
338    use bynk_syntax::ast::{BaseType, DecimalBound, PredKind};
339    use bynk_syntax::span::Span;
340
341    fn bound(coef: &str, scale: u32) -> DecimalBound {
342        DecimalBound {
343            coef: coef.to_string(),
344            scale,
345            lexeme: String::new(),
346            span: Span::new(0, 0),
347        }
348    }
349
350    /// #2955: the text the `Decimal` arms `format!`-ed before they became
351    /// `TsExpr` nodes — kept as the oracle so the node tree stays byte-identical.
352    fn legacy_range(recv: &str, lo: &DecimalBound, hi: &DecimalBound) -> String {
353        let bound = |op: &str, b: &DecimalBound| {
354            let coef = decimal_signed_coef(&b.coef);
355            format!(
356                "(({recv}).coefficient * 10n ** globalThis.BigInt({}) {op} ({coef}n) * 10n ** globalThis.BigInt(({recv}).scale))",
357                b.scale
358            )
359        };
360        format!("({} && {})", bound(">=", lo), bound("<=", hi))
361    }
362
363    fn decimal_cond(pred: &PredKind, recv: &str) -> String {
364        let (cond, _) = pred_condition_and_message_for(pred, recv, Some(BaseType::Decimal));
365        crate::print_expr(&cond)
366    }
367
368    #[test]
369    fn decimal_sign_predicates_print_the_legacy_text() {
370        for recv in ["value", "json", "__v"] {
371            assert_eq!(
372                decimal_cond(&PredKind::NonNegative, recv),
373                format!("({recv}).coefficient >= 0n")
374            );
375            assert_eq!(
376                decimal_cond(&PredKind::Positive, recv),
377                format!("({recv}).coefficient > 0n")
378            );
379        }
380        // A receiver that is an expression, not a name, goes through
381        // `pred_condition_and_message_over` (an `Ident` holds an identifier path only).
382        let indexed = crate::TsExpr::Index {
383            object: Box::new(crate::TsExpr::Ident("json".to_string())),
384            index: Box::new(crate::TsExpr::Lit(crate::program::TsLit::Str(
385                "amount".to_string(),
386            ))),
387        };
388        let (cond, _) = pred_condition_and_message_over(
389            &PredKind::NonNegative,
390            &indexed,
391            Some(BaseType::Decimal),
392        );
393        assert_eq!(
394            crate::print_expr(&cond),
395            "(json[\"amount\"]).coefficient >= 0n"
396        );
397    }
398
399    #[test]
400    fn decimal_range_prints_the_legacy_text() {
401        let cases = [
402            (bound("0", 0), bound("100", 0)),
403            (bound("-12", 2), bound("007", 1)),
404            (bound("-0", 3), bound("-000", 0)),
405            (bound("-1999", 3), bound("25", 5)),
406        ];
407        for recv in ["value", "json", "__v"] {
408            for (lo, hi) in &cases {
409                let want = legacy_range(recv, lo, hi);
410                assert_eq!(decimal_range_condition(recv, lo, hi), want);
411                let pred = PredKind::InRangeD(lo.clone(), hi.clone());
412                assert_eq!(decimal_cond(&pred, recv), want);
413                // `InRangeD` takes the `Decimal` path even with no base given.
414                let (cond, _) = pred_condition_and_message_for(&pred, recv, None);
415                assert_eq!(crate::print_expr(&cond), want);
416            }
417        }
418    }
419
420    #[test]
421    fn decimal_coefficients_drop_leading_zeros_and_negative_zero() {
422        assert_eq!(decimal_signed_coef("007"), "7");
423        assert_eq!(decimal_signed_coef("-0"), "0");
424        assert_eq!(decimal_signed_coef("-000"), "0");
425        assert_eq!(decimal_signed_coef("-12"), "-12");
426        assert_eq!(decimal_signed_coef("0"), "0");
427    }
428
429    /// A receiver that is itself an expression is used as it stands: a name, a member read
430    /// and a call all give the same condition as the text form over the same text.
431    #[test]
432    fn a_receiver_expression_gives_the_same_condition_as_its_text() {
433        use crate::{TsExpr, print_expr};
434        let member = TsExpr::Member {
435            object: Box::new(TsExpr::Ident("a".to_string())),
436            property: "b".to_string(),
437        };
438        for pred in [
439            PredKind::NonNegative,
440            PredKind::NonEmpty,
441            PredKind::MinLength(2),
442            PredKind::IsoDate,
443        ] {
444            let (over, over_msg) = pred_condition_and_message_over(&pred, &member, None);
445            let (text, text_msg) = pred_condition_and_message_for(&pred, "a.b", None);
446            assert_eq!(print_expr(&over), print_expr(&text), "{pred:?}");
447            assert_eq!(over_msg, text_msg);
448        }
449        let (decimal, _) =
450            pred_condition_and_message_over(&PredKind::Positive, &member, Some(BaseType::Decimal));
451        assert_eq!(print_expr(&decimal), "(a.b).coefficient > 0n");
452    }
453}