rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! The input grammars a single-line text field can enforce.
//!
//! # Why this is its own module
//!
//! It is a *rule*, not a widget: two functions over a string (`filter` for the characters a
//! grammar cannot represent, `check` for whether a value satisfies it) plus the message shown
//! when it does not. `LineEdit` is already the crate's largest control; keeping the grammar
//! beside it would make the field the home of both the editing machinery and the validation
//! vocabulary, and every future grammar would grow the same file.
//!
//! # Why the grammar lives on the field rather than in a wrapper
//!
//! `phone_input` / `email_input` are the same control with a different accepted alphabet and
//! validity rule: a wrapper widget would have to duplicate the caret, selection, undo, IME and
//! decoration machinery to filter what reaches the model. The field owns the one insertion path
//! (`LineEdit::insert_str`) and the one assignment path (`LineEdit::set_text`), so the rule
//! belongs there. A plain `line_edit` carries no validator and reports itself valid.

use crate::compat::{Box, Cow, String, ToString, Vec};

/// The three-way outcome of validating a value.
///
/// A boolean cannot describe the ordinary state of a field the user is still filling in: a
/// partially typed number is neither acceptable nor wrong, and painting it red while the user
/// types turns every entry into an error message. The third state is what lets a form keep its
/// submit affordance disabled without accusing the value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValidationState {
    /// The value cannot be made acceptable by further typing (for example, out of range).
    Invalid,
    /// The value is incomplete but not yet wrong (for example, a lone `-` in a number field).
    #[default]
    Intermediate,
    /// The value satisfies the rule.
    Acceptable,
}

impl ValidationState {
    /// Whether the value satisfies the rule.
    pub fn is_acceptable(self) -> bool {
        matches!(self, Self::Acceptable)
    }

    /// Whether the value is definitely wrong (as opposed to merely incomplete).
    pub fn is_invalid(self) -> bool {
        matches!(self, Self::Invalid)
    }
}

/// A rule a text field can consult while the value changes.
///
/// # Why a trait rather than a closed enum
///
/// The two shipped grammars (phone and e-mail) answered a boolean question for one widget. A
/// host that owns a domain type — an order code, a range, a product identifier — has a rule the
/// library cannot enumerate, and wrapping the field was not an option: the wrapper would have to
/// reimplement the caret, selection, undo, IME and validation plumbing to filter what reaches the
/// model. The trait is the extension point the field consults, and the shipped grammars implement
/// it too, so there is one validation vocabulary rather than two.
///
/// Implementations must be deterministic and free of interior mutability: the field may call
/// [`Validator::state`] for every keystroke.
pub trait Validator: core::fmt::Debug + Send + Sync {
    /// The outcome for `text`.
    fn state(&self, text: &str) -> ValidationState;

    /// The message shown when [`Validator::state`] is not [`ValidationState::Acceptable`].
    fn message(&self) -> &'static str;

    /// The message for `text`, which may quote the value that was refused.
    ///
    /// [`Validator::message`] is a static sentence, so a host rule could not say *which* value
    /// was out of range and the field's error row could only show a generic hint (I-27). A rule
    /// that has nothing value-specific to say inherits the static message, so this is an optional
    /// refinement rather than a second required method.
    fn message_for(&self, _text: &str) -> Cow<'_, str> {
        Cow::Borrowed(self.message())
    }

    /// The nearest acceptable value, when the rule can repair one.
    ///
    /// `None` means the value cannot be repaired without asking the user. The default is
    /// `None`, so a rule that has nothing sensible to offer does not have to say so.
    fn fixup(&self, _text: &str) -> Option<String> {
        None
    }

    /// Drops the characters the rule cannot represent from incoming text.
    ///
    /// The default keeps everything, which is right for a rule that constrains shape rather
    /// than alphabet (a range or a pattern).
    fn filter(&self, text: &str) -> String {
        text.to_string()
    }

    /// The shipped grammar this rule is, when it is one of them.
    ///
    /// A field uses this to keep assignment idempotent without downcasting: re-assigning the
    /// grammar it already holds must not revalidate and repaint. A host rule reports `None`
    /// and is therefore always applied.
    fn builtin(&self) -> Option<InputValidator> {
        None
    }
}

