1use std::collections::HashSet;
37
38use bynk_syntax::ast::{
39 BaseType, CommonsItem, PredKind, Refinement, SourceUnit, TypeBody, TypeDecl,
40};
41use bynk_syntax::lexer::tokenize;
42use bynk_syntax::parser::parse_unit_with_recovery;
43use tower_lsp::lsp_types::{Position, TextDocumentIdentifier};
44
45pub const EXPLORE_COMMAND: &str = "bynk.exploreRefinedType";
48
49pub const CLIENT_CAPABILITY: &str = "refinedTypeExplorerCommand";
52
53pub const SEED: u32 = 0x2470;
55
56const MAX_EXAMPLES: usize = 6;
58
59const MAX_EXAMPLE_LEN: i64 = 256;
61
62#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
64#[serde(rename_all = "camelCase")]
65pub struct RefinedParams {
66 pub text_document: TextDocumentIdentifier,
67 pub position: Position,
68}
69
70#[derive(Debug, Clone, PartialEq, serde::Serialize)]
72pub struct Clause {
73 pub source: String,
75 pub description: String,
77 pub predicate: Predicate,
79 pub check: String,
82 pub message: String,
84}
85
86#[derive(Debug, Clone, PartialEq, serde::Serialize)]
94#[serde(tag = "kind", rename_all = "camelCase")]
95pub enum Predicate {
96 NonNegative,
98 Positive,
100 Range { min: Bound, max: Bound },
102 NonEmpty,
104 MinLength { length: i64 },
106 MaxLength { length: i64 },
108 Length { length: i64 },
110 Matches { pattern: String },
112 IsoDate,
114 Cron,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
122#[serde(untagged)]
123pub enum Bound {
124 Int(i64),
125 Float(f64),
126}
127
128impl Predicate {
129 fn of(kind: &PredKind) -> Self {
130 match kind {
131 PredKind::NonNegative => Predicate::NonNegative,
132 PredKind::Positive => Predicate::Positive,
133 PredKind::InRange(a, b) => Predicate::Range {
134 min: Bound::Int(a.value),
135 max: Bound::Int(b.value),
136 },
137 PredKind::InRangeF(a, b) => Predicate::Range {
138 min: Bound::Float(a.value),
139 max: Bound::Float(b.value),
140 },
141 PredKind::InRangeD(a, b) => Predicate::Range {
144 min: Bound::Float(a.lexeme.trim_end_matches('d').parse().unwrap_or(0.0)),
145 max: Bound::Float(b.lexeme.trim_end_matches('d').parse().unwrap_or(0.0)),
146 },
147 PredKind::NonEmpty => Predicate::NonEmpty,
148 PredKind::MinLength(n) => Predicate::MinLength { length: *n },
149 PredKind::MaxLength(n) => Predicate::MaxLength { length: *n },
150 PredKind::Length(n) => Predicate::Length { length: *n },
151 PredKind::Matches(p) => Predicate::Matches { pattern: p.clone() },
152 PredKind::IsoDate => Predicate::IsoDate,
153 PredKind::Cron => Predicate::Cron,
154 }
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, serde::Serialize)]
160#[serde(rename_all = "camelCase")]
161pub struct RefinedModel {
162 pub name: String,
163 pub base: &'static str,
165 pub opaque: bool,
166 pub declaration: String,
168 pub clauses: Vec<Clause>,
170 pub examples: Vec<String>,
172 pub examples_note: Option<String>,
174 pub seed: u32,
175}
176
177pub fn find_type_decl(source: &str, name: &str) -> Option<TypeDecl> {
179 let tokens = tokenize(source).ok()?;
180 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
181 let items: &[CommonsItem] = match unit.as_ref()? {
182 SourceUnit::Commons(c) => &c.items,
183 SourceUnit::Context(c) => &c.items,
184 SourceUnit::Adapter(a) => &a.items,
185 SourceUnit::Suite(_) => &[],
186 };
187 items.iter().find_map(|item| match item {
188 CommonsItem::Type(t) if t.name.name == name => Some(t.clone()),
189 _ => None,
190 })
191}
192
193pub fn model_for(decl: &TypeDecl, with_examples: bool) -> Option<RefinedModel> {
198 let (base, refinement, opaque) = match &decl.body {
199 TypeBody::Refined {
200 base,
201 refinement: Some(r),
202 ..
203 } => (*base, r, false),
204 TypeBody::Opaque {
205 base,
206 refinement: Some(r),
207 ..
208 } => (*base, r, true),
209 _ => return None,
210 };
211 let base_name = match base {
212 BaseType::Int => "Int",
213 BaseType::Float => "Float",
214 BaseType::String => "String",
215 _ => return None,
216 };
217 if refinement.predicates.is_empty() {
218 return None;
219 }
220 let clauses = bynk_syntax::ast::in_check_order(&refinement.predicates, |p| &p.kind)
221 .into_iter()
222 .map(|p| clause(&p.kind))
223 .collect();
224 let (examples, examples_note) = if with_examples {
225 examples(base, refinement)
226 } else {
227 (Vec::new(), None)
228 };
229 Some(RefinedModel {
230 name: decl.name.name.clone(),
231 base: base_name,
232 opaque,
233 declaration: format!(
234 "type {} = {}{} where {}",
235 decl.name.name,
236 if opaque { "opaque " } else { "" },
237 base_name,
238 bynk_fmt::refinement_to_string(refinement)
239 ),
240 clauses,
241 examples,
242 examples_note,
243 seed: SEED,
244 })
245}
246
247fn clause(kind: &PredKind) -> Clause {
248 let (cond, message) = bynk_ts::pred_condition_and_message(kind, "value");
249 let description = match kind {
250 PredKind::NonNegative => "value ≥ 0".to_string(),
251 PredKind::Positive => "value > 0".to_string(),
252 PredKind::InRange(a, b) => format!("{} ≤ value ≤ {}", a.value, b.value),
253 PredKind::InRangeF(a, b) => format!("{} ≤ value ≤ {}", a.lexeme, b.lexeme),
254 PredKind::InRangeD(a, b) => format!("{} ≤ value ≤ {}", a.lexeme, b.lexeme),
255 PredKind::NonEmpty => "length ≥ 1".to_string(),
256 PredKind::MinLength(n) => format!("length ≥ {n}"),
257 PredKind::MaxLength(n) => format!("length ≤ {n}"),
258 PredKind::Length(n) => format!("length = {n}"),
259 PredKind::Matches(re) => format!("the whole string matches /{re}/"),
260 PredKind::IsoDate => "a calendar date, YYYY-MM-DD".to_string(),
261 PredKind::Cron => {
262 "a cron schedule: five fields, minute hour day-of-month month day-of-week".to_string()
263 }
264 };
265 Clause {
266 source: bynk_fmt::refinement_to_string(&Refinement {
267 predicates: vec![bynk_syntax::ast::RefinementPred {
268 kind: kind.clone(),
269 arg_text: None,
270 span: bynk_syntax::span::Span::default(),
271 }],
272 annotations: Vec::new(),
273 span: bynk_syntax::span::Span::default(),
274 }),
275 description,
276 predicate: Predicate::of(kind),
277 check: bynk_ts::print_expr(&cond)
280 .replace("__bynkCodePointLength(value)", "Array.from(value).length"),
281 message,
282 }
283}
284
285pub fn hover_section(model: &RefinedModel) -> String {
287 let mut out = format!(
288 "**{}** over `{}` — a value is valid when:\n",
289 if model.opaque {
290 "Opaque refined type"
291 } else {
292 "Refined type"
293 },
294 model.base
295 );
296 for c in &model.clauses {
297 out.push_str(&format!("\n- `{}` — {}", c.source, c.description));
298 }
299 out
300}
301
302pub fn hover_link(uri: &str, position: Position) -> String {
304 let args = serde_json::json!([uri, { "line": position.line, "character": position.character }]);
305 let mut enc = String::new();
306 for b in args.to_string().bytes() {
307 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
308 enc.push(b as char);
309 } else {
310 enc.push_str(&format!("%{b:02X}"));
311 }
312 }
313 format!("[Try values…](command:{EXPLORE_COMMAND}?{enc})")
314}
315
316pub fn client_supports_explorer_command(experimental: Option<&serde_json::Value>) -> bool {
318 experimental
319 .and_then(|v| v.get(CLIENT_CAPABILITY))
320 .and_then(serde_json::Value::as_bool)
321 .unwrap_or(false)
322}
323
324struct Rng(u32);
329
330impl Rng {
331 fn next(&mut self) -> f64 {
332 self.0 = self.0.wrapping_add(0x6d2b_79f5);
333 let mut t = self.0;
334 t = (t ^ (t >> 15)).wrapping_mul(t | 1);
335 t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(t | 61));
336 f64::from(t ^ (t >> 14)) / 4_294_967_296.0
337 }
338
339 fn int(&mut self, lo: i128, hi: i128) -> i128 {
340 if hi <= lo {
341 return lo;
342 }
343 let span = hi - lo + 1;
344 let mut r: i128 = 0;
345 let mut bound = span;
346 while bound > 0 {
347 r = (r << 32) | (self.next() * 4_294_967_296.0).floor() as i128;
348 bound >>= 32;
349 }
350 lo + r.rem_euclid(span)
351 }
352
353 fn string(&mut self, len: usize) -> String {
354 (0..len)
355 .map(|_| (b'a' + (self.next() * 26.0).floor() as u8) as char)
356 .collect()
357 }
358}
359
360fn examples(base: BaseType, r: &Refinement) -> (Vec<String>, Option<String>) {
361 let mut rng = Rng(SEED);
362 let mut seen = HashSet::new();
363 let mut out: Vec<String> = Vec::new();
364 let mut push = |s: String, out: &mut Vec<String>| {
365 if out.len() < MAX_EXAMPLES && seen.insert(s.clone()) {
366 out.push(s);
367 }
368 };
369 let preds = r.predicates.iter().map(|p| &p.kind);
370 match base {
371 BaseType::Int => {
372 let (mut lower, mut upper): (Option<i64>, Option<i64>) = (None, None);
373 for k in preds {
374 let (l, u) = match k {
375 PredKind::Positive => (Some(1), None),
376 PredKind::NonNegative => (Some(0), None),
377 PredKind::InRange(a, b) => (Some(a.value), Some(b.value)),
378 _ => continue,
379 };
380 lower = lower.max(l);
381 upper = match (upper, u) {
382 (Some(x), Some(y)) => Some(x.min(y)),
383 (x, y) => x.or(y),
384 };
385 }
386 let lo = lower.unwrap_or_else(|| (-1000).min(upper.unwrap_or(1000)));
387 let hi = upper.unwrap_or_else(|| 1000.max(lo));
388 if lo > hi {
389 return (out, Some("No integer satisfies every clause.".to_string()));
390 }
391 push(lo.to_string(), &mut out);
392 push(hi.to_string(), &mut out);
393 for _ in 0..64 {
394 if out.len() >= MAX_EXAMPLES {
395 break;
396 }
397 push(
398 rng.int(i128::from(lo), i128::from(hi)).to_string(),
399 &mut out,
400 );
401 }
402 (out, None)
403 }
404 BaseType::Float => {
405 let (mut lower, mut upper): (Option<f64>, Option<f64>) = (None, None);
406 let mut positive = false;
407 for k in preds {
408 let (l, u) = match k {
409 PredKind::Positive => {
410 positive = true;
411 (Some(0.0), None)
412 }
413 PredKind::NonNegative => (Some(0.0), None),
414 PredKind::InRangeF(a, b) => (Some(a.value), Some(b.value)),
415 _ => continue,
416 };
417 lower = match (lower, l) {
418 (Some(x), Some(y)) => Some(x.max(y)),
419 (x, y) => x.or(y),
420 };
421 upper = match (upper, u) {
422 (Some(x), Some(y)) => Some(x.min(y)),
423 (x, y) => x.or(y),
424 };
425 }
426 let lo = lower.unwrap_or_else(|| (-1000.0f64).min(upper.unwrap_or(1000.0)));
427 let hi = upper.unwrap_or_else(|| 1000.0f64.max(lo));
428 let admits = |v: f64| !positive || v > 0.0;
430 if lo > hi || !admits(hi) {
431 return (out, Some("No number satisfies every clause.".to_string()));
432 }
433 for v in [lo, hi] {
434 if admits(v) {
435 push(format!("{v}"), &mut out);
436 }
437 }
438 for _ in 0..64 {
439 if out.len() >= MAX_EXAMPLES {
440 break;
441 }
442 let v = lo + rng.next() * (hi - lo);
443 let v = ((v * 100.0).round() / 100.0).clamp(lo, hi);
444 if admits(v) {
445 push(format!("{v}"), &mut out);
446 }
447 }
448 (out, None)
449 }
450 BaseType::String => {
451 let (mut min, mut max): (i64, Option<i64>) = (0, None);
452 let mut pattern: Option<&str> = None;
453 if preds.clone().any(|k| matches!(k, PredKind::IsoDate)) {
455 let re = preds
456 .clone()
457 .find_map(|k| match k {
458 PredKind::Matches(p) => Some(p),
459 _ => None,
460 })
461 .and_then(|p| regress::Regex::new(&format!("^(?:{p})$")).ok());
462 for d in ["2026-11-03", "2028-02-29", "2000-02-29"] {
463 if re.as_ref().is_none_or(|re| re.find(d).is_some()) {
464 push(d.to_string(), &mut out);
465 }
466 }
467 let note = out.is_empty().then(|| {
468 "No sample date satisfies every clause; type a candidate below.".to_string()
469 });
470 return (out, note);
471 }
472 if preds.clone().any(|k| matches!(k, PredKind::Cron)) {
474 let re = preds
475 .clone()
476 .find_map(|k| match k {
477 PredKind::Matches(p) => Some(p),
478 _ => None,
479 })
480 .and_then(|p| regress::Regex::new(&format!("^(?:{p})$")).ok());
481 for d in ["0 2 * * MON-FRI", "*/15 * * * *", "0 0 1 JAN *"] {
482 if re.as_ref().is_none_or(|re| re.find(d).is_some()) {
483 push(d.to_string(), &mut out);
484 }
485 }
486 let note = out.is_empty().then(|| {
487 "No sample schedule satisfies every clause; type a candidate below.".to_string()
488 });
489 return (out, note);
490 }
491 for k in preds {
492 match k {
493 PredKind::NonEmpty => min = min.max(1),
494 PredKind::MinLength(n) => min = min.max(*n),
495 PredKind::MaxLength(n) => max = Some(max.map_or(*n, |m| m.min(*n))),
496 PredKind::Length(n) => {
497 min = min.max(*n);
498 max = Some(max.map_or(*n, |m| m.min(*n)));
499 }
500 PredKind::Matches(p) => pattern = Some(p),
501 _ => {}
502 }
503 }
504 let hi = max.unwrap_or(min + 8).min(min + 8);
505 if min > hi {
506 return (out, Some("No string satisfies every clause.".to_string()));
507 }
508 if min > MAX_EXAMPLE_LEN {
509 return (
510 out,
511 Some(format!(
512 "Every valid string is longer than {MAX_EXAMPLE_LEN} characters, too long to list."
513 )),
514 );
515 }
516 let re = pattern.and_then(|p| regress::Regex::new(&format!("^(?:{p})$")).ok());
517 let ok = |s: &str| re.as_ref().is_none_or(|re| re.find(s).is_some());
518 let mut try_push = |len: i64, out: &mut Vec<String>, rng: &mut Rng| {
519 let s = rng.string(len as usize);
520 if ok(&s) {
521 push(s, out);
522 }
523 };
524 try_push(min, &mut out, &mut rng);
525 try_push(hi, &mut out, &mut rng);
526 for _ in 0..64 {
527 if out.len() >= MAX_EXAMPLES {
528 break;
529 }
530 let len = min + (rng.next() * ((hi - min + 1) as f64)).floor() as i64;
531 try_push(len, &mut out, &mut rng);
532 }
533 let note = (pattern.is_some() && out.is_empty()).then(|| {
534 "`Val[T]` has no generator for a `Matches` type (`bynk.val.needs_pin`); type a candidate below.".to_string()
535 });
536 (out, note)
537 }
538 _ => (out, None),
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545
546 fn model(src: &str, name: &str) -> RefinedModel {
547 let decl = find_type_decl(src, name).expect("declaration");
548 model_for(&decl, true).expect("model")
549 }
550
551 fn checks(m: &RefinedModel) -> Vec<&str> {
552 m.clauses.iter().map(|c| c.check.as_str()).collect()
553 }
554
555 #[test]
556 fn int_range_lists_boundaries_first_and_is_stable() {
557 let src = "commons demo\n\ntype Quantity = Int where InRange(1, 100)\n";
558 let m = model(src, "Quantity");
559 assert_eq!(m.base, "Int");
560 assert_eq!(m.examples[..2], ["1".to_string(), "100".to_string()]);
561 assert_eq!(
562 m,
563 model(src, "Quantity"),
564 "a fixed seed: the same list on every open"
565 );
566 assert!(m.examples.len() > 2);
567 assert!(
568 m.examples
569 .iter()
570 .all(|e| (1..=100).contains(&e.parse::<i64>().unwrap()))
571 );
572 assert_eq!(m.clauses[0].description, "1 ≤ value ≤ 100");
573 assert_eq!(m.declaration, "type Quantity = Int where InRange(1, 100)");
574 }
575
576 #[test]
577 fn every_int_predicate_form() {
578 let src = "commons demo\n\ntype A = Int where NonNegative\ntype B = Int where Positive\ntype C = Int where InRange(-5, 5)\n";
579 let a = model(src, "A");
580 assert_eq!(checks(&a), ["value >= 0"]);
581 assert_eq!(a.clauses[0].message, "must be non-negative");
582 assert_eq!(a.clauses[0].description, "value ≥ 0");
583 assert!(a.examples.iter().all(|e| e.parse::<i64>().unwrap() >= 0));
584 let b = model(src, "B");
585 assert_eq!(checks(&b), ["value > 0"]);
586 assert_eq!(b.clauses[0].description, "value > 0");
587 assert!(b.examples.iter().all(|e| e.parse::<i64>().unwrap() > 0));
588 let c = model(src, "C");
589 assert_eq!(checks(&c), ["value >= -5 && value <= 5"]);
590 assert_eq!(c.clauses[0].message, "must be in range [-5, 5]");
591 assert_eq!(c.examples[..2], ["-5".to_string(), "5".to_string()]);
592 }
593
594 #[test]
595 fn float_range_and_sign_predicates() {
596 let src = "commons demo\n\ntype P = Float where InRange(0.5, 2.5)\ntype N = Float where NonNegative\ntype Q = Float where Positive\n";
597 let p = model(src, "P");
598 assert_eq!(p.base, "Float");
599 assert_eq!(p.clauses[0].description, "0.5 ≤ value ≤ 2.5");
600 assert_eq!(p.clauses[0].message, "must be in range [0.5, 2.5]");
601 assert_eq!(p.examples[..2], ["0.5".to_string(), "2.5".to_string()]);
602 assert!(
603 p.examples
604 .iter()
605 .all(|e| (0.5..=2.5).contains(&e.parse::<f64>().unwrap()))
606 );
607 assert!(
608 model(src, "N")
609 .examples
610 .iter()
611 .all(|e| e.parse::<f64>().unwrap() >= 0.0)
612 );
613 assert!(
614 model(src, "Q")
615 .examples
616 .iter()
617 .all(|e| e.parse::<f64>().unwrap() >= 1.0)
618 );
619 }
620
621 #[test]
622 fn positive_float_combines_with_a_small_range() {
623 let src = "commons demo\n\ntype P = Float where Positive && InRange(0.1, 0.5)\ntype Z = Float where Positive && InRange(-1.0, 0.0)\ntype Tiny = Float where Positive && InRange(0.0, 0.005)\n";
624 let p = model(src, "P");
625 assert!(!p.examples.is_empty(), "{:?}", p.examples_note);
626 assert!(
627 p.examples
628 .iter()
629 .all(|e| (0.1..=0.5).contains(&e.parse::<f64>().unwrap()))
630 );
631 assert!(model(src, "Z").examples.is_empty());
632 assert!(model(src, "Z").examples_note.is_some());
633 let t = model(src, "Tiny");
634 assert!(
635 t.examples.iter().all(|e| e.parse::<f64>().unwrap() > 0.0),
636 "{:?}",
637 t.examples
638 );
639 }
640
641 #[test]
642 fn a_huge_min_length_draws_nothing_and_says_so() {
643 let src = "commons demo\n\ntype Big = String where MinLength(100000000)\n";
644 let m = model(src, "Big");
645 assert!(m.examples.is_empty());
646 assert!(
647 m.examples_note
648 .as_deref()
649 .unwrap()
650 .contains("too long to list")
651 );
652 }
653
654 #[test]
655 fn the_hover_path_draws_no_examples() {
656 let src = "commons demo\n\ntype Q = Int where InRange(1, 100)\n";
657 let decl = find_type_decl(src, "Q").unwrap();
658 let m = model_for(&decl, false).unwrap();
659 assert!(m.examples.is_empty() && m.examples_note.is_none());
660 assert_eq!(m.clauses.len(), 1);
661 }
662
663 #[test]
664 fn every_string_predicate_form() {
665 let src = "commons demo\n\ntype E = String where NonEmpty\ntype Lo = String where MinLength(3)\ntype Hi = String where MaxLength(2)\ntype Ex = String where Length(4)\ntype Both = String where MinLength(3) && MaxLength(5)\n";
666 let e = model(src, "E");
667 assert_eq!(checks(&e), ["Array.from(value).length > 0"]);
668 assert_eq!(e.clauses[0].description, "length ≥ 1");
669 assert!(e.examples.iter().all(|s| !s.is_empty()));
670 let lo = model(src, "Lo");
671 assert_eq!(checks(&lo), ["Array.from(value).length >= 3"]);
672 assert!(lo.examples.iter().all(|s| s.len() >= 3));
673 let hi = model(src, "Hi");
674 assert_eq!(checks(&hi), ["Array.from(value).length <= 2"]);
675 assert!(hi.examples.iter().all(|s| s.len() <= 2));
676 assert!(
677 hi.examples.contains(&String::new()),
678 "the empty string is in MaxLength's domain"
679 );
680 let ex = model(src, "Ex");
681 assert_eq!(checks(&ex), ["Array.from(value).length === 4"]);
682 assert_eq!(ex.clauses[0].message, "length must be exactly 4");
683 assert!(ex.examples.iter().all(|s| s.len() == 4));
684 let both = model(src, "Both");
685 assert_eq!(both.clauses.len(), 2);
686 assert!(both.examples.iter().all(|s| (3..=5).contains(&s.len())));
687 }
688
689 #[test]
690 fn matches_is_checked_last_and_keeps_only_matching_examples() {
691 let src = "commons demo\n\ntype Code = String where Matches(\"[a-z]+\") && MaxLength(4)\ntype Pin = String where Matches(\"[0-9]{4}\")\n";
692 let m = model(src, "Code");
693 assert_eq!(m.clauses[0].source, "MaxLength(4)", "length first, #1651");
694 assert!(m.clauses[1].check.contains("globalThis.RegExp"));
695 assert!(m.clauses[1].check.contains("^(?:"));
696 assert_eq!(
697 m.clauses[1].description,
698 "the whole string matches /[a-z]+/"
699 );
700 assert!(
701 m.examples
702 .iter()
703 .all(|s| s.chars().all(|c| c.is_ascii_lowercase())
704 && s.len() <= 4
705 && !s.is_empty())
706 );
707 let pin = model(src, "Pin");
708 assert!(pin.examples.is_empty());
709 assert!(pin.examples_note.as_deref().unwrap().contains("needs_pin"));
710 }
711
712 #[test]
713 fn a_pattern_stays_inside_its_string_literal() {
714 let src = "commons demo\n\ntype T = String where Matches(\"a\\\\\\\"); process.exit(1); (\\\"\")\n";
715 let m = model(src, "T");
716 let check = &m.clauses[0].check;
717 let body = &check[check.find("\"^(?:\"").unwrap()..];
719 assert!(body.contains("\\\""), "{check}");
720 }
721
722 #[test]
723 fn every_predicate_form_has_its_structured_json() {
724 use serde_json::json;
725 let src = "commons demo\n\n\
726 type A = Int where NonNegative\n\
727 type B = Int where Positive\n\
728 type C = Int where InRange(-5, 5)\n\
729 type F = Float where InRange(0.5, 2.5)\n\
730 type E = String where NonEmpty\n\
731 type Lo = String where MinLength(3)\n\
732 type Hi = String where MaxLength(2)\n\
733 type Ex = String where Length(4)\n\
734 type M = String where Matches(\"[a-z]+\")\n";
735 let cases = [
736 ("A", json!({ "kind": "nonNegative" })),
737 ("B", json!({ "kind": "positive" })),
738 ("C", json!({ "kind": "range", "min": -5, "max": 5 })),
739 ("F", json!({ "kind": "range", "min": 0.5, "max": 2.5 })),
740 ("E", json!({ "kind": "nonEmpty" })),
741 ("Lo", json!({ "kind": "minLength", "length": 3 })),
742 ("Hi", json!({ "kind": "maxLength", "length": 2 })),
743 ("Ex", json!({ "kind": "length", "length": 4 })),
744 ("M", json!({ "kind": "matches", "pattern": "[a-z]+" })),
745 ];
746 for (name, want) in cases {
747 let m = model(src, name);
748 let clause = serde_json::to_value(&m.clauses[0]).unwrap();
749 assert_eq!(clause["predicate"], want, "{name}");
750 assert!(clause["check"].is_string(), "{name}: `check` is kept");
751 }
752 }
753
754 #[test]
755 fn an_int_range_bound_is_a_json_integer() {
756 let src = "commons demo\n\ntype C = Int where InRange(1, 100)\n";
757 let p = serde_json::to_string(&model(src, "C").clauses[0].predicate).unwrap();
758 assert_eq!(p, r#"{"kind":"range","min":1,"max":100}"#);
759 }
760
761 #[test]
762 fn a_hostile_pattern_reaches_the_structured_form_unchanged() {
763 let src = "commons demo\n\ntype T = String where Matches(\"a\\\\\\\"); process.exit(1); (\\\"\")\n";
764 let decl = find_type_decl(src, "T").unwrap();
765 let TypeBody::Refined {
766 refinement: Some(r),
767 ..
768 } = &decl.body
769 else {
770 panic!("refined");
771 };
772 let PredKind::Matches(written) = &r.predicates[0].kind else {
773 panic!("matches");
774 };
775 let m = model_for(&decl, false).unwrap();
776 assert_eq!(
777 m.clauses[0].predicate,
778 Predicate::Matches {
779 pattern: written.clone()
780 }
781 );
782 assert!(written.contains("process.exit(1)"), "{written}");
783 }
784
785 #[test]
786 fn non_refined_and_unrefined_types_have_no_model() {
787 let src = "commons demo\n\ntype Plain = Int\ntype Rec = { a: Int }\ntype Flag = Bool\n";
788 for n in ["Plain", "Rec", "Flag"] {
789 assert!(
790 model_for(&find_type_decl(src, n).unwrap(), true).is_none(),
791 "{n}"
792 );
793 }
794 }
795
796 #[test]
797 fn opaque_with_a_predicate_is_modelled() {
798 let src = "commons demo\n\ntype Id = opaque Int where Positive\n";
799 let decl = find_type_decl(src, "Id");
800 let m = decl.as_ref().and_then(|d| model_for(d, true));
801 assert!(m.as_ref().is_some_and(|m| m.opaque), "{decl:?}");
802 assert_eq!(
803 m.unwrap().declaration,
804 "type Id = opaque Int where Positive"
805 );
806 }
807
808 #[test]
809 fn the_hover_link_is_a_percent_encoded_command_uri() {
810 let link = hover_link("file:///a/b.bynk", Position::new(3, 7));
811 assert!(
812 link.starts_with("[Try values…](command:bynk.exploreRefinedType?%5B%22file"),
813 "{link}"
814 );
815 let query = link.split_once('?').unwrap().1;
816 assert!(!query.contains(' ') && !query.contains('"'), "{link}");
817 }
818}