1use crate::program::{TsBinaryOp, TsExpr, TsLit};
7use bynk_syntax::ast::{BaseType, PredKind};
8
9pub 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 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
33pub 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
46pub fn pred_condition_and_message(pred: &PredKind, receiver: &str) -> (crate::TsExpr, String) {
78 pred_condition_and_message_for(pred, receiver, None)
79}
80
81fn 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
128fn bigint(digits: &str) -> TsExpr {
130 TsExpr::bigint(digits)
131}
132
133fn 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
141fn 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
153fn 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
180pub 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
194pub 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
204pub 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 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 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 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 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 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 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 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 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 #[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}