/// An input grammar a text field enforces as the user types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputValidator {
    /// A phone number: only digits and the separators `+ - ( ) space` are accepted,
    /// and a non-empty value must hold between 7 and 15 digits (the E.164 span).
    Phone,
    /// An e-mail address: whitespace and control characters are refused, and a
    /// non-empty value must be `local@domain` with a non-empty domain containing a
    /// dot, a non-empty local part, and at most 254 characters overall.
    Email,
}

impl InputValidator {
    /// Drops the characters this grammar cannot represent from incoming text.
    ///
    /// A phone number never starts or ends with its own separator, so a filtered edge space —
    /// the trace of a dropped word like "call " — is trimmed rather than kept as a leading gap.
    pub(crate) fn filter(self, text: &str) -> crate::compat::String {
        match self {
            Self::Phone => text
                .chars()
                .filter(|ch| ch.is_ascii_digit() || matches!(ch, '+' | '-' | ' ' | '(' | ')'))
                .collect::<crate::compat::String>()
                .trim()
                .chars()
                .collect(),
            Self::Email => {
                text.chars().filter(|ch| !ch.is_whitespace() && !ch.is_control()).collect()
            }
        }
    }

    /// Whether `text` satisfies the grammar, and the message to show when it does not.
    ///
    /// An **empty** value is valid for both grammars: "nothing typed yet" is not a
    /// misspelling, and a field that reports an error before the user has typed is noise.
    /// A caller that requires a value enforces that with its own rule (the `required`
    /// idiom belongs to the form, not to the field's character grammar).
    pub(crate) fn check(self, text: &str) -> (bool, &'static str) {
        if text.is_empty() {
            return (true, "");
        }
        match self {
            Self::Phone => {
                let digits = text.chars().filter(|ch| ch.is_ascii_digit()).count();
                if (7..=15).contains(&digits) {
                    (true, "")
                } else {
                    (false, "Enter a phone number (7 to 15 digits)")
                }
            }
            Self::Email => {
                let mut parts = text.split('@');
                let local = parts.next().unwrap_or_default();
                let domain = parts.next().unwrap_or_default();
                let single_at = parts.next().is_none();
                let domain_valid = !domain.is_empty()
                    && domain.contains('.')
                    && domain.split('.').all(|label| !label.is_empty());
                if single_at && !local.is_empty() && domain_valid && text.len() <= 254 {
                    (true, "")
                } else {
                    (false, "Enter an e-mail address (name@domain.com)")
                }
            }
        }
    }

    /// Repairs the value when the grammar has an unambiguous nearest form.
    ///
    /// A phone number is the one repairable grammar: separators at either edge are the trace of a
    /// word that happened to accompany the number (`"call 555-0100 "`), so trimming them yields
    /// the number the user meant. An e-mail address has no such rule — `name@domain` cannot be
    /// guessed into a top-level label — so it is returned unchanged and reported unrepairable.
    pub fn fixup(self, text: &str) -> Option<String> {
        match self {
            Self::Phone => {
                let trimmed =
                    text.trim_matches(|ch: char| matches!(ch, '+' | '-' | ' ' | '(' | ')'));
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_string())
                }
            }
            Self::Email => None,
        }
    }
}

impl Validator for InputValidator {
    /// The bool rule mapped onto the three states.
    ///
    /// Both shipped grammars have no meaningful intermediate state: an empty value is accepted
    /// ("nothing typed yet" is not a misspelling) and anything else is either a complete value or
    /// a wrong one. A grammar with a prefix notion can report `Intermediate` instead.
    fn state(&self, text: &str) -> ValidationState {
        if self.check(text).0 {
            ValidationState::Acceptable
        } else {
            ValidationState::Invalid
        }
    }

