tvision_rs/validate.rs
1//! Input validators that gate what an [`InputLine`](crate::widgets::InputLine)
2//! accepts.
3//!
4//! [`Validator`] is a trait; an input line holds an
5//! `Option<Box<dyn Validator>>` and, with no validator, accepts every input.
6//! The crate ships several concrete validators: [`FilterValidator`] (an allowed
7//! character set), [`RangeValidator`] (a numeric range),
8//! [`LookupValidator`] / [`StringLookupValidator`] (membership in a set),
9//! [`PXPictureValidator`] (a Paradox picture mask), and the Rust-native
10//! [`RegexValidator`].
11//!
12//! ## Object safety
13//!
14//! Because the validator is stored as a boxed trait object, [`Validator`] is
15//! **object-safe**: every method takes `&self`, no generics, no `Self` return.
16//! `validate` is a provided method that dispatches through the overridable
17//! `is_valid`/`error`.
18//!
19//! ## Typed value transfer
20//!
21//! A validator can also convert between the field's text and a typed
22//! [`FieldValue`] — [`Validator::transfer_get`] reports the field's value to a
23//! dialog gather, and [`Validator::transfer_set`] formats a value back into the
24//! field. Only validators with transfer enabled override these (for example
25//! [`RangeValidator`] transfers an [`FieldValue::Int`]); the base returns
26//! `None`, leaving the input line to use its plain text value.
27//!
28//! **Guide:** [Controls](../../../apps/controls.html).
29//!
30//! # Turbo Vision heritage
31//!
32//! Ports `TValidator` and its subclasses (`tvalidator.cpp`). The abstract base
33//! and its subclass hierarchy become this trait plus concrete impls (deviation
34//! D2); the untyped value-transfer hook becomes the typed
35//! `transfer_get`/`transfer_set` pair (deviation D10); and the streaming
36//! machinery is dropped (deviation D12).
37
38use crate::data::FieldValue;
39use crate::view::Context;
40use regex_automata::{
41 Anchored,
42 dfa::{Automaton, StartKind, dense},
43 util::start::Config as StartConfig,
44};
45
46/// An input validator.
47///
48/// An [`InputLine`](crate::widgets::InputLine) holds an
49/// `Option<Box<dyn Validator>>`; with no validator every input is accepted. The
50/// default methods all accept; concrete validators override them.
51///
52/// # Turbo Vision heritage
53///
54/// Ports the abstract `TValidator` base class (`tvalidator.cpp`); the subclass
55/// hierarchy becomes this trait (deviation D2).
56pub trait Validator {
57 /// Check (and optionally auto-fill/modify) `s` *as it is being typed*. May
58 /// mutate `s` in place (e.g. a picture validator inserting literal
59 /// characters). `suppress_fill` asks it not to auto-fill. Default: accept, no
60 /// change. Object-safe: `&self`, `s: &mut String`.
61 fn is_valid_input(&self, _s: &mut String, _suppress_fill: bool) -> bool {
62 true
63 }
64
65 /// The final-form check, run when the field must be fully valid (the
66 /// modal-OK / focus-release path). Override this to enforce your validity
67 /// rule; the base accepts every string. Prefer [`validate`](Validator::validate)
68 /// when you also need to pop the error box on failure.
69 ///
70 /// Default: `true`.
71 fn is_valid(&self, _s: &str) -> bool {
72 true
73 }
74
75 /// Report an invalid final value. Concrete validators pop up a message box via
76 /// the async-modal-from-a-view seam ([`Context::request_message_box`],
77 /// `answer_to`/`then_command` both `None` — informational, OK-only); the base
78 /// is a no-op.
79 ///
80 /// This is a [`Validator`] method, not a [`View`](crate::view::View) method.
81 fn error(&self, _ctx: &mut Context) {}
82
83 /// Validate `s` and, if invalid, pop the error box. Call this at the
84 /// field-commit point (modal OK / focus release): it calls `is_valid`, and on
85 /// failure calls `error` to display the message box before returning `false`.
86 /// Returns `true` immediately when valid without touching the context.
87 ///
88 /// A provided method; override `is_valid` and `error` rather than this.
89 fn validate(&self, s: &str, ctx: &mut Context) -> bool {
90 if self.is_valid(s) {
91 true
92 } else {
93 self.error(ctx);
94 false
95 }
96 }
97
98 /// Whether the validator's status is OK — consulted when the field must
99 /// commit. The base never enters a non-OK status, so the default is `true`;
100 /// [`PXPictureValidator`] overrides to report a malformed mask.
101 fn is_status_ok(&self) -> bool {
102 true
103 }
104
105 /// Report the field's current text `s` as a typed [`FieldValue`] during a
106 /// dialog **gather** walk. Return `Some(typed value)` when the validator has
107 /// transfer enabled and can parse the text; return `None` to leave the input
108 /// line carrying its plain text (the default, meaning "I don't transfer").
109 ///
110 /// Override this together with [`transfer_set`](Validator::transfer_set) to
111 /// participate in dialog data transfer.
112 fn transfer_get(&self, _s: &str) -> Option<FieldValue> {
113 None
114 }
115
116 /// Format a typed [`FieldValue`] back to the field's text during a dialog
117 /// **scatter** walk. Return `Some(text)` when transfer is enabled and `v`
118 /// is the type this validator handles; return `None` to leave the input line
119 /// on its own text path (the default).
120 ///
121 /// Override this together with [`transfer_get`](Validator::transfer_get) to
122 /// participate in dialog data transfer.
123 fn transfer_set(&self, _v: &FieldValue) -> Option<String> {
124 None
125 }
126}
127
128// ── Concrete validators ──────────────────────────────────────────────────────
129
130/// Accepts only characters drawn from an allowed set: every character of the
131/// input must be a member of `valid_chars`. Empty input passes.
132///
133/// Membership is tested **per Unicode `char`** (`valid_chars.contains(c)`). On
134/// an invalid final value, `error` pops up an OK-only error message box.
135///
136/// # Turbo Vision heritage
137///
138/// Ports `TFilterValidator` (`tvalidator.cpp`), which tests membership per byte
139/// where tvision-rs tests per Unicode `char` (identical for the ASCII charsets these
140/// validators carry). The streaming machinery is dropped (deviation D12).
141pub struct FilterValidator {
142 valid_chars: String,
143}
144
145impl FilterValidator {
146 /// Build a filter that accepts only characters in `valid_chars`. Pass any
147 /// `Into<String>` — typically a string literal like `"0123456789"` or
148 /// `"+-0123456789"`. Membership is tested per Unicode `char`.
149 ///
150 /// Attach the result to an [`InputLine`](crate::widgets::InputLine) as
151 /// its validator to restrict what the user can type and what the final
152 /// value may contain.
153 pub fn new(valid_chars: impl Into<String>) -> Self {
154 Self {
155 valid_chars: valid_chars.into(),
156 }
157 }
158}
159
160impl Validator for FilterValidator {
161 /// Returns `true` iff every `char` of `s` is in `valid_chars`. An empty
162 /// string passes (vacuously all characters are valid). Use this at the
163 /// final-commit check; for the while-typing path see `is_valid_input`.
164 fn is_valid(&self, s: &str) -> bool {
165 s.chars().all(|c| self.valid_chars.contains(c))
166 }
167
168 /// Returns `true` iff every `char` of `s` is in `valid_chars` — the same
169 /// rule as `is_valid`, applied per-keystroke. Never mutates `s` (a filter
170 /// never auto-fills); `suppress_fill` is ignored.
171 fn is_valid_input(&self, s: &mut String, _suppress_fill: bool) -> bool {
172 self.is_valid(s)
173 }
174
175 /// Pop an OK-only "Invalid character in input" error box via
176 /// [`Context::request_message_box`]. Called automatically by
177 /// [`validate`](Validator::validate) when [`is_valid`](FilterValidator::is_valid)
178 /// returns `false`.
179 fn error(&self, ctx: &mut Context) {
180 ctx.request_message_box(
181 "Invalid character in input".to_string(),
182 crate::dialog::MessageBoxKind::Error,
183 crate::dialog::MessageBoxButtons::ok(),
184 None,
185 None,
186 );
187 }
188}
189
190/// The accept-all base for lookup-style validators — it accepts every input.
191///
192/// Use `LookupValidator` as a stand-in when you need a no-op validator in a
193/// context that expects a lookup-style type, or as the starting point before
194/// you know which concrete validator to plug in. For actual membership testing,
195/// use [`StringLookupValidator`] instead.
196///
197/// # Turbo Vision heritage
198///
199/// Ports `TLookupValidator` (`tvalidator.cpp`), an abstract intermediate that
200/// routed validity through a virtual `lookup` step. In tvision-rs the indirection
201/// collapses: each concrete lookup validator folds the lookup directly into its
202/// `is_valid`, so this type only realises the base's accept-all behaviour.
203pub struct LookupValidator;
204
205impl LookupValidator {
206 /// Construct the accept-all lookup base.
207 pub fn new() -> Self {
208 Self
209 }
210}
211
212impl Default for LookupValidator {
213 fn default() -> Self {
214 Self::new()
215 }
216}
217
218/// Accept-all: all default methods from the base `Validator` trait suffice.
219impl Validator for LookupValidator {}
220
221/// Valid iff the input exactly matches one entry in an owned list of strings.
222/// On an invalid final value, `error` pops up an OK-only error message box.
223///
224/// Validation is a linear scan (`O(n)`) over the list, which preserves the
225/// caller's order (UI pickers may rely on it). [`StringLookupValidator::new_string_list`] replaces
226/// the whole list.
227///
228/// # Turbo Vision heritage
229///
230/// Ports `TStringLookupValidator` (`tvalidator.cpp`). The lookup folds into
231/// `is_valid` (deviation D2), the string collection becomes an owned
232/// `Vec<String>`, and the streaming machinery is dropped (deviation D12).
233///
234/// C++ `TStringLookupValidator` held a *sorted* collection and binary-searched
235/// (`O(log n)`). For the small fixed lists these validators carry, the linear
236/// scan is simpler and fast enough; order preservation is the deliberate
237/// trade-off.
238pub struct StringLookupValidator {
239 strings: Vec<String>,
240}
241
242impl StringLookupValidator {
243 /// Build a validator that accepts only strings in `strings`. Pass an owned
244 /// `Vec<String>` of the allowed values; the order is preserved and used as
245 /// the iteration order for membership tests. Attach the result to an
246 /// [`InputLine`](crate::widgets::InputLine) to restrict the final value to
247 /// one of the listed entries.
248 pub fn new(strings: Vec<String>) -> Self {
249 Self { strings }
250 }
251
252 /// Replace the accepted-string list at runtime, dropping the previous `Vec`.
253 ///
254 /// Call this when the set of valid entries changes after the validator is
255 /// already in use — e.g. a dependent field whose allowed values depend on
256 /// another control's selection. The new `strings` order becomes the
257 /// membership-test iteration order, exactly as in [`new`](Self::new); pass an
258 /// empty `Vec` to reject every input until the list is repopulated.
259 ///
260 /// # Turbo Vision heritage
261 /// Ports `TStringLookupValidator::newStringList`. The C++ `newStringList(nil)`
262 /// form (dispose the list without installing a replacement) has no analog —
263 /// pass an empty `Vec` instead.
264 pub fn new_string_list(&mut self, strings: Vec<String>) {
265 self.strings = strings;
266 }
267}
268
269impl Validator for StringLookupValidator {
270 /// Accepts `s` iff it exactly matches some entry in the list.
271 fn is_valid(&self, s: &str) -> bool {
272 self.strings.iter().any(|x| x == s)
273 }
274
275 /// Pop an OK-only "Input is not in list of valid strings" error box via
276 /// [`Context::request_message_box`]. Called automatically by
277 /// [`validate`](Validator::validate) when
278 /// [`is_valid`](StringLookupValidator::is_valid) returns `false`.
279 fn error(&self, ctx: &mut Context) {
280 ctx.request_message_box(
281 "Input is not in list of valid strings".to_string(),
282 crate::dialog::MessageBoxKind::Error,
283 crate::dialog::MessageBoxButtons::ok(),
284 None,
285 None,
286 );
287 }
288}
289
290/// A numeric validator: it gates input through a digit charset filter (an
291/// embedded [`FilterValidator`]), then on the final check parses the text and
292/// requires it to fall within `[min, max]`.
293///
294/// Whether the field also transfers its value as an [`FieldValue::Int`] is
295/// off by default — enable it with [`set_transfer`](RangeValidator::set_transfer).
296/// `min`/`max` are `i32`. On an out-of-range final value, `error` pops up an
297/// OK-only message box naming the range.
298///
299/// # Turbo Vision heritage
300///
301/// Ports `TRangeValidator` (`tvalidator.cpp`), a filter subclass. The charset is
302/// selected by the sign of `min`. Its final check adds a parse + range test on
303/// top of the charset gate, while the while-typing check is the plain charset
304/// filter (so a partial out-of-range number is accepted as input). Inheritance
305/// becomes embed-and-delegate over a [`FilterValidator`] field (deviation D2);
306/// the untyped value-transfer becomes the typed `transfer_get`/`transfer_set`
307/// pair over [`FieldValue::Int`] (deviation D10); and the streaming machinery is
308/// dropped (deviation D12).
309pub struct RangeValidator {
310 /// Embedded filter — the sign-selected digit charset.
311 filter: FilterValidator,
312 min: i32,
313 max: i32,
314 /// Whether the field also transfers its value; default OFF.
315 transfer_enabled: bool,
316}
317
318/// Parse the leading numeric value of a range-validator field.
319///
320/// Rust's `str::parse::<i32>()` is stricter than a `%ld`-style scan: it rejects
321/// trailing junk and a lone `"+"`/`"-"`. Because the charset filter already
322/// restricts the field to `[+-0-9]`, clean numeric input behaves the same; the
323/// only divergence is pathological mid-string sign/junk (e.g. `"12+3"`), which a
324/// leading-run scan truncate-accepts and we reject — an acceptable, stricter
325/// simplification. We `.trim()` first (whitespace is not in the charset, so this
326/// only matters for direct callers) and never panic.
327fn parse_long(s: &str) -> Option<i32> {
328 s.trim().parse::<i32>().ok()
329}
330
331impl RangeValidator {
332 /// Build a range validator that requires the entered integer to be in
333 /// `[min, max]` (inclusive). The embedded charset filter is selected by
334 /// `min`: non-negative → digits + `'+'`; negative → digits + `'+'` +
335 /// `'-'`. Call [`set_transfer`](RangeValidator::set_transfer) afterward
336 /// to enable typed `i32` transfer for dialog gather/scatter; transfer is
337 /// **off by default**.
338 pub fn new(min: i32, max: i32) -> Self {
339 let chars = if min >= 0 {
340 "+0123456789"
341 } else {
342 "+-0123456789"
343 };
344 Self {
345 filter: FilterValidator::new(chars),
346 min,
347 max,
348 transfer_enabled: false,
349 }
350 }
351
352 /// Enable/disable typed value transfer. Default OFF — until enabled,
353 /// [`transfer_get`](Validator::transfer_get) /
354 /// [`transfer_set`](Validator::transfer_set) return `None` and the input line
355 /// keeps its text value.
356 pub fn set_transfer(&mut self, enabled: bool) {
357 self.transfer_enabled = enabled;
358 }
359}
360
361impl Validator for RangeValidator {
362 /// Returns `true` iff `s` passes the charset gate, parses as an `i32`,
363 /// and falls within `[min, max]` (inclusive). All three conditions must
364 /// hold; the charset gate fires first so malformed input is caught early
365 /// without an attempted parse.
366 fn is_valid(&self, s: &str) -> bool {
367 self.filter.is_valid(s) && parse_long(s).is_some_and(|v| v >= self.min && v <= self.max)
368 }
369
370 /// Charset-only while typing, **no** range check (delegated straight to the
371 /// embedded filter). So a partial, out-of-range number is accepted as input;
372 /// the range is enforced only at [`is_valid`](RangeValidator::is_valid) (the
373 /// final check).
374 fn is_valid_input(&self, s: &mut String, suppress_fill: bool) -> bool {
375 self.filter.is_valid_input(s, suppress_fill)
376 }
377
378 /// When transfer is enabled, report the field text as [`FieldValue::Int`]. A
379 /// failed parse falls back to `Int(0)`; transfer only runs on already-valid
380 /// data, so that fallback is unreachable-but-safe.
381 fn transfer_get(&self, s: &str) -> Option<FieldValue> {
382 self.transfer_enabled
383 .then(|| FieldValue::Int(parse_long(s).unwrap_or(0)))
384 }
385
386 /// Format an [`Int`] back to text. `None` when transfer is disabled or `v` is
387 /// not an `Int` (the input line then takes its text path).
388 ///
389 /// [`Int`]: FieldValue::Int
390 fn transfer_set(&self, v: &FieldValue) -> Option<String> {
391 if !self.transfer_enabled {
392 return None;
393 }
394 match v {
395 FieldValue::Int(n) => Some(n.to_string()),
396 _ => None,
397 }
398 }
399
400 /// Pop an OK-only error box naming the valid range ("Value not in the
401 /// range {min} to {max}") via [`Context::request_message_box`]. Called
402 /// automatically by [`validate`](Validator::validate) when
403 /// [`is_valid`](RangeValidator::is_valid) returns `false`.
404 fn error(&self, ctx: &mut Context) {
405 ctx.request_message_box(
406 format!("Value not in the range {} to {}", self.min, self.max),
407 crate::dialog::MessageBoxKind::Error,
408 crate::dialog::MessageBoxButtons::ok(),
409 None,
410 None,
411 );
412 }
413}
414
415// ── PXPictureValidator ───────────────────────────────────────────────────────
416
417/// The result of running a Paradox picture mask against an input: complete,
418/// incomplete, empty, a runtime error, a malformed mask, an ambiguous match, or
419/// incomplete-with-no-fill.
420#[derive(Clone, Copy, PartialEq, Eq, Debug)]
421enum PicResult {
422 Complete,
423 Incomplete,
424 Empty,
425 Error,
426 Syntax,
427 Ambiguous,
428 IncompNoFill,
429}
430
431/// ASCII digit.
432fn is_number(ch: u8) -> bool {
433 ch.is_ascii_digit()
434}
435
436/// ASCII letter. Implemented as `(ch & 0xdf).is_ascii_uppercase()`: clearing
437/// `0x20` folds the case bit, so both `a..z` and `A..Z` qualify. Kept as the bit
438/// trick to stay byte-faithful to the mask engine.
439fn is_letter(ch: u8) -> bool {
440 (ch & 0xdf).is_ascii_uppercase()
441}
442
443/// Membership of `ch` in the byte set `special`.
444fn is_special(ch: u8, special: &[u8]) -> bool {
445 special.contains(&ch)
446}
447
448/// A complete match: fully complete or an accepted ambiguous match.
449fn is_complete(r: PicResult) -> bool {
450 matches!(r, PicResult::Complete | PicResult::Ambiguous)
451}
452
453/// An incomplete match, with or without fill.
454fn is_incomplete(r: PicResult) -> bool {
455 matches!(r, PicResult::Incomplete | PicResult::IncompNoFill)
456}
457
458/// ASCII uppercase fold.
459fn uppercase(ch: u8) -> u8 {
460 ch.to_ascii_uppercase()
461}
462
463/// Read mask byte `pic[i]`: an in-range byte, or `0` (a NUL terminator) when `i`
464/// is at/past the end. The mask engine relies on a trailing NUL to stop its
465/// scans, so synthesising one for out-of-range reads keeps every mask access
466/// panic-free and bit-faithful.
467fn pic_at(pic: &[u8], i: i32) -> u8 {
468 if i < 0 {
469 return 0;
470 }
471 pic.get(i as usize).copied().unwrap_or(0)
472}
473
474/// Advance `i` past one character or one balanced picture group (`[...]` /
475/// `{...}`), stopping at `term_ch`. A free function reading only the mask; kept
476/// free so callers can pass either a local cursor or `self.index` without an
477/// aliasing borrow of `self` (see `skip_to_comma`).
478fn to_group_end(pic: &[u8], i: &mut i32, term_ch: i32) {
479 let mut brk_level = 0i32;
480 let mut brc_level = 0i32;
481 loop {
482 if *i == term_ch {
483 return;
484 }
485 match pic_at(pic, *i) {
486 b'[' => brk_level += 1,
487 b']' => brk_level -= 1,
488 b'{' => brc_level += 1,
489 b'}' => brc_level -= 1,
490 b';' => *i += 1,
491 _ => {}
492 }
493 *i += 1;
494 if brk_level == 0 && brc_level == 0 {
495 break;
496 }
497 }
498}
499
500/// Validate the mask's own syntax. Rejects an empty mask, a mask ending in `;`,
501/// or unbalanced `[]`/`{}` nesting.
502fn syntax_check(pic: &[u8]) -> bool {
503 if pic.is_empty() {
504 return false;
505 }
506 if pic[pic.len() - 1] == b';' {
507 return false;
508 }
509 let mut i = 0i32;
510 let mut brk_level = 0i32;
511 let mut brc_level = 0i32;
512 let len = pic.len() as i32;
513 while i < len {
514 match pic_at(pic, i) {
515 b'[' => brk_level += 1,
516 b']' => brk_level -= 1,
517 b'{' => brc_level += 1,
518 b'}' => brc_level -= 1,
519 b';' => i += 1,
520 _ => {}
521 }
522 i += 1;
523 }
524 brk_level == 0 && brc_level == 0
525}
526
527/// The transient picture scanner — per-match-call scratch state.
528///
529/// The two cursors (`index` into the mask, `jndex` into the input) are reset to 0
530/// at the start of every match and are pure per-call scratch, not persistent
531/// validator state. The [`Validator`] methods are `&self` (object-safe), so this
532/// scratch lives in a fresh `Picture` created per call rather than in the
533/// validator.
534///
535/// ## Byte-level by design
536/// The scanner works byte-by-byte (`& 0xdf` case fold, in-place input writes), so
537/// it is ported over `&[u8]` / `Vec<u8>`. Picture masks and the inputs to such
538/// fields are ASCII, making this exact; multibyte UTF-8 in such a field is out of
539/// scope (same posture as [`FilterValidator`]'s byte-vs-char note).
540struct Picture<'a> {
541 /// The mask.
542 pic: &'a [u8],
543 /// The working input buffer; mutated in place and may GROW via autofill.
544 input: Vec<u8>,
545 /// Cursor into the mask.
546 index: i32,
547 /// Cursor into the input.
548 jndex: i32,
549}
550
551impl<'a> Picture<'a> {
552 fn new(pic: &'a [u8], input: Vec<u8>) -> Self {
553 Self {
554 pic,
555 input,
556 index: 0,
557 jndex: 0,
558 }
559 }
560
561 /// Read a mask byte (`0` past the end).
562 fn pic_at(&self, i: i32) -> u8 {
563 pic_at(self.pic, i)
564 }
565
566 /// Read an input byte (`0` past the end or before the start). Used where the
567 /// scan may touch the terminator.
568 fn input_at(&self, j: i32) -> u8 {
569 if j < 0 {
570 return 0;
571 }
572 self.input.get(j as usize).copied().unwrap_or(0)
573 }
574
575 /// Write `ch` into the input at `jndex`, then advance both cursors. (The
576 /// scanner's end-of-input guard ensures `jndex` is in range before any call,
577 /// so the write is safe.)
578 fn consume(&mut self, ch: u8) {
579 self.input[self.jndex as usize] = ch;
580 self.index += 1;
581 self.jndex += 1;
582 }
583
584 /// Advance `index` over groups until a comma separator or `term_ch`, then step
585 /// past the comma. Returns whether `index < term_ch` (i.e. there is another
586 /// alternative to try).
587 fn skip_to_comma(&mut self, term_ch: i32) -> bool {
588 loop {
589 // `to_group_end` mutates a cursor; copy `self.index` across the call
590 // to avoid aliasing `&self` (free fn reads only `pic`).
591 let mut idx = self.index;
592 to_group_end(self.pic, &mut idx, term_ch);
593 self.index = idx;
594 if self.index == term_ch || self.pic_at(self.index) == b',' {
595 break;
596 }
597 }
598 if self.pic_at(self.index) == b',' {
599 self.index += 1;
600 }
601 self.index < term_ch
602 }
603
604 /// The end index of the group starting at `index`.
605 fn calc_term(&self, term_ch: i32) -> i32 {
606 let mut k = self.index;
607 to_group_end(self.pic, &mut k, term_ch);
608 k
609 }
610
611 /// The `*[n]<group>` repeat operator. `index` points at the `*`. Reads the
612 /// optional repeat count, then runs the group exactly `itr` times (count
613 /// given) or greedily (count 0 → "any number").
614 fn iteration(&mut self, in_term: i32) -> PicResult {
615 let mut itr = 0i32;
616 let mut rslt = PicResult::Error;
617
618 self.index += 1; // Skip '*'
619
620 // Retrieve number
621 while is_number(self.pic_at(self.index)) {
622 itr = itr * 10 + (self.pic_at(self.index) - b'0') as i32;
623 self.index += 1;
624 }
625
626 let k = self.index;
627 let term_ch = self.calc_term(in_term);
628
629 // If Itr is 0 allow any number, otherwise enforce the number
630 if itr != 0 {
631 for _l in 1..=itr {
632 self.index = k;
633 rslt = self.process(term_ch);
634 if !is_complete(rslt) {
635 // Empty means incomplete since all are required
636 if rslt == PicResult::Empty {
637 rslt = PicResult::Incomplete;
638 }
639 return rslt;
640 }
641 }
642 } else {
643 loop {
644 self.index = k;
645 rslt = self.process(term_ch);
646 if rslt != PicResult::Complete {
647 break;
648 }
649 }
650 if rslt == PicResult::Empty || rslt == PicResult::Error {
651 self.index += 1;
652 rslt = PicResult::Ambiguous;
653 }
654 }
655 self.index = term_ch;
656
657 rslt
658 }
659
660 /// A `{...}` (required) or `[...]` (optional) bracketed picture group. `index`
661 /// points at the opening bracket.
662 fn group(&mut self, in_term: i32) -> PicResult {
663 let term_ch = self.calc_term(in_term);
664 self.index += 1;
665 let rslt = self.process(term_ch - 1);
666
667 if !is_incomplete(rslt) {
668 self.index = term_ch;
669 }
670
671 rslt
672 }
673
674 /// On an incomplete result, see whether all that remains in the mask is
675 /// optional (`[...]` groups or unbounded `*` iterations); if so the input is
676 /// ambiguously complete.
677 fn check_complete(&mut self, rslt: PicResult, term_ch: i32) -> PicResult {
678 let mut rslt = rslt;
679 let mut j = self.index;
680 let mut status = true;
681
682 if is_incomplete(rslt) {
683 // Skip optional pieces
684 while status {
685 match self.pic_at(j) {
686 b'[' => {
687 to_group_end(self.pic, &mut j, term_ch);
688 }
689 b'*' => {
690 if !is_number(self.pic_at(j + 1)) {
691 j += 1;
692 }
693 to_group_end(self.pic, &mut j, term_ch);
694 }
695 _ => {
696 status = false;
697 }
698 }
699 }
700
701 if j == term_ch {
702 rslt = PicResult::Ambiguous;
703 }
704 }
705
706 rslt
707 }
708
709 /// Match the input against one comma-free run of the mask (up to `term_ch` or
710 /// a `,`), consuming input as it goes.
711 fn scan(&mut self, term_ch: i32) -> PicResult {
712 let r_scan = PicResult::Error;
713 let mut rslt = PicResult::Empty;
714
715 while self.index != term_ch && self.pic_at(self.index) != b',' {
716 if self.jndex >= self.input.len() as i32 {
717 return self.check_complete(rslt, term_ch);
718 }
719
720 let ch = self.input_at(self.jndex);
721 match self.pic_at(self.index) {
722 b'#' => {
723 if !is_number(ch) {
724 return PicResult::Error;
725 } else {
726 self.consume(ch);
727 }
728 }
729 b'?' => {
730 if !is_letter(ch) {
731 return PicResult::Error;
732 } else {
733 self.consume(ch);
734 }
735 }
736 b'&' => {
737 if !is_letter(ch) {
738 return PicResult::Error;
739 } else {
740 self.consume(uppercase(ch));
741 }
742 }
743 b'!' => {
744 self.consume(uppercase(ch));
745 }
746 b'@' => {
747 self.consume(ch);
748 }
749 b'*' => {
750 rslt = self.iteration(term_ch);
751 if !is_complete(rslt) {
752 return rslt;
753 }
754 if rslt == PicResult::Error {
755 rslt = PicResult::Ambiguous;
756 }
757 }
758 b'{' => {
759 rslt = self.group(term_ch);
760 if !is_complete(rslt) {
761 return rslt;
762 }
763 }
764 b'[' => {
765 rslt = self.group(term_ch);
766 if is_incomplete(rslt) {
767 return rslt;
768 }
769 if rslt == PicResult::Error {
770 rslt = PicResult::Ambiguous;
771 }
772 }
773 _ => {
774 // Literal arm: a `;`-escape advances past the `;` to the
775 // escaped literal; the typed char must match the mask literal
776 // case-insensitively (a typed space matches any literal — it
777 // gets overwritten); otherwise the run fails. The byte CONSUMED
778 // is always the MASK byte, so the buffer is normalized to the
779 // mask's literal — NOT the typed `ch`.
780 if self.pic_at(self.index) == b';' {
781 self.index += 1;
782 }
783 if uppercase(self.pic_at(self.index)) != uppercase(ch) && ch != b' ' {
784 return r_scan;
785 }
786 self.consume(self.pic_at(self.index));
787 }
788 }
789
790 if rslt == PicResult::Ambiguous {
791 rslt = PicResult::IncompNoFill;
792 } else {
793 rslt = PicResult::Incomplete;
794 }
795 }
796
797 if rslt == PicResult::IncompNoFill {
798 PicResult::Ambiguous
799 } else {
800 PicResult::Complete
801 }
802 }
803
804 /// Try each comma-separated alternative in the mask run, backtracking on
805 /// error/incomplete; tracks the best (farthest-consuming) incomplete to
806 /// disambiguate.
807 fn process(&mut self, term_ch: i32) -> PicResult {
808 let mut incomp = false;
809 let mut old_i = self.index;
810 let old_j = self.jndex;
811 let mut incomp_j = 0i32;
812 let mut incomp_i = 0i32;
813 let mut rslt;
814 let mut r_process;
815
816 loop {
817 rslt = self.scan(term_ch);
818
819 // Only accept completes if they make it farther in the input
820 // stream from the last incomplete
821 if rslt == PicResult::Complete && incomp && self.jndex < incomp_j {
822 rslt = PicResult::Incomplete;
823 self.jndex = incomp_j;
824 }
825
826 if rslt == PicResult::Error || rslt == PicResult::Incomplete {
827 r_process = rslt;
828
829 if !incomp && rslt == PicResult::Incomplete {
830 incomp = true;
831 incomp_i = self.index;
832 incomp_j = self.jndex;
833 }
834 self.index = old_i;
835 self.jndex = old_j;
836 if !self.skip_to_comma(term_ch) {
837 if incomp {
838 r_process = PicResult::Incomplete;
839 self.index = incomp_i;
840 self.jndex = incomp_j;
841 }
842 return r_process;
843 }
844 old_i = self.index;
845 }
846
847 if rslt != PicResult::Error && rslt != PicResult::Incomplete {
848 break;
849 }
850 }
851
852 if rslt == PicResult::Complete && incomp {
853 PicResult::Ambiguous
854 } else {
855 rslt
856 }
857 }
858
859 /// The top-level match driver. Resets the cursors, runs the alternative
860 /// matcher, applies the trailing-input/autofill logic, and maps the internal
861 /// `Ambiguous`/`IncompNoFill` results to their public `Complete`/`Incomplete`
862 /// equivalents.
863 fn run(&mut self, auto_fill: bool) -> PicResult {
864 if !syntax_check(self.pic) {
865 return PicResult::Syntax;
866 }
867
868 if self.input.is_empty() {
869 return PicResult::Empty;
870 }
871
872 self.jndex = 0;
873 self.index = 0;
874
875 let mut rslt = self.process(self.pic.len() as i32);
876
877 if rslt != PicResult::Error && self.jndex < self.input.len() as i32 {
878 rslt = PicResult::Error;
879 }
880
881 if rslt == PicResult::Incomplete && auto_fill {
882 let mut reprocess = false;
883
884 while self.index < self.pic.len() as i32
885 && !is_special(self.pic_at(self.index), b"#?&!@*{}[],")
886 {
887 if self.pic_at(self.index) == b';' {
888 self.index += 1;
889 }
890 // Append one mask byte to the input (the Vec carries its own
891 // length, so no NUL terminator is stored).
892 self.input.push(self.pic_at(self.index));
893 self.index += 1;
894 reprocess = true;
895 }
896
897 self.jndex = 0;
898 self.index = 0;
899 if reprocess {
900 rslt = self.process(self.pic.len() as i32);
901 }
902 }
903
904 match rslt {
905 PicResult::Ambiguous => PicResult::Complete,
906 PicResult::IncompNoFill => PicResult::Incomplete,
907 other => other,
908 }
909 }
910}
911
912/// The Paradox picture-mask validator.
913///
914/// Validates and auto-fills input against a Paradox "picture" mask: `#` digit,
915/// `?` letter, `&` letter→uppercase, `!` any→uppercase, `@` any, `*` repeat,
916/// `{}`/`[]` required/optional groups, `,` alternatives, `;` literal-escape, and
917/// any other character is a literal. On an invalid final value, `error` pops up
918/// an OK-only message box.
919///
920/// The matching engine is a recursive state machine. Its scan cursors are pure
921/// per-call scratch, not validator state, so — because the [`Validator`] methods
922/// are `&self` (object-safe) — that scratch lives in a transient `Picture`
923/// created fresh per call. Operation is byte-level.
924///
925/// # Turbo Vision heritage
926///
927/// Ports `TPXPictureValidator`, with the matching engine taken verbatim from
928/// `tvalidat.cpp`. The streaming machinery is dropped (deviation D12). Where the
929/// original copies the input into a fixed 256-byte stack buffer, tvision-rs lets the
930/// backing `String` grow instead (real inputs are length-bounded by the field).
931/// No null-mask guard is needed: `pic` is always a (possibly empty) `String`,
932/// and an empty or malformed mask yields the same `Syntax`/`Empty` results.
933pub struct PXPictureValidator {
934 /// The mask, owned.
935 pic: String,
936 /// Auto-fill literals while typing.
937 auto_fill: bool,
938 /// Whether the mask is well-formed (`false` on a syntax error). Set in
939 /// [`new`](Self::new).
940 status_ok: bool,
941}
942
943impl PXPictureValidator {
944 /// Build a Paradox picture validator from `pic` (the mask) and
945 /// `auto_fill` (whether to insert mask literals while the user types).
946 ///
947 /// The constructor runs the engine on empty input as a **syntax probe**:
948 /// a well-formed mask returns `Empty`, leaving `is_status_ok()` true;
949 /// any other result means the mask is malformed and `is_status_ok()`
950 /// returns `false`. Check `is_status_ok()` after construction if you want
951 /// to report a bad mask before the field is even used.
952 pub fn new(pic: impl Into<String>, auto_fill: bool) -> Self {
953 let pic = pic.into();
954 let mut p = Picture::new(pic.as_bytes(), Vec::new());
955 // status_ok iff the empty-input probe yields Empty (a well-formed mask).
956 let status_ok = p.run(false) == PicResult::Empty;
957 Self {
958 pic,
959 auto_fill,
960 status_ok,
961 }
962 }
963}
964
965impl Validator for PXPictureValidator {
966 /// Run the mask while typing (auto-filling unless `suppress_fill`); returns
967 /// whether the result is not an error. MUTATES `s` in place — autofill of
968 /// literals plus uppercase transforms is the whole point of a picture
969 /// validator.
970 fn is_valid_input(&self, s: &mut String, suppress_fill: bool) -> bool {
971 let do_fill = self.auto_fill && !suppress_fill;
972 let mut p = Picture::new(self.pic.as_bytes(), s.as_bytes().to_vec());
973 let r = p.run(do_fill);
974 *s = String::from_utf8_lossy(&p.input).into_owned();
975 r != PicResult::Error
976 }
977
978 /// Returns `true` iff `s` fully satisfies the mask (i.e. the engine returns
979 /// `Complete`). Runs the matcher on a copy with auto-fill off, so `s` is
980 /// never mutated. Use this at the final-commit check; for the while-typing
981 /// path see [`is_valid_input`](PXPictureValidator::is_valid_input).
982 fn is_valid(&self, s: &str) -> bool {
983 let mut p = Picture::new(self.pic.as_bytes(), s.as_bytes().to_vec());
984 p.run(false) == PicResult::Complete
985 }
986
987 /// Whether the mask itself is well-formed — overrides the base accept-all to
988 /// report a malformed mask.
989 fn is_status_ok(&self) -> bool {
990 self.status_ok
991 }
992
993 /// Pop an OK-only error box quoting the malformed mask ("Error in picture
994 /// format. {pic}") via [`Context::request_message_box`]. Called
995 /// automatically by [`validate`](Validator::validate) when
996 /// [`is_valid`](PXPictureValidator::is_valid) returns `false`.
997 fn error(&self, ctx: &mut Context) {
998 ctx.request_message_box(
999 format!("Error in picture format.\n {}", self.pic),
1000 crate::dialog::MessageBoxKind::Error,
1001 crate::dialog::MessageBoxButtons::ok(),
1002 None,
1003 None,
1004 );
1005 }
1006}
1007
1008// ── RegexValidator (tvision-rs extension) ─────────────────────────────────────────
1009
1010/// Error returned when compiling a [`RegexValidator`] pattern.
1011///
1012/// A thin wrapper over the regex-automata build error so the dependency's
1013/// exact error type does not leak into the public API.
1014#[derive(Debug)]
1015pub struct RegexError(String);
1016
1017impl std::fmt::Display for RegexError {
1018 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1019 f.write_str(&self.0)
1020 }
1021}
1022
1023impl std::error::Error for RegexError {}
1024
1025/// A [`Validator`] driven by a regular expression, giving the same two-phase behavior as
1026/// [`PXPictureValidator`] — `is_valid` = the input fully matches the pattern;
1027/// `is_valid_input` = the input is still a *prefix of some complete match*
1028/// ("could it still become valid?") — but expressed as a regex so callers can
1029/// leverage regex knowledge instead of Paradox picture-mask syntax.
1030///
1031/// ## Pattern semantics
1032/// The pattern describes the **complete field value** and is implicitly fully
1033/// anchored. The user pattern is compiled twice (see [`new`](Self::new)); the
1034/// effective pattern is `(?:<pattern>)\z` built with an anchored start state.
1035/// Three pieces cooperate:
1036/// - **Start anchor** comes from the DFA's anchored-start configuration
1037/// (`StartKind::Anchored`).
1038/// - **End anchor**: for [`is_valid`](Validator::is_valid) it is the
1039/// `next_eoi_state` + `is_match_state` step; the `\z` in the wrapped pattern
1040/// is what drives [`is_valid_input`](Validator::is_valid_input)'s dead-state
1041/// rejection (without it, no trailing input could ever be ruled out).
1042/// - The **`(?:…)` non-capturing group** fixes alternation precedence: it
1043/// anchors the *whole* alternation, so `cat|dog` means "(cat or dog), then
1044/// end" rather than "cat, or (dog then `\z`)".
1045///
1046/// To stop a malformed pattern from escaping that wrap (e.g. an unbalanced `)`
1047/// that would close `(?:…)` early and silently defeat end-anchoring), the bare
1048/// user pattern is validated for self-containment before wrapping — see
1049/// [`new`](Self::new).
1050///
1051/// ## Per-keystroke viability (`is_valid_input`)
1052/// Uses the DFA **dead-state** test: walk the anchored DFA over the bytes of
1053/// the input; if a dead state (one from which no match is ever reachable) is
1054/// reached, the input cannot become valid no matter what is appended → reject.
1055/// Unlike [`PXPictureValidator`], `RegexValidator` performs **no autofill** and
1056/// never mutates the input string.
1057///
1058/// ## Construction cost and thread safety
1059/// The DFA is compiled once in [`new`](Self::new) and is thereafter immutable.
1060/// `RegexValidator` is `Send + Sync`. `\d`/`\w`/`\s` and other Perl-compatible
1061/// character classes are available (`unicode-perl` feature is enabled).
1062///
1063/// # Turbo Vision heritage
1064/// **tvision-rs extension**: no Turbo Vision counterpart. It sits alongside the faithful
1065/// [`PXPictureValidator`] port.
1066///
1067/// [`PXPictureValidator`]: crate::PXPictureValidator
1068pub struct RegexValidator {
1069 dfa: dense::DFA<Vec<u32>>,
1070 /// The original user-supplied pattern, retained for [`Debug`] and [`error`](Validator::error).
1071 pattern: String,
1072}
1073
1074impl std::fmt::Debug for RegexValidator {
1075 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1076 // The DFA's internal repr is not Debug-friendly to print; show the pattern only.
1077 f.debug_struct("RegexValidator")
1078 .field("pattern", &self.pattern)
1079 .finish()
1080 }
1081}
1082
1083impl RegexValidator {
1084 /// Compile `pattern` as a description of a complete, valid field value.
1085 ///
1086 /// The pattern is wrapped as `(?:<pattern>)\z` (end-anchored) and the DFA
1087 /// is built with `StartKind::Anchored` (start-anchored). Returns `Err` if
1088 /// the pattern is syntactically invalid or its DFA exceeds build limits.
1089 ///
1090 /// The bare pattern is built and validated *first*, before wrapping: a
1091 /// pattern that is not self-contained — e.g. an unbalanced `)` that would
1092 /// close the `(?:…)` group early and silently defeat end-anchoring (the
1093 /// `\z` binding only part of the pattern) — is rejected here. A balanced
1094 /// bare pattern cannot break out of the wrap, so this closes that hole.
1095 pub fn new(pattern: &str) -> Result<Self, RegexError> {
1096 let cfg = dense::Config::new().start_kind(StartKind::Anchored);
1097 // Reject patterns that aren't self-contained (paren-injection guard).
1098 dense::Builder::new()
1099 .configure(cfg.clone())
1100 .build(pattern)
1101 .map_err(|e| RegexError(e.to_string()))?;
1102 let wrapped = format!(r"(?:{pattern})\z");
1103 let dfa = dense::Builder::new()
1104 .configure(cfg)
1105 .build(&wrapped)
1106 .map_err(|e| RegexError(e.to_string()))?;
1107 Ok(Self {
1108 dfa,
1109 pattern: pattern.to_string(),
1110 })
1111 }
1112
1113 /// Walk the anchored DFA over the bytes of `s`.
1114 ///
1115 /// Returns `(dead, state)` where `dead == true` means the DFA reached a
1116 /// dead state (no continuation can ever match). `StartKind::Anchored`
1117 /// guarantees the anchored start state exists, so the `start_state` call
1118 /// never errors — the `expect` documents that build-time invariant.
1119 fn walk(&self, s: &str) -> (bool, regex_automata::util::primitives::StateID) {
1120 let mut st = self
1121 .dfa
1122 .start_state(&StartConfig::new().anchored(Anchored::Yes))
1123 .expect("anchored start state (DFA built with StartKind::Anchored)");
1124 for &b in s.as_bytes() {
1125 st = self.dfa.next_state(st, b);
1126 if self.dfa.is_dead_state(st) {
1127 return (true, st);
1128 }
1129 }
1130 (false, st)
1131 }
1132}
1133
1134impl Validator for RegexValidator {
1135 /// The whole input matches the pattern (a complete, valid value).
1136 ///
1137 /// The regex analogue of `PicResult::Complete` in the picture validator:
1138 /// both the start and end anchors must be satisfied.
1139 fn is_valid(&self, s: &str) -> bool {
1140 let (dead, st) = self.walk(s);
1141 if dead {
1142 return false;
1143 }
1144 let st = self.dfa.next_eoi_state(st);
1145 self.dfa.is_match_state(st)
1146 }
1147
1148 /// The input is still a prefix of some complete match — "could it become
1149 /// valid if the user keeps typing?".
1150 ///
1151 /// Equivalent to "incomplete (or better)" in the picture-validator model:
1152 /// rejects only when the DFA has reached a dead state (no continuation can
1153 /// ever lead to a match). Does **not** mutate `s` — unlike
1154 /// [`PXPictureValidator`], there is no autofill.
1155 fn is_valid_input(&self, s: &mut String, _suppress_fill: bool) -> bool {
1156 !self.walk(s).0
1157 }
1158
1159 /// Report an invalid final value via the async-modal-from-a-view seam
1160 /// (informational, OK-only).
1161 fn error(&self, ctx: &mut Context) {
1162 ctx.request_message_box(
1163 format!("Input does not match pattern: {}", self.pattern),
1164 crate::dialog::MessageBoxKind::Error,
1165 crate::dialog::MessageBoxButtons::ok(),
1166 None,
1167 None,
1168 );
1169 }
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174 use super::*;
1175
1176 /// Run `validator.validate(s, ctx)` over a throwaway [`Context`] and return the
1177 /// bool (the test never inspects the requested box here — that is covered by the
1178 /// program-level async-modal tests). Also returns whether a box was requested.
1179 fn vd<V: Validator + ?Sized>(v: &V, s: &str) -> bool {
1180 let mut out = std::collections::VecDeque::new();
1181 let mut timers = crate::timer::TimerQueue::new();
1182 let mut deferred: Vec<crate::view::Deferred> = Vec::new();
1183 let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
1184 v.validate(s, &mut ctx)
1185 }
1186
1187 /// The abstract base accepts everything and reports OK.
1188 struct AcceptAll;
1189 impl Validator for AcceptAll {}
1190
1191 /// A validator that rejects anything not equal to its target — exercises the
1192 /// non-default path through `validate`/`is_valid`.
1193 struct OnlyExact(&'static str);
1194 impl Validator for OnlyExact {
1195 fn is_valid(&self, s: &str) -> bool {
1196 s == self.0
1197 }
1198 }
1199
1200 #[test]
1201 fn default_methods_accept() {
1202 let v = AcceptAll;
1203 let mut s = String::from("anything");
1204 assert!(v.is_valid_input(&mut s, false));
1205 assert_eq!(s, "anything", "default is_valid_input does not modify");
1206 assert!(v.is_valid("x"));
1207 assert!(vd(&v, "x"));
1208 assert!(v.is_status_ok());
1209 }
1210
1211 #[test]
1212 fn validate_fails_when_is_valid_false() {
1213 let v = OnlyExact("ok");
1214 assert!(vd(&v, "ok"));
1215 assert!(!vd(&v, "nope"));
1216 assert!(v.is_valid("ok"));
1217 assert!(!v.is_valid("nope"));
1218 }
1219
1220 #[test]
1221 fn is_object_safe() {
1222 // Compiles only if Validator is object-safe (the InputLine storage form).
1223 let v: Box<dyn Validator> = Box::new(OnlyExact("ok"));
1224 assert!(vd(&*v, "ok"));
1225 assert!(!vd(&*v, "no"));
1226 }
1227
1228 // ── FilterValidator ───────────────────────────────────────────────────────
1229
1230 #[test]
1231 fn filter_accepts_all_valid_chars() {
1232 let v = FilterValidator::new("0123456789");
1233 assert!(v.is_valid("42"));
1234 assert!(v.is_valid("0"));
1235 }
1236
1237 #[test]
1238 fn filter_rejects_out_of_set_char() {
1239 let v = FilterValidator::new("0123456789");
1240 // 'a' is not in the digit set — must reject.
1241 assert!(!v.is_valid("12a3"));
1242 assert!(!v.is_valid("a"));
1243 }
1244
1245 #[test]
1246 fn filter_accepts_empty_string() {
1247 // strspn("", validChars) == strlen("") == 0 → accepts.
1248 let v = FilterValidator::new("abc");
1249 assert!(v.is_valid(""));
1250 }
1251
1252 #[test]
1253 fn filter_is_valid_input_agrees_with_is_valid() {
1254 let v = FilterValidator::new("abc");
1255 let mut good = String::from("ab");
1256 let mut bad = String::from("ax");
1257 assert!(v.is_valid_input(&mut good, false));
1258 assert!(!v.is_valid_input(&mut bad, false));
1259 // is_valid_input must not mutate the string.
1260 assert_eq!(good, "ab");
1261 assert_eq!(bad, "ax");
1262 }
1263
1264 #[test]
1265 fn filter_validate_returns_false_on_rejected() {
1266 let v = FilterValidator::new("abc");
1267 assert!(vd(&v, "abc"));
1268 assert!(!vd(&v, "abx")); // 'x' not in set
1269 }
1270
1271 #[test]
1272 fn filter_object_safe_as_boxed_trait() {
1273 // Verifies the storage form `Option<Box<dyn Validator>>` compiles.
1274 let v: Box<dyn Validator> = Box::new(FilterValidator::new("abc"));
1275 assert!(v.is_valid("ab"));
1276 assert!(!v.is_valid("az"));
1277 }
1278
1279 // ── LookupValidator ───────────────────────────────────────────────────────
1280
1281 #[test]
1282 fn lookup_validator_accepts_anything() {
1283 let v = LookupValidator::new();
1284 assert!(v.is_valid(""));
1285 assert!(v.is_valid("anything at all"));
1286 assert!(vd(&v, "whatever"));
1287 assert!(v.is_status_ok());
1288 }
1289
1290 #[test]
1291 fn lookup_validator_default_impl() {
1292 // Default::default() must work.
1293 let v: LookupValidator = Default::default();
1294 let mut s = String::from("test");
1295 assert!(v.is_valid_input(&mut s, false));
1296 }
1297
1298 #[test]
1299 fn lookup_validator_object_safe() {
1300 let v: Box<dyn Validator> = Box::new(LookupValidator::new());
1301 assert!(vd(&*v, "foo"));
1302 }
1303
1304 // ── StringLookupValidator ─────────────────────────────────────────────────
1305
1306 #[test]
1307 fn string_lookup_accepts_exact_member() {
1308 let v = StringLookupValidator::new(vec!["yes".into(), "no".into()]);
1309 assert!(v.is_valid("yes"));
1310 assert!(v.is_valid("no"));
1311 }
1312
1313 #[test]
1314 fn string_lookup_rejects_non_member() {
1315 let v = StringLookupValidator::new(vec!["yes".into(), "no".into()]);
1316 assert!(!v.is_valid("maybe"));
1317 assert!(!v.is_valid("YES")); // case-sensitive (strcmp == 0)
1318 }
1319
1320 #[test]
1321 fn string_lookup_rejects_prefix_or_substring() {
1322 // "ye" is a prefix of "yes" — exact match only (strcmp semantics).
1323 let v = StringLookupValidator::new(vec!["yes".into()]);
1324 assert!(!v.is_valid("ye"));
1325 assert!(!v.is_valid("es"));
1326 assert!(!v.is_valid("yes ")); // trailing space → not equal
1327 }
1328
1329 #[test]
1330 fn string_lookup_rejects_against_empty_list() {
1331 let v = StringLookupValidator::new(vec![]);
1332 assert!(!v.is_valid("anything"));
1333 }
1334
1335 #[test]
1336 fn string_lookup_new_string_list_replaces_set() {
1337 let mut v = StringLookupValidator::new(vec!["old".into()]);
1338 assert!(v.is_valid("old"));
1339 assert!(!v.is_valid("new"));
1340 v.new_string_list(vec!["new".into()]);
1341 assert!(!v.is_valid("old")); // was-accepted now rejected
1342 assert!(v.is_valid("new")); // was-rejected now accepted
1343 }
1344
1345 #[test]
1346 fn string_lookup_validate_false_on_non_member() {
1347 let v = StringLookupValidator::new(vec!["ok".into()]);
1348 assert!(vd(&v, "ok"));
1349 assert!(!vd(&v, "bad"));
1350 }
1351
1352 #[test]
1353 fn string_lookup_object_safe() {
1354 let v: Box<dyn Validator> = Box::new(StringLookupValidator::new(vec!["x".into()]));
1355 assert!(v.is_valid("x"));
1356 assert!(!v.is_valid("y"));
1357 }
1358
1359 // ── RangeValidator ────────────────────────────────────────────────────────
1360
1361 #[test]
1362 fn range_is_valid_in_range_accepts() {
1363 let v = RangeValidator::new(1, 100);
1364 assert!(v.is_valid("1"));
1365 assert!(v.is_valid("50"));
1366 assert!(v.is_valid("100"));
1367 }
1368
1369 #[test]
1370 fn range_is_valid_below_min_rejects() {
1371 let v = RangeValidator::new(10, 100);
1372 assert!(!v.is_valid("9"));
1373 assert!(!v.is_valid("0"));
1374 }
1375
1376 #[test]
1377 fn range_is_valid_above_max_rejects() {
1378 let v = RangeValidator::new(1, 10);
1379 assert!(!v.is_valid("11"));
1380 assert!(!v.is_valid("999"));
1381 }
1382
1383 #[test]
1384 fn range_is_valid_rejects_non_charset_at_filter_gate() {
1385 // 'a' is not in "+0123456789" — the filter gate fires before any parse.
1386 let v = RangeValidator::new(0, 100);
1387 assert!(!v.is_valid("1a2"));
1388 assert!(!v.is_valid("abc"));
1389 }
1390
1391 #[test]
1392 fn range_is_valid_rejects_sign_only_string() {
1393 // "+" passes the charset gate but `parse_long` fails → reject.
1394 let v = RangeValidator::new(0, 100);
1395 assert!(!v.is_valid("+"));
1396 let signed = RangeValidator::new(-5, 5);
1397 assert!(!signed.is_valid("-"));
1398 }
1399
1400 #[test]
1401 fn range_charset_selected_by_sign_of_min() {
1402 // DISCRIMINATING: the signed validator's charset accepts '-', the unsigned
1403 // one rejects it at the FILTER gate (before any parse).
1404 let signed = RangeValidator::new(-10, 10);
1405 assert!(signed.is_valid("-5"));
1406 let unsigned = RangeValidator::new(0, 10);
1407 assert!(!unsigned.is_valid("-5")); // '-' not in unsigned charset
1408 }
1409
1410 #[test]
1411 fn range_is_valid_input_is_charset_only_not_range_checked() {
1412 // DISCRIMINATING: the while-typing check is the embedded filter's — it
1413 // checks charset only, NOT the range. "999" is accepted as input even
1414 // though is_valid("999") is false for range 1..=10. Would fail if someone
1415 // "helpfully" range-checked during typing.
1416 let v = RangeValidator::new(1, 10);
1417 let mut s = String::from("999");
1418 assert!(v.is_valid_input(&mut s, false));
1419 assert!(!v.is_valid("999"));
1420 assert_eq!(
1421 s, "999",
1422 "is_valid_input must not mutate (Filter never fills)"
1423 );
1424 }
1425
1426 #[test]
1427 fn range_transfer_disabled_by_default_returns_none() {
1428 let v = RangeValidator::new(0, 100);
1429 assert_eq!(v.transfer_get("42"), None);
1430 assert_eq!(v.transfer_set(&FieldValue::Int(42)), None);
1431 }
1432
1433 #[test]
1434 fn range_transfer_enabled_round_trips_int() {
1435 let mut v = RangeValidator::new(0, 100);
1436 v.set_transfer(true);
1437 assert_eq!(v.transfer_get("42"), Some(FieldValue::Int(42)));
1438 assert_eq!(v.transfer_set(&FieldValue::Int(42)), Some("42".to_string()));
1439 }
1440
1441 #[test]
1442 fn range_transfer_set_wrong_type_returns_none() {
1443 let mut v = RangeValidator::new(0, 100);
1444 v.set_transfer(true);
1445 // Text is not the type RangeValidator transfers → None (Text fallback path).
1446 assert_eq!(v.transfer_set(&FieldValue::Text("42".into())), None);
1447 }
1448
1449 #[test]
1450 fn range_transfer_get_unparseable_falls_back_to_zero() {
1451 // Unreachable-but-safe: transfer only runs on already-valid data; a bad
1452 // parse falls back to Int(0) rather than panicking.
1453 let mut v = RangeValidator::new(0, 100);
1454 v.set_transfer(true);
1455 assert_eq!(v.transfer_get("+"), Some(FieldValue::Int(0)));
1456 }
1457
1458 #[test]
1459 fn range_object_safe_as_boxed_trait() {
1460 let v: Box<dyn Validator> = Box::new(RangeValidator::new(1, 10));
1461 assert!(v.is_valid("5"));
1462 assert!(!v.is_valid("11"));
1463 }
1464
1465 // ── PXPictureValidator ────────────────────────────────────────────────────
1466 //
1467 // Golden vectors hand-traced against the reference engine (`tvalidat.cpp`).
1468 // If the implementation disagrees with one, the implementation (or the trace)
1469 // is wrong — re-check against the reference, don't weaken the assertion.
1470
1471 /// Mask "###" (three required digits), autoFill=false.
1472 #[test]
1473 fn pic_three_digits_is_valid() {
1474 let v = PXPictureValidator::new("###", false);
1475 assert!(v.is_valid("123")); // prComplete
1476 assert!(!v.is_valid("12")); // prIncomplete
1477 assert!(!v.is_valid("1234")); // prError (jndex < len after complete)
1478 assert!(!v.is_valid("12a")); // prError
1479 assert!(!v.is_valid("")); // prEmpty != Complete
1480 assert!(v.is_status_ok()); // well-formed mask
1481 }
1482
1483 /// Mask "###" autoFill=false — isValidInput accepts partial/incomplete (only
1484 /// prError fails) and does NOT mutate a non-filling field.
1485 #[test]
1486 fn pic_three_digits_is_valid_input() {
1487 let v = PXPictureValidator::new("###", false);
1488
1489 let mut s = String::from("12");
1490 assert!(v.is_valid_input(&mut s, false)); // prIncomplete != Error
1491 assert_eq!(s, "12"); // unchanged (no autofill)
1492
1493 let mut s = String::from("12a");
1494 assert!(!v.is_valid_input(&mut s, false)); // prError
1495
1496 let mut s = String::from("1234");
1497 assert!(!v.is_valid_input(&mut s, false)); // prError
1498 }
1499
1500 /// Mask "&&&" autoFill=true — three letters, uppercased. THE most
1501 /// discriminating mutation test: "abc" → "ABC".
1502 #[test]
1503 fn pic_uppercase_autofill_mutates() {
1504 let v = PXPictureValidator::new("&&&", true);
1505 let mut s = String::from("abc");
1506 assert!(v.is_valid_input(&mut s, false));
1507 assert_eq!(s, "ABC"); // & uppercases each consumed letter
1508 assert!(v.is_valid("abc")); // prComplete (& matches lowercase letters)
1509 }
1510
1511 /// Mask "!" autoFill=true — one char, uppercased: "a" → "A".
1512 #[test]
1513 fn pic_bang_uppercases_single() {
1514 let v = PXPictureValidator::new("!", true);
1515 let mut s = String::from("a");
1516 assert!(v.is_valid_input(&mut s, false));
1517 assert_eq!(s, "A");
1518 }
1519
1520 /// Mask "##:##" autoFill=true — the literal ':' auto-fills after "12":
1521 /// "12" → "12:". And a full "12:34" is complete.
1522 #[test]
1523 fn pic_literal_colon_autofills() {
1524 let v = PXPictureValidator::new("##:##", true);
1525 let mut s = String::from("12");
1526 assert!(v.is_valid_input(&mut s, false));
1527 assert_eq!(s, "12:"); // autofill tail appends the literal ':'
1528 assert!(v.is_valid("12:34")); // prComplete
1529 }
1530
1531 /// Syntax / status: trailing ';' is a syntax error → vsSyntax.
1532 #[test]
1533 fn pic_trailing_semicolon_is_syntax_error() {
1534 let v = PXPictureValidator::new("##;", false);
1535 assert!(!v.is_status_ok());
1536 }
1537
1538 /// Syntax / status: unbalanced '[' → vsSyntax.
1539 #[test]
1540 fn pic_unbalanced_bracket_is_syntax_error() {
1541 let v = PXPictureValidator::new("[##", false);
1542 assert!(!v.is_status_ok());
1543 }
1544
1545 /// Syntax / status: well-formed mask → OK.
1546 #[test]
1547 fn pic_well_formed_status_ok() {
1548 let v = PXPictureValidator::new("##", false);
1549 assert!(v.is_status_ok());
1550 }
1551
1552 /// Object safety: the boxed-trait storage form (`Option<Box<dyn Validator>>`).
1553 #[test]
1554 fn pic_object_safe_as_boxed_trait() {
1555 let v: Box<dyn Validator> = Box::new(PXPictureValidator::new("###", false));
1556 assert!(v.is_valid("123"));
1557 assert!(!v.is_valid("12"));
1558 }
1559
1560 /// Optional group: "#####[-####]" zip+4. Five required digits then an
1561 /// optional `[-####]` (a literal dash plus four required digits):
1562 /// - "12345" → five digits then the optional `[...]` group; the trailing
1563 /// all-optional remainder is skipped → complete.
1564 /// - "12345-678" → the dash plus only three of four required digits → the
1565 /// group is incomplete (not complete).
1566 /// - "12345-6789" → dash + all four digits consumed → complete.
1567 ///
1568 /// NOTE: a 3-digit lead (`"###[-####]"`) only accepts 3 digits or 3-dash-4
1569 /// (8 chars); the 5-digit ZIP (`"#####[-####]"`) is what yields the intended
1570 /// complete/incomplete/complete trio, so that is the mask used here.
1571 #[test]
1572 fn pic_optional_zip_plus_four() {
1573 let v = PXPictureValidator::new("#####[-####]", false);
1574 assert!(v.is_valid("12345")); // optional group skipped → complete
1575 assert!(!v.is_valid("12345-678")); // partial +4 → incomplete
1576 assert!(v.is_valid("12345-6789")); // full +4 → complete
1577 }
1578
1579 /// Literal letter in the mask: the buffer is normalized to the MASK's case,
1580 /// not the typed case. The scanner consumes the mask's literal byte
1581 /// regardless of how it was typed (the match is case-insensitive). Mask
1582 /// "N##", typed "n12" → buffer "N12".
1583 #[test]
1584 fn pic_literal_letter_normalizes_to_mask_case() {
1585 let v = PXPictureValidator::new("N##", false);
1586 let mut s = String::from("n12");
1587 assert!(v.is_valid_input(&mut s, false)); // 'n' matches literal 'N'
1588 assert_eq!(s, "N12"); // consume(pic[index]) writes the mask's 'N'
1589 assert!(v.is_valid("N12")); // exact case also complete
1590 assert!(!v.is_valid("X12")); // wrong literal → not complete
1591 }
1592
1593 /// Comma alternatives — exercises the `skip_to_comma` backtracking path.
1594 ///
1595 /// SEMANTICS (hand-traced, then confirmed empirically against the engine):
1596 /// `process` tries each comma-separated branch in order and returns as soon
1597 /// as one **completes**; the next branch is tried only when the current one
1598 /// errors or is incomplete. Crucially, the outer `picture()` then rejects any
1599 /// run that completed a branch but left input unconsumed (`jndex < len` →
1600 /// prError). So for `"###,#####"` the FIRST branch (`###`) completes on a
1601 /// 3-digit input and a 5-digit input has trailing "45" → prError — the second
1602 /// branch is NOT reached. The alternatives are "either form, but the first
1603 /// matching one wins", not "match the longest".
1604 #[test]
1605 fn pic_comma_alternatives() {
1606 let v = PXPictureValidator::new("###,#####", false);
1607 assert!(v.is_valid("123")); // first branch (3 digits) completes
1608 assert!(!v.is_valid("12345")); // first branch completes, "45" left → error
1609 assert!(!v.is_valid("1234")); // first completes, "4" left → error
1610 assert!(!v.is_valid("12")); // both branches need more → incomplete
1611 // A mask where the SHORT branch can't complete the input falls
1612 // through to the long branch:
1613 let v2 = PXPictureValidator::new("##,####", false);
1614 assert!(v2.is_valid("12")); // first branch (2 digits) completes
1615 assert!(!v2.is_valid("1234")); // first completes, "34" left → error
1616 }
1617
1618 /// `*` iteration operator and `{}` required group — the two most complex arms
1619 /// (`iteration`/`group`). Hand-traced and confirmed empirically:
1620 /// - `"*3#"` (`*` count 3, then `#`) = exactly three digits: "123" complete,
1621 /// "12" incomplete, "1234" error (trailing), "" empty.
1622 /// - `"*#"` (`*` count 0 = greedy "any number") = any run of digits: "12345"
1623 /// complete (greedy consumes all → ambiguous → complete), "1" complete,
1624 /// "" empty.
1625 /// - `"{###}"` (required group of three digits): "123" complete, "12"
1626 /// incomplete, "12a" error.
1627 #[test]
1628 fn pic_iteration_and_group() {
1629 let exact3 = PXPictureValidator::new("*3#", false);
1630 assert!(exact3.is_valid("123")); // counted iteration: 3 digits complete
1631 assert!(!exact3.is_valid("12")); // only 2 → incomplete
1632 assert!(!exact3.is_valid("1234")); // 4th digit trailing → error
1633 assert!(!exact3.is_valid("")); // empty → not complete
1634
1635 let any = PXPictureValidator::new("*#", false);
1636 assert!(any.is_valid("12345")); // greedy iteration → ambiguous → complete
1637 assert!(any.is_valid("1")); // a single digit is complete too
1638 assert!(!any.is_valid("")); // empty → not complete
1639
1640 let grp = PXPictureValidator::new("{###}", false);
1641 assert!(grp.is_valid("123")); // required group satisfied
1642 assert!(!grp.is_valid("12")); // group short → incomplete
1643 assert!(!grp.is_valid("12a")); // 'a' not a digit → error
1644 }
1645
1646 // ── RegexValidator (tvision-rs extension) ──────────────────────────────────────
1647 //
1648 // Golden vectors verified against the working spike implementation.
1649 // If a test disagrees with its comment, the implementation is wrong — do
1650 // not weaken the assertion.
1651
1652 /// SSN pattern `\d{3}-\d{2}-\d{4}` — `is_valid` complete/incomplete/too-long.
1653 #[test]
1654 fn regex_ssn_is_valid() {
1655 let v = RegexValidator::new(r"\d{3}-\d{2}-\d{4}").unwrap();
1656 assert!(v.is_valid("123-45-6789")); // complete
1657 assert!(!v.is_valid("123-45-678")); // incomplete (one digit short)
1658 assert!(!v.is_valid("123-45-67890")); // too long
1659 }
1660
1661 /// SSN pattern — `is_valid_input` viable-prefix test.
1662 #[test]
1663 fn regex_ssn_is_valid_input() {
1664 let v = RegexValidator::new(r"\d{3}-\d{2}-\d{4}").unwrap();
1665 assert!(v.is_valid_input(&mut "123".into(), false)); // viable prefix
1666 assert!(v.is_valid_input(&mut "123-45-678".into(), false)); // one digit still possible
1667 assert!(v.is_valid_input(&mut "123-45-6789".into(), false)); // complete is also viable
1668 assert!(!v.is_valid_input(&mut "123-45-67890".into(), false)); // 5th trailing digit → dead
1669 assert!(!v.is_valid_input(&mut "12a".into(), false)); // letter kills the DFA
1670 }
1671
1672 /// Three-digit pattern `\d{3}` — complete/incomplete/too-long + empty.
1673 #[test]
1674 fn regex_three_digits_is_valid() {
1675 let v = RegexValidator::new(r"\d{3}").unwrap();
1676 assert!(v.is_valid("123")); // complete
1677 assert!(!v.is_valid("12")); // incomplete
1678 assert!(!v.is_valid("1234")); // too long
1679 }
1680
1681 /// Three-digit pattern — `is_valid_input` including empty and 4th-digit dead.
1682 #[test]
1683 fn regex_three_digits_is_valid_input() {
1684 let v = RegexValidator::new(r"\d{3}").unwrap();
1685 assert!(v.is_valid_input(&mut "".into(), false)); // empty: still viable
1686 assert!(v.is_valid_input(&mut "12".into(), false)); // two digits: still viable
1687 assert!(!v.is_valid_input(&mut "1234".into(), false)); // 4th digit → dead
1688 assert!(!v.is_valid_input(&mut "12a".into(), false)); // letter → dead
1689 }
1690
1691 /// `cat|dog` — the whole alternation is anchored at both ends. End-anchoring
1692 /// for `is_valid` comes from the `next_eoi_state`+`is_match_state` step; the
1693 /// `(?:…)` group ensures `\z` binds the *whole* alternation (not just one
1694 /// branch), so neither "cat…" nor "dog…" can pass with trailing input.
1695 #[test]
1696 fn regex_alternation_end_anchored() {
1697 let v = RegexValidator::new(r"cat|dog").unwrap();
1698 assert!(v.is_valid("cat")); // complete
1699 assert!(v.is_valid("dog")); // complete
1700 assert!(!v.is_valid("do")); // incomplete
1701 assert!(!v.is_valid("cats")); // end-anchored: trailing 's' makes it fail
1702 }
1703
1704 /// Paren-injection guard: a pattern that is not self-contained — e.g. an
1705 /// unbalanced `)` that would close the `(?:…)` wrap early and silently
1706 /// defeat end-anchoring — is rejected at construction.
1707 #[test]
1708 fn regex_paren_injection_is_rejected() {
1709 // `cat)|(.*` would build `(?:cat)|(.*)\z`, binding `\z` only to the
1710 // second branch — accepting arbitrary trailing input. Must be Err.
1711 assert!(RegexValidator::new("cat)|(.*").is_err());
1712 assert!(RegexValidator::new(")evil(").is_err());
1713 }
1714
1715 /// `cat|dog` — `is_valid_input` viable prefixes.
1716 #[test]
1717 fn regex_alternation_is_valid_input() {
1718 let v = RegexValidator::new(r"cat|dog").unwrap();
1719 assert!(v.is_valid_input(&mut "c".into(), false)); // prefix of "cat"
1720 assert!(v.is_valid_input(&mut "d".into(), false)); // prefix of "dog"
1721 assert!(v.is_valid_input(&mut "ca".into(), false)); // prefix of "cat"
1722 assert!(!v.is_valid_input(&mut "x".into(), false)); // not a prefix of either
1723 }
1724
1725 /// Start+end anchoring: a valid sub-match that is not at the start/end must fail.
1726 #[test]
1727 fn regex_anchoring_both_ends() {
1728 let v = RegexValidator::new(r"cat").unwrap();
1729 assert!(!v.is_valid("xcat")); // leading 'x' breaks start anchor
1730 assert!(!v.is_valid("catx")); // trailing 'x' breaks end anchor
1731 assert!(!v.is_valid_input(&mut "xc".into(), false)); // 'x' is not a valid prefix
1732 }
1733
1734 /// No-mutation guarantee: `is_valid_input` must not modify the string.
1735 #[test]
1736 fn regex_no_mutation() {
1737 let v = RegexValidator::new(r"\d{3}").unwrap();
1738 let mut s = "12".to_string();
1739 v.is_valid_input(&mut s, false);
1740 assert_eq!(s, "12");
1741 }
1742
1743 /// Invalid pattern returns `Err` rather than panicking.
1744 #[test]
1745 fn regex_invalid_pattern_returns_err() {
1746 assert!(RegexValidator::new("(").is_err()); // unbalanced paren
1747 }
1748
1749 /// Object safety: `RegexValidator` is storable as `Box<dyn Validator>`.
1750 #[test]
1751 fn regex_object_safe() {
1752 let v: Box<dyn Validator> = Box::new(RegexValidator::new(r"\d+").unwrap());
1753 assert!(v.is_valid("42"));
1754 assert!(!v.is_valid("4x"));
1755 }
1756
1757 /// `is_status_ok` uses the trait default (true) — construction failure is
1758 /// reported via `Err`, not a bad status on a successfully-built validator.
1759 #[test]
1760 fn regex_status_ok_after_successful_construction() {
1761 let v = RegexValidator::new(r"\d+").unwrap();
1762 assert!(v.is_status_ok());
1763 }
1764}