    fn message(&self) -> &'static str {
        match self {
            Self::Phone => "Enter a phone number (7 to 15 digits)",
            Self::Email => "Enter an e-mail address (name@domain.com)",
        }
    }

    fn fixup(&self, text: &str) -> Option<String> {
        (*self).fixup(text)
    }

    fn filter(&self, text: &str) -> String {
        (*self).filter(text)
    }

    fn builtin(&self) -> Option<InputValidator> {
        Some(*self)
    }
}

/// A numeric range rule for a text field.
///
/// The range spans are carried as `i64`/`f64` because that is what a field parses; a caller with a
/// larger domain type can implement [`Validator`] itself.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RangeValidator {
    /// An integer between `minimum` and `maximum`, inclusive.
    Int {
        /// The lowest accepted value.
        minimum: i64,
        /// The highest accepted value.
        maximum: i64,
    },
    /// A finite decimal between `minimum` and `maximum`, inclusive.
    Double {
        /// The lowest accepted value.
        minimum: f64,
        /// The highest accepted value.
        maximum: f64,
    },
}

impl RangeValidator {
    /// Creates an inclusive integer range rule.
    pub fn int(minimum: i64, maximum: i64) -> Self {
        Self::Int { minimum: minimum.min(maximum), maximum: maximum.max(minimum) }
    }

    /// Creates an inclusive decimal range rule.
    pub fn double(minimum: f64, maximum: f64) -> Self {
        Self::Double { minimum: minimum.min(maximum), maximum: maximum.max(minimum) }
    }

    /// The message for this rule.
    fn range_message(self) -> &'static str {
        match self {
            Self::Int { .. } => "Enter a whole number in range",
            Self::Double { .. } => "Enter a number in range",
        }
    }
}

impl Validator for RangeValidator {
    /// Parses the value and compares it with the bounds.
    ///
    /// An empty value is intermediate (a form may still be filled in), an unparsable non-empty
    /// value is intermediate as well — the user may be halfway through `-` or `1.` — and only a
    /// parsed value outside the bounds is definitely invalid. That distinction is what keeps a
    /// spinner from colouring the field red while the sign key is still the only thing typed.
    fn state(&self, text: &str) -> ValidationState {
        if text.is_empty() {
            return ValidationState::Intermediate;
        }
        match self {
            Self::Int { minimum, maximum } => match text.trim().parse::<i64>() {
                Ok(value) if (*minimum..=*maximum).contains(&value) => ValidationState::Acceptable,
                Ok(_) => ValidationState::Invalid,
                Err(_) => ValidationState::Intermediate,
            },
            Self::Double { minimum, maximum } => match text.trim().parse::<f64>() {
                Ok(value) if value.is_finite() && (*minimum..=*maximum).contains(&value) => {
                    ValidationState::Acceptable
                }
                Ok(value) if value.is_finite() => ValidationState::Invalid,
                _ => ValidationState::Intermediate,
            },
        }
    }

    fn message(&self) -> &'static str {
        self.range_message()
    }

    /// Names the bound and the refused value, so the field's error row can say *why* it refused
    /// rather than repeating "in range" (I-27).
    fn message_for(&self, text: &str) -> Cow<'_, str> {
        let trimmed = text.trim();
        match self {
            Self::Int { minimum, maximum } => match trimmed.parse::<i64>() {
                Ok(value) if !(*minimum..=*maximum).contains(&value) => {
                    Cow::Owned(format!("{value} is outside {minimum}..={maximum}"))
                }
                _ => Cow::Borrowed(self.range_message()),
            },
            Self::Double { minimum, maximum } => match trimmed.parse::<f64>() {
                Ok(value) if value.is_finite() && !(*minimum..=*maximum).contains(&value) => {
                    Cow::Owned(format!("{value} is outside {minimum}..={maximum}"))
                }
                _ => Cow::Borrowed(self.range_message()),
            },
        }
    }

    /// Clamps a parsable value into the range; an unparsable value is not repairable.
    fn fixup(&self, text: &str) -> Option<String> {
        match self {
            Self::Int { minimum, maximum } => text
                .trim()
                .parse::<i64>()
                .ok()
                .map(|value| value.clamp(*minimum, *maximum).to_string()),
            Self::Double { minimum, maximum } => text
                .trim()
                .parse::<f64>()
                .ok()
                .filter(|value| value.is_finite())
                .map(|value| value.clamp(*minimum, *maximum).to_string()),
        }
    }
}

/// A small regular-expression rule.
///
/// # Supported syntax
///
/// The engine is deliberately a **subset** rather than a full regular-expression
/// implementation, because the crate has no regex dependency and the validation use case is
/// shape checking, not text processing. It supports:
///
/// * literal characters and `\` escapes;
/// * `.` for any character;
/// * character classes `[abc]`, ranges `[a-z]`, and their negation `[^abc]`;
/// * groupings `(...)` and alternation `a|b|c`, nested to any depth (I-05);
/// * the quantifiers `*`, `+` and `?` on the preceding atom or group;
/// * the anchors `^` (start) and `$` (end), at the top level.
///
/// Back-references and look-around are **not** supported; an unsupported construct is matched
/// literally, so a caller who needs it must use a full engine through the [`Validator`] trait
/// instead of being silently given the wrong answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatternValidator {
    pattern: String,
    message: &'static str,
}

impl PatternValidator {
    /// Creates a pattern rule with the message shown when the value does not match.
    pub fn new(pattern: impl Into<String>, message: &'static str) -> Self {
        Self { pattern: pattern.into(), message }
    }

    /// The pattern this rule matches.
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Whether `text` matches the pattern.
    pub fn is_match(&self, text: &str) -> bool {
        match CompiledPattern::compile(&self.pattern) {
            Some(compiled) => compiled.is_match(text),
            None => false,
        }
    }
}

impl Validator for PatternValidator {
    /// An empty value is intermediate; a non-matching value is invalid.
    fn state(&self, text: &str) -> ValidationState {
        if text.is_empty() {
            ValidationState::Intermediate
        } else if self.is_match(text) {
            ValidationState::Acceptable
        } else {
            ValidationState::Invalid
        }
    }

    fn message(&self) -> &'static str {
        self.message
    }
}

/// One node of a compiled pattern.
///
/// The engine used to be a flat atom list, which could not express grouping or alternation at
/// all: `"A|B"` was matched as the five characters it is spelled with, so the commonest
/// completion filter a host writes silently never matched (I-05). A tree of sequences,
/// alternations and repetitions is the smallest shape that supports both constructs while the
/// rest of the grammar (classes, quantifiers, anchors) is unchanged.
#[derive(Debug, Clone)]
enum Node {
    /// One matcher with its repetition span.
    Atom { kind: AtomKind, min: usize, max: Option<usize> },
    /// A parenthesised sequence, matched as a unit so a quantifier can repeat all of it.
    Group(Vec<Node>),
    /// An alternation of sequences, `a|b|c`.
    Alt(Vec<Vec<Node>>),
    /// A node repeated a bounded number of times — a quantified group.
    Repeat { node: Box<Node>, min: usize, max: Option<usize> },
}

/// What one pattern position accepts.
#[derive(Debug, Clone)]
enum AtomKind {
    /// Any character.
    Any,
    /// One literal character.
    Literal(char),
    /// A member of a class, optionally negated.
    Class { negated: bool, members: Vec<(char, char)> },
}

impl AtomKind {
    fn matches(&self, ch: char) -> bool {
        match self {
            Self::Any => true,
            Self::Literal(literal) => *literal == ch,
            Self::Class { negated, members } => {
                let inside = members.iter().any(|(lo, hi)| (*lo..=*hi).contains(&ch));
                inside != *negated
            }
        }
    }
}

/// A pattern compiled once and matched against many candidates.
///
/// Compiling a pattern is the one part of matching that does not depend on the candidate, and the
/// completion filter used to pay it once per candidate per keystroke (I-P05). A caller that
/// matches a list against one pattern compiles it once here and reuses it.
#[derive(Debug, Clone)]
pub(crate) struct CompiledPattern {
    anchored_start: bool,
    anchored_end: bool,
    nodes: Vec<Node>,
}

impl CompiledPattern {
    /// Compiles `pattern`, or returns `None` when it is malformed.
    pub(crate) fn compile(pattern: &str) -> Option<Self> {
        let chars: Vec<char> = pattern.chars().collect();
        let anchored_start = chars.first() == Some(&'^');
        let start = if anchored_start { 1 } else { 0 };
        let anchored_end = chars.len() > start && chars.last() == Some(&'$');
        let limit = if anchored_end { chars.len() - 1 } else { chars.len() };
        let (branches, next) = parse_alternation(&chars, start, limit)?;
        // A `)` with no opening `(` is a malformed pattern rather than a literal.
        if next < limit {
            return None;
        }
        Some(Self { anchored_start, anchored_end, nodes: collapse(branches) })
    }

    /// Whether `text` matches.
    pub(crate) fn is_match(&self, text: &str) -> bool {
        let chars: Vec<char> = text.chars().collect();
        self.matches_chars(&chars)
    }

    /// Whether the character slice matches, with the same unanchored semantics as before.
    fn matches_chars(&self, text: &[char]) -> bool {
        if self.anchored_start {
            return accepts(&self.nodes, text, 0, self.anchored_end);
        }
        (0..=text.len()).any(|start| accepts(&self.nodes, text, start, self.anchored_end))
    }
}

/// Collapses a one-branch alternation to its sequence, keeping the branch list otherwise.
fn collapse(mut branches: Vec<Vec<Node>>) -> Vec<Node> {
    if branches.len() == 1 {
        branches.pop().unwrap_or_default()
    } else {
        vec![Node::Alt(branches)]
    }
}

/// Parses `a|b|c` from `index`, stopping at `)` or `limit`.
fn parse_alternation(
    chars: &[char],
    start: usize,
    limit: usize,
) -> Option<(Vec<Vec<Node>>, usize)> {
    let mut branches = Vec::new();
    let mut index = start;
    loop {
        let (sequence, next) = parse_sequence(chars, index, limit)?;
        branches.push(sequence);
        index = next;
        if index < limit && chars.get(index) == Some(&'|') {
            index += 1;
            continue;
        }
        return Some((branches, index));
    }
}

/// Parses atoms until `|`, `)` or `limit`.
fn parse_sequence(chars: &[char], mut index: usize, limit: usize) -> Option<(Vec<Node>, usize)> {
    let mut nodes = Vec::new();
    while index < limit {
        if matches!(chars[index], '|' | ')') {
            break;
        }
        let (node, next) = parse_node(chars, index, limit)?;
        nodes.push(node);
        index = next;
    }
    Some((nodes, index))
}

/// Parses one atom, class or group plus the quantifier that follows it.
fn parse_node(chars: &[char], index: usize, limit: usize) -> Option<(Node, usize)> {
    let ch = chars[index];
    let mut next = index;
    let base = match ch {
        '.' => {
            next += 1;
            Node::Atom { kind: AtomKind::Any, min: 1, max: Some(1) }
        }
        '\\' => {
            next += 1;
            let escaped = *chars.get(next)?;
            next += 1;
            Node::Atom { kind: AtomKind::Literal(escaped), min: 1, max: Some(1) }
        }
        '[' => {
            let (kind, after) = compile_class(chars, index)?;
            next = after;
            Node::Atom { kind, min: 1, max: Some(1) }
        }
        '(' => {
            let (branches, after) = parse_alternation(chars, index + 1, limit)?;
            if chars.get(after) != Some(&')') {
                return None;
            }
            next = after + 1;
            Node::Group(collapse(branches))
        }
        _ => {
            next += 1;
            Node::Atom { kind: AtomKind::Literal(ch), min: 1, max: Some(1) }
        }
    };
    if next >= limit {
        return Some((base, next));
    }
    let (min, max) = match chars[next] {
        '*' => (0, None),
        '+' => (1, None),
        '?' => (0, Some(1)),
        _ => return Some((base, next)),
    };
    let node = match base {
        Node::Atom { kind, .. } => Node::Atom { kind, min, max },
        other => Node::Repeat { node: Box::new(other), min, max },
    };
    Some((node, next + 1))
}

/// Compiles one `[...]` class starting at `start`, returning it and the index after `]`.
fn compile_class(chars: &[char], start: usize) -> Option<(AtomKind, usize)> {
    let mut index = start + 1;
    let mut negated = false;
    if chars.get(index) == Some(&'^') {
        negated = true;
        index += 1;
    }
    let mut members: Vec<(char, char)> = Vec::new();
    let mut first = true;
    while index < chars.len() {
        let ch = chars[index];
        if ch == ']' && !first {
            return Some((AtomKind::Class { negated, members }, index + 1));
        }
        first = false;
        let lo = if ch == '\\' {
            index += 1;
            *chars.get(index)?
        } else {
            ch
        };
        index += 1;
        // A `-` followed by a member and then `]` is a literal hyphen.
        if chars.get(index) == Some(&'-') && chars.get(index + 1).is_some_and(|next| *next != ']') {
            index += 1;
            let hi_raw = chars.get(index).copied()?;
            let hi = if hi_raw == '\\' {
                index += 1;
                *chars.get(index)?
            } else {
                hi_raw
            };
            index += 1;
            members.push((lo.min(hi), lo.max(hi)));
        } else {
            members.push((lo, lo));
        }
    }
    None
}

/// Whether `nodes` can consume `text` from `position` and reach an accepted end.
fn accepts(nodes: &[Node], text: &[char], position: usize, anchored_end: bool) -> bool {
    ends_of(nodes, text, position).into_iter().any(|end| !anchored_end || end == text.len())
}

/// Every position `nodes` can reach from `position`, longest match first.
fn ends_of(nodes: &[Node], text: &[char], position: usize) -> Vec<usize> {
    let mut reached = vec![position];
    for node in nodes {
        let mut next: Vec<usize> = Vec::new();
        for pos in reached {
            for end in node_ends(node, text, pos) {
                if !next.contains(&end) {
                    next.push(end);
                }
            }
        }
        if next.is_empty() {
            return next;
        }
        reached = next;
    }
    reached
}

/// Every position `node` can reach from `position`, longest (greediest) first.
fn node_ends(node: &Node, text: &[char], position: usize) -> Vec<usize> {
    match node {
        Node::Atom { kind, min, max } => {
            let mut ends = Vec::new();
            if *min == 0 {
                ends.push(position);
            }
            let mut count = 0usize;
            let mut pos = position;
            let limit = max.unwrap_or(text.len().saturating_add(1));
            while count < limit && pos < text.len() && kind.matches(text[pos]) {
                pos += 1;
                count += 1;
                if count >= *min {
                    ends.push(pos);
                }
            }
            // Greedy, then backtrack: try the longest repetition first so `.*x` matches
            // the last `x`.
            ends.reverse();
            ends
        }
        Node::Group(nodes) => ends_of(nodes, text, position),
        Node::Alt(branches) => {
            let mut ends = Vec::new();
            for branch in branches {
                for end in ends_of(branch, text, position) {
                    if !ends.contains(&end) {
                        ends.push(end);
                    }
                }
            }
            ends
        }
        Node::Repeat { node, min, max } => {
            let mut ends = Vec::new();
            if *min == 0 {
                ends.push(position);
            }
            let max_count = max.unwrap_or(text.len().saturating_add(1));
            let mut frontier = vec![position];
            let mut count = 0usize;
            while count < max_count && !frontier.is_empty() {
                let mut next: Vec<usize> = Vec::new();
                for pos in frontier {
                    for end in node_ends(node, text, pos) {
                        // A repetition that does not advance would loop forever; only a step
                        // that consumes input counts as a repetition.
                        if end > pos && !next.contains(&end) {
                            next.push(end);
                        }
                    }
                }
                count += 1;
                for pos in &next {
                    if count >= *min && !ends.contains(pos) {
                        ends.push(*pos);
                    }
                }
                frontier = next;
            }
            ends.reverse();
            ends
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_phone_grammar_keeps_only_its_own_characters() {
        assert_eq!(InputValidator::Phone.filter("call +1 (555) 010-9999!"), "+1 (555) 010-9999");
        assert_eq!(InputValidator::Phone.filter("abc"), "");
    }

    #[test]
    fn an_empty_value_is_valid_for_both_grammars() {
        assert_eq!(InputValidator::Phone.check(""), (true, ""));
        assert_eq!(InputValidator::Email.check(""), (true, ""));
    }

    #[test]
    fn the_phone_grammar_measures_digits_not_characters() {
        assert!(InputValidator::Phone.check("1234567").0);
        assert!(InputValidator::Phone.check("+1 (555) 010-9999").0);
        assert!(!InputValidator::Phone.check("123456").0, "six digits is too short");
        assert!(!InputValidator::Phone.check("1234567890123456").0, "sixteen is too long");
    }

    #[test]
    fn the_email_grammar_requires_one_at_and_a_dotted_domain() {
        assert!(InputValidator::Email.check("name@domain.com").0);
        assert!(!InputValidator::Email.check("name@domain").0, "no top-level label");
        assert!(!InputValidator::Email.check("@domain.com").0, "no local part");
        assert!(!InputValidator::Email.check("a@b@c.com").0, "two at signs");
        assert!(!InputValidator::Email.check("name@.com").0, "an empty label");
    }

    #[test]
    fn the_email_grammar_refuses_whitespace_and_control_characters() {
        assert_eq!(InputValidator::Email.filter("a b\tc"), "abc");
        assert_eq!(InputValidator::Email.filter("name@domain.com"), "name@domain.com");
    }

    #[test]
    fn a_message_is_carried_only_when_the_value_is_refused() {
        assert_eq!(InputValidator::Phone.check("12").1, "Enter a phone number (7 to 15 digits)");
        assert_eq!(InputValidator::Email.check("x").1, "Enter an e-mail address (name@domain.com)");
    }

    #[test]
    fn the_grammars_report_the_three_way_state() {
        assert_eq!(InputValidator::Phone.state(""), ValidationState::Acceptable);
        assert_eq!(InputValidator::Phone.state("1234567"), ValidationState::Acceptable);
        assert_eq!(InputValidator::Email.state("not-an-address"), ValidationState::Invalid);
        assert!(!ValidationState::Intermediate.is_acceptable());
        assert!(!ValidationState::Intermediate.is_invalid());
    }

    #[test]
    fn the_phone_grammar_repairs_its_own_edge_separators() {
        assert_eq!(InputValidator::Phone.fixup(" 555-0100 "), Some("555-0100".to_string()));
        assert_eq!(InputValidator::Phone.fixup("---"), None);
        assert_eq!(InputValidator::Email.fixup("name@domain.com"), None);
    }

    #[test]
    fn a_range_rule_separates_incomplete_from_out_of_range() {
        let range = RangeValidator::int(1, 10);
        assert_eq!(range.state(""), ValidationState::Intermediate);
        assert_eq!(range.state("-"), ValidationState::Intermediate);
        assert_eq!(range.state("11"), ValidationState::Invalid);
        assert_eq!(range.state("5"), ValidationState::Acceptable);
        assert_eq!(range.fixup("42"), Some("10".to_string()));
    }

    #[test]
    fn a_double_range_rule_accepts_decimals_and_refuses_non_finite_values() {
        let range = RangeValidator::double(0.0, 1.0);
        assert_eq!(range.state("0.5"), ValidationState::Acceptable);
        assert_eq!(range.state("1.5"), ValidationState::Invalid);
        assert_eq!(range.state("NaN"), ValidationState::Intermediate);
        assert_eq!(range.fixup("1.5"), Some("1".to_string()));
    }

    #[test]
    fn a_pattern_rule_supports_anchors_classes_and_quantifiers() {
        let code = PatternValidator::new("^[A-Z]{0}", "bad code");
        // `{0}` is not part of the subset, so it is matched literally and this value fails.
        assert_eq!(code.state("ABC"), ValidationState::Invalid);

        let digits = PatternValidator::new("^[0-9]+$", "digits only");
        assert!(digits.is_match("0123"));
        assert!(!digits.is_match("0123a"));
        assert_eq!(digits.state(""), ValidationState::Intermediate);
        assert_eq!(digits.state("12"), ValidationState::Acceptable);

        let name = PatternValidator::new("[a-z]+\\.[a-z]+", "name.ext");
        assert!(name.is_match("report.txt"));
        assert!(!name.is_match("report"));
        assert_eq!(name.message(), "name.ext");
    }

    #[test]
    fn a_validator_can_be_used_behind_the_trait() {
        let rule: &dyn Validator = &RangeValidator::int(0, 3);
        assert!(rule.state("2").is_acceptable());
        assert_eq!(rule.filter(" anything "), " anything ");
    }

    #[test]
    fn a_pattern_supports_groups_and_alternation() {
        // The constructs `"A|B"` needs, which the flat-atom engine could not express (I-05).
        let images = PatternValidator::new("^(png|jpg|webp)$", "image extension");
        assert!(images.is_match("png"));
        assert!(images.is_match("jpg"));
        assert!(images.is_match("webp"));
        assert!(!images.is_match("gif"));
        assert!(!images.is_match("pngjpg"), "the anchors apply to the whole alternation");

        // A quantified group repeats the whole sequence rather than its last atom.
        let pairs = PatternValidator::new("^(ab)+$", "pairs");
        assert!(pairs.is_match("ab"));
        assert!(pairs.is_match("abab"));
        assert!(!pairs.is_match("a"));
        assert!(!pairs.is_match("aba"));

        // Groups nest.
        let nested = PatternValidator::new("^((a|b)c)+$", "nested");
        assert!(nested.is_match("acbc"));
        assert!(!nested.is_match("acb"));
    }

    #[test]
    fn a_compiled_pattern_matches_many_values() {
        let compiled = CompiledPattern::compile("a|b").expect("a valid pattern");
        assert!(compiled.is_match("a") && compiled.is_match("b"));
        assert!(!compiled.is_match("c"));
        // A malformed pattern is refused rather than matched as literals.
        assert!(CompiledPattern::compile("(a").is_none());
    }

    #[test]
    fn a_range_message_names_the_bound_and_the_refused_value() {
        // The static message is still available, and the value-specific one refines it (I-27).
        let range = RangeValidator::int(1, 100);
        assert_eq!(range.message(), "Enter a whole number in range");
        assert_eq!(range.message_for("999"), "999 is outside 1..=100");
        // A rule with nothing value-specific to say keeps the static sentence.
        assert_eq!(range.message_for("50"), "Enter a whole number in range");
        let builtin: &dyn Validator = &InputValidator::Phone;
        assert_eq!(builtin.message_for("12"), builtin.message());
    }
}