ac-algorithm 0.2.0

Algorithm competition domain logic for ac
Documentation
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
//! Generation-spec parsing: the problem's input-format block and
//! constraint lines become a [`GenSpec`] (spike #6 §2.3–§2.4).
//!
//! Only the Level-1 subset is recognized: integer scalars and
//! one-dimensional integer arrays. Anything that cannot be proven to
//! yield valid input — multi-dimensional arrays, strings, permutations,
//! strict inequalities, unparseable constraint expressions — marks the
//! spec [`SpecError::Unsupported`] and generation is skipped entirely.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

/// JavaScript `Number.MAX_SAFE_INTEGER`; ac-test evaluated constraint
/// expressions as safe integers only.
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;

/// Why a spec cannot drive generation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SpecError {
    /// The input format or a constraint line is outside the Level-1
    /// subset; generation must be skipped conservatively.
    Unsupported(String),
}

impl fmt::Display for SpecError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsupported(reason) => write!(f, "generation spec unsupported: {reason}"),
        }
    }
}

impl std::error::Error for SpecError {}

/// One recognized input-format line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FormatLine {
    /// Scalar variables emitted space-separated on one line.
    Scalars(Vec<String>),
    /// One-dimensional integer array `A_1 A_2 ... A_<length_var>`.
    /// `name` is the element base (`A` for `A_i`-style constraints).
    Array {
        /// Element base name (`A` in `A_i`).
        name: String,
        /// Scalar variable that determines the element count.
        length_var: String,
    },
}

/// Parsed input-format block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InputFormat {
    /// Format lines in document order.
    pub lines: Vec<FormatLine>,
    /// Declared scalar variable names.
    scalars: BTreeSet<String>,
    /// Declared array element base names.
    arrays: BTreeSet<String>,
}

impl InputFormat {
    /// Parses the `<pre>` text of the problem's Input section.
    ///
    /// # Errors
    ///
    /// [`SpecError::Unsupported`] when any non-empty line is neither an
    /// all-identifier scalar line nor a recognized 1-D array line.
    pub fn parse(text: &str) -> Result<Self, SpecError> {
        let mut format = Self::default();
        for raw in text.lines() {
            let normalized = normalize_markup(raw);
            let tokens: Vec<&str> = normalized.split_whitespace().collect();
            if tokens.is_empty() {
                continue;
            }
            let line = if tokens.contains(&"...") {
                parse_array_line(&tokens)?
            } else if tokens.iter().all(|t| is_ident(t)) {
                for name in &tokens {
                    if !format.scalars.insert((*name).to_owned()) {
                        return Err(SpecError::Unsupported(format!(
                            "duplicate scalar variable `{name}`"
                        )));
                    }
                }
                FormatLine::Scalars(tokens.iter().map(|t| (*t).to_owned()).collect())
            } else {
                return Err(SpecError::Unsupported(format!(
                    "unrecognized input-format line: {}",
                    raw.trim()
                )));
            };
            if let FormatLine::Array { name, .. } = &line {
                if format.arrays.contains(name) {
                    return Err(SpecError::Unsupported(format!(
                        "duplicate array variable `{name}`"
                    )));
                }
                format.arrays.insert(name.clone());
            }
            format.lines.push(line);
        }
        if format.lines.is_empty() {
            return Err(SpecError::Unsupported(
                "input format block is empty".to_owned(),
            ));
        }
        Ok(format)
    }

    /// `true` when `name` is a declared scalar variable.
    fn is_scalar(&self, name: &str) -> bool {
        self.scalars.contains(name)
    }

    /// Array element base for `name` (`A_i` → `A`), when `name` is not
    /// itself a scalar.
    fn element_base(&self, name: &str) -> Option<String> {
        let (base, _index) = name.rsplit_once('_')?;
        self.arrays.contains(base).then(|| base.to_owned())
    }

    /// All declared scalar names (for spec validation).
    pub(crate) fn scalar_names(&self) -> impl Iterator<Item = &String> {
        self.scalars.iter()
    }

    /// Array declarations `(element base, length var)` in line order.
    pub(crate) fn array_decls(&self) -> Vec<(String, String)> {
        self.lines
            .iter()
            .filter_map(|line| match line {
                FormatLine::Array {
                    name, length_var, ..
                } => Some((name.clone(), length_var.clone())),
                FormatLine::Scalars(_) => None,
            })
            .collect()
    }
}

/// Recognizes `X_1 X_2 ... X_<len>` array lines.
fn parse_array_line(tokens: &[&str]) -> Result<FormatLine, SpecError> {
    let unsupported = || {
        SpecError::Unsupported(format!(
            "unrecognized input-format line: {}",
            tokens.join(" ")
        ))
    };
    let ellipsis = tokens
        .iter()
        .position(|t| *t == "...")
        .ok_or_else(unsupported)?;
    if tokens.iter().filter(|t| **t == "...").count() != 1
        || ellipsis == 0
        || ellipsis + 1 != tokens.len() - 1
    {
        return Err(unsupported());
    }
    let before = &tokens[..ellipsis];
    let after = tokens[ellipsis + 1];
    // Every token must be `BASE_<suffix>` with one shared base; the
    // after-ellipsis token's suffix is the length variable.
    let mut base: Option<&str> = None;
    for token in before.iter().chain(std::iter::once(&after)) {
        let Some((token_base, suffix)) = token.rsplit_once('_') else {
            return Err(unsupported());
        };
        if suffix.is_empty()
            || !suffix
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            return Err(unsupported());
        }
        match base {
            None => base = Some(token_base),
            Some(existing) if existing != token_base => return Err(unsupported()),
            _ => {}
        }
    }
    let base = base.ok_or_else(unsupported)?;
    if !is_ident(base) {
        return Err(unsupported());
    }
    let Some((_, length_var)) = after.rsplit_once('_') else {
        return Err(unsupported());
    };
    if !is_ident(length_var) {
        return Err(unsupported());
    }
    Ok(FormatLine::Array {
        name: base.to_owned(),
        length_var: length_var.to_owned(),
    })
}

/// `true` for `[A-Za-z][A-Za-z0-9_]*` (ac-test's identifier rule).
fn is_ident(text: &str) -> bool {
    let mut chars = text.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// What a constraint line bounds.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum VarKey {
    /// A declared scalar variable.
    Scalar(String),
    /// Elements of a declared array (`A` bounds `A_i`, `A_1`, …).
    Element(String),
    /// Anything else (index variables, prose) — ignored.
    Other(String),
}

/// Lower/upper bound expressions for one variable. Multiple
/// constraints on the same variable accumulate; generation takes the
/// tightest resolved bound.
#[derive(Clone, Debug, Default)]
pub struct VarBounds {
    /// Lower-bound expressions (`l <= X`).
    pub lowers: Vec<Expr>,
    /// Upper-bound expressions (`X <= r`).
    pub uppers: Vec<Expr>,
}

/// A parsed safe-integer expression. Variables resolve against the
/// scalar values chosen earlier in generation order.
#[derive(Clone, Debug, PartialEq)]
pub enum Expr {
    /// Integer literal.
    Int(i64),
    /// Variable reference (scalar name).
    Var(String),
    /// `-e`.
    Neg(Box<Expr>),
    /// `a + b`.
    Add(Box<Expr>, Box<Expr>),
    /// `a - b`.
    Sub(Box<Expr>, Box<Expr>),
    /// `a * b`.
    Mul(Box<Expr>, Box<Expr>),
    /// `a ^ b` (non-negative integer exponent).
    Pow(Box<Expr>, Box<Expr>),
}

impl Expr {
    /// Variable names referenced by this expression.
    #[must_use]
    pub fn vars(&self) -> Vec<&str> {
        match self {
            Self::Int(_) => Vec::new(),
            Self::Var(name) => vec![name.as_str()],
            Self::Neg(inner) => inner.vars(),
            Self::Add(a, b) | Self::Sub(a, b) | Self::Mul(a, b) | Self::Pow(a, b) => {
                let mut vars = a.vars();
                vars.extend(b.vars());
                vars
            }
        }
    }

    /// Evaluates against `env` (chosen scalar values). Fails on unknown
    /// variables, non-integer/negative exponents, overflow, or results
    /// outside the JS safe-integer range ac-test used.
    ///
    /// # Errors
    ///
    /// Returns a description when the expression cannot be evaluated to
    /// a safe integer.
    pub fn eval(&self, env: &BTreeMap<String, i64>) -> Result<i64, ExprError> {
        let value = self.eval_wide(env)?;
        if value.unsigned_abs() > MAX_SAFE_INTEGER as u128 {
            return Err(ExprError::Unsafe(value.to_string()));
        }
        i64::try_from(value).map_err(|_| ExprError::Unsafe(value.to_string()))
    }

    /// Wide evaluation in `i128`; overflow or invalid operations are
    /// [`ExprError`].
    fn eval_wide(&self, env: &BTreeMap<String, i64>) -> Result<i128, ExprError> {
        match self {
            Self::Int(value) => Ok(i128::from(*value)),
            Self::Var(name) => env
                .get(name)
                .map(|v| i128::from(*v))
                .ok_or_else(|| ExprError::UnknownVar(name.clone())),
            Self::Neg(inner) => Ok(-inner.eval_wide(env)?),
            Self::Add(a, b) => Ok(a.eval_wide(env)? + b.eval_wide(env)?),
            Self::Sub(a, b) => Ok(a.eval_wide(env)? - b.eval_wide(env)?),
            Self::Mul(a, b) => Ok(a.eval_wide(env)? * b.eval_wide(env)?),
            Self::Pow(base, exp) => {
                let base = base.eval_wide(env)?;
                let exp = exp.eval_wide(env)?;
                if !(0..=62).contains(&exp) {
                    return Err(ExprError::BadExponent(exp.to_string()));
                }
                base.checked_pow(
                    u32::try_from(exp).map_err(|_| ExprError::BadExponent(exp.to_string()))?,
                )
                .ok_or(ExprError::Overflow)
            }
        }
    }
}

/// Expression evaluation failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExprError {
    /// Referenced variable has no chosen value.
    UnknownVar(String),
    /// Exponent is negative or too large.
    BadExponent(String),
    /// Arithmetic overflowed `i128`.
    Overflow,
    /// Result exceeds the safe-integer range.
    Unsafe(String),
}

impl fmt::Display for ExprError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownVar(name) => write!(f, "unknown variable `{name}`"),
            Self::BadExponent(exp) => write!(f, "invalid exponent {exp}"),
            Self::Overflow => write!(f, "expression overflow"),
            Self::Unsafe(value) => write!(f, "expression result {value} is not a safe integer"),
        }
    }
}

impl std::error::Error for ExprError {}

/// Recursive-descent parser for the constraint-expression subset:
/// integers, variable references, `+ - * ^`, parentheses, unary minus.
/// Division and other operators are rejected (conservative).
struct ExprParser<'a> {
    chars: std::str::Chars<'a>,
    peeked: Option<char>,
}

impl<'a> ExprParser<'a> {
    fn new(text: &'a str) -> Self {
        Self {
            chars: text.chars(),
            peeked: None,
        }
    }

    fn parse(mut self) -> Result<Expr, ()> {
        let expr = self.expr()?;
        self.skip_ws();
        if self.peeked.is_some() || self.chars.next().is_some() {
            return Err(());
        }
        Ok(expr)
    }

    fn peek(&mut self) -> Option<char> {
        if self.peeked.is_none() {
            self.peeked = self.chars.next();
        }
        self.peeked
    }

    fn bump(&mut self) -> Option<char> {
        let ch = self.peek()?;
        self.peeked = None;
        Some(ch)
    }

    fn skip_ws(&mut self) {
        while self.peek().is_some_and(char::is_whitespace) {
            self.bump();
        }
    }

    fn expr(&mut self) -> Result<Expr, ()> {
        let mut left = self.term()?;
        loop {
            self.skip_ws();
            match self.peek() {
                Some('+') => {
                    self.bump();
                    let right = self.term()?;
                    left = Expr::Add(Box::new(left), Box::new(right));
                }
                Some('-') => {
                    self.bump();
                    let right = self.term()?;
                    left = Expr::Sub(Box::new(left), Box::new(right));
                }
                _ => return Ok(left),
            }
        }
    }

    fn term(&mut self) -> Result<Expr, ()> {
        let mut left = self.factor()?;
        loop {
            self.skip_ws();
            if self.peek() == Some('*') {
                self.bump();
                let right = self.factor()?;
                left = Expr::Mul(Box::new(left), Box::new(right));
            } else {
                return Ok(left);
            }
        }
    }

    fn factor(&mut self) -> Result<Expr, ()> {
        self.skip_ws();
        let mut negative = false;
        while self.peek() == Some('-') {
            self.bump();
            negative = !negative;
        }
        let mut base = self.atom()?;
        self.skip_ws();
        if self.peek() == Some('^') {
            self.bump();
            let exp = self.factor()?;
            base = Expr::Pow(Box::new(base), Box::new(exp));
        }
        if negative {
            base = Expr::Neg(Box::new(base));
        }
        Ok(base)
    }

    fn atom(&mut self) -> Result<Expr, ()> {
        self.skip_ws();
        match self.peek() {
            Some('(') => {
                self.bump();
                let inner = self.expr()?;
                self.skip_ws();
                if self.bump() != Some(')') {
                    return Err(());
                }
                Ok(inner)
            }
            Some(c) if c.is_ascii_digit() => self.integer(),
            Some(c) if c.is_ascii_alphabetic() || c == '_' => self.ident(),
            _ => Err(()),
        }
    }

    fn integer(&mut self) -> Result<Expr, ()> {
        let mut text = String::new();
        while self.peek().is_some_and(|c| c.is_ascii_digit()) {
            text.push(self.bump().expect("peeked digit"));
        }
        let value: i64 = text.parse().map_err(|_| ())?;
        Ok(Expr::Int(value))
    }

    fn ident(&mut self) -> Result<Expr, ()> {
        let mut text = String::new();
        while self
            .peek()
            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            text.push(self.bump().expect("peeked ident char"));
        }
        if !is_ident(&text) {
            return Err(());
        }
        Ok(Expr::Var(text))
    }
}

/// Parses an `Expr` from `text`; the whole string must be consumed.
pub fn parse_expr(text: &str) -> Result<Expr, SpecError> {
    ExprParser::new(text)
        .parse()
        .map_err(|()| SpecError::Unsupported(format!("unparseable expression: {text}")))
}

/// Parsed constraint set: bounds keyed by schema variable.
#[derive(Clone, Debug, Default)]
pub struct ConstraintSet {
    /// Bounds for scalar and array-element variables.
    pub bounds: BTreeMap<VarKey, VarBounds>,
}

/// The merged generation spec: input format plus constraint bounds.
#[derive(Clone, Debug)]
pub struct GenSpec {
    /// Recognized input-format lines.
    pub format: InputFormat,
    /// Constraint bounds (scalar and element keys only).
    pub bounds: BTreeMap<VarKey, VarBounds>,
}

impl GenSpec {
    /// Builds a spec from input-format text and raw constraint lines.
    ///
    /// # Errors
    ///
    /// [`SpecError::Unsupported`] when the format is unrecognized, a
    /// constraint line looks like a constraint but cannot be parsed,
    /// required bounds are missing, or array length variables are not
    /// declared scalars.
    pub fn parse(input_format: &str, constraint_lines: &[String]) -> Result<Self, SpecError> {
        let format = InputFormat::parse(input_format)?;
        let constraints = ConstraintSet::parse(constraint_lines, &format)?;
        let spec = Self {
            format,
            bounds: constraints.bounds,
        };
        spec.validate()?;
        Ok(spec)
    }

    /// Scalar bounds `(name, bounds)` for declared scalar variables.
    pub(crate) fn scalar_bounds(&self) -> impl Iterator<Item = (&str, &VarBounds)> {
        self.bounds.iter().filter_map(|(key, bounds)| match key {
            VarKey::Scalar(name) => Some((name.as_str(), bounds)),
            _ => None,
        })
    }

    /// Element bounds `(lowers, uppers)` for array `name`.
    pub(crate) fn element_bounds(&self, name: &str) -> Option<(&[Expr], &[Expr])> {
        let bounds = self.bounds.get(&VarKey::Element(name.to_owned()))?;
        Some((&bounds.lowers, &bounds.uppers))
    }

    /// Validates that every generated value is bounded: each scalar has
    /// at least one lower and one upper expression, each array has
    /// element bounds, and every array length variable is a declared
    /// scalar.
    fn validate(&self) -> Result<(), SpecError> {
        for name in self.format.scalar_names() {
            let bounds = self
                .bounds
                .get(&VarKey::Scalar(name.clone()))
                .ok_or_else(|| {
                    SpecError::Unsupported(format!("scalar `{name}` has no constraints"))
                })?;
            if bounds.lowers.is_empty() || bounds.uppers.is_empty() {
                return Err(SpecError::Unsupported(format!(
                    "scalar `{name}` lacks a lower or upper bound"
                )));
            }
        }
        for (name, length_var) in self.format.array_decls() {
            if !self.format.is_scalar(&length_var) {
                return Err(SpecError::Unsupported(format!(
                    "array `{name}` length variable `{length_var}` is not a declared scalar"
                )));
            }
            let bounds = self
                .bounds
                .get(&VarKey::Element(name.clone()))
                .ok_or_else(|| {
                    SpecError::Unsupported(format!("array `{name}` elements have no constraints"))
                })?;
            if bounds.lowers.is_empty() || bounds.uppers.is_empty() {
                return Err(SpecError::Unsupported(format!(
                    "array `{name}` elements lack a lower or upper bound"
                )));
            }
        }
        Ok(())
    }
}

impl ConstraintSet {
    /// Parses constraint lines against the input format. Lines without
    /// comparison operators are prose and ignored; lines that look like
    /// constraints but cannot be parsed are [`SpecError::Unsupported`].
    ///
    /// # Errors
    ///
    /// [`SpecError::Unsupported`] on the first unparseable constraint.
    pub fn parse(lines: &[String], format: &InputFormat) -> Result<Self, SpecError> {
        let mut set = Self::default();
        for raw in lines {
            // Entries may embed newlines (e.g. `<pre>`-sourced text).
            for line in raw.lines() {
                set.parse_line(line, format)?;
            }
        }
        Ok(set)
    }

    fn parse_line(&mut self, raw: &str, format: &InputFormat) -> Result<(), SpecError> {
        let trimmed = strip_list_marker(raw.trim());
        if trimmed.is_empty() {
            return Ok(());
        }
        if has_multi_index(trimmed) {
            return Err(SpecError::Unsupported(format!(
                "multi-dimensional constraint: {trimmed}"
            )));
        }
        let mut normalized = normalize_markup(trimmed);
        strip_annotation_parens(&mut normalized);
        let normalized = normalized.trim();
        if normalized.is_empty() || !normalized.contains(['<', '>', '=']) {
            return Ok(());
        }
        let (segments, ops) = split_comparisons(normalized)
            .ok_or_else(|| SpecError::Unsupported(format!("unparseable constraint: {trimmed}")))?;
        match (segments.as_slice(), ops.as_slice()) {
            ([low, vars, high], [op1, op2]) if op1 == op2 => {
                let names = parse_var_list(vars)?;
                for name in &names {
                    self.add_bound(name, format, *op1, low, high)?;
                }
            }
            ([left, right], [op]) => {
                if is_ident(left.trim()) {
                    self.add_two_part(left.trim(), right.trim(), *op, format, true)?;
                } else if is_ident(right.trim()) {
                    self.add_two_part(right.trim(), left.trim(), *op, format, false)?;
                } else {
                    return Err(SpecError::Unsupported(format!(
                        "unparseable constraint: {trimmed}"
                    )));
                }
            }
            _ => {
                return Err(SpecError::Unsupported(format!(
                    "unparseable constraint: {trimmed}"
                )));
            }
        }
        Ok(())
    }

    /// `l OP X OP r` three-part form: `l <= X <= r` bounds below/above;
    /// `l >= X >= r` swaps the sides.
    fn add_bound(
        &mut self,
        name: &str,
        format: &InputFormat,
        op: CmpOp,
        low_text: &str,
        high_text: &str,
    ) -> Result<(), SpecError> {
        let (lower_text, upper_text) = match op {
            CmpOp::Le => (low_text, high_text),
            CmpOp::Ge => (high_text, low_text),
        };
        let lower = parse_expr(lower_text)?;
        let upper = parse_expr(upper_text)?;
        self.insert(name, format, lower, upper);
        Ok(())
    }

    /// Two-part form `A OP B`. `var_is_left` records which side held
    /// the identifier so `<=`/`>=` map to upper/lower correctly.
    ///
    /// `X <= r` → upper bound; `l <= X` → lower bound; `X >= r` →
    /// lower bound; `l >= X` → upper bound.
    fn add_two_part(
        &mut self,
        var: &str,
        expr_text: &str,
        op: CmpOp,
        format: &InputFormat,
        var_is_left: bool,
    ) -> Result<(), SpecError> {
        let expr = parse_expr(expr_text)?;
        // For `var OP expr`: `<=` gives an upper bound, `>=` a lower.
        // For `expr OP var` the relation flips.
        let (lower, upper) = match (op, var_is_left) {
            (CmpOp::Le, true) | (CmpOp::Ge, false) => (None, Some(expr)),
            _ => (Some(expr), None),
        };
        self.push_bound(var, format, lower, upper);
        Ok(())
    }

    /// Three-part insert helper shared by `add_bound`.
    fn insert(&mut self, name: &str, format: &InputFormat, lower: Expr, upper: Expr) {
        self.push_bound(name, format, Some(lower), Some(upper));
    }

    /// Adds bound expressions for `name`; `Other` variables (index
    /// names, prose) are dropped.
    fn push_bound(
        &mut self,
        name: &str,
        format: &InputFormat,
        lower: Option<Expr>,
        upper: Option<Expr>,
    ) {
        let key = classify(name, format);
        if matches!(key, VarKey::Other(_)) {
            return;
        }
        let bounds = self.bounds.entry(key).or_default();
        if let Some(expr) = lower {
            bounds.lowers.push(expr);
        }
        if let Some(expr) = upper {
            bounds.uppers.push(expr);
        }
    }
}

/// Comparison operator direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CmpOp {
    /// `<=`.
    Le,
    /// `>=`.
    Ge,
}

/// Splits `a <= b <= c`-style text into operand segments and operators.
/// Returns `None` when the comparison structure is not a chain of
/// `<=`/`>=` (strict `<`/`>`, `=`, `!=` all fail here).
fn split_comparisons(text: &str) -> Option<(Vec<String>, Vec<CmpOp>)> {
    let bytes = text.as_bytes();
    let mut segments = Vec::new();
    let mut ops = Vec::new();
    let mut start = 0;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'<' | b'>' if bytes.get(i + 1) == Some(&b'=') => {
                segments.push(text[start..i].to_owned());
                ops.push(if bytes[i] == b'<' {
                    CmpOp::Le
                } else {
                    CmpOp::Ge
                });
                i += 2;
                start = i;
            }
            b'<' | b'>' | b'=' | b'!' => return None,
            _ => i += 1,
        }
    }
    // A trailing/leading operator or empty operand is malformed.
    if start == 0 || start >= text.len() {
        return None;
    }
    segments.push(text[start..].to_owned());
    if segments.iter().any(|s| s.trim().is_empty()) {
        return None;
    }
    Some((segments, ops))
}

/// Parses the comma-separated variable list of a three-part constraint.
fn parse_var_list(text: &str) -> Result<Vec<String>, SpecError> {
    let names: Vec<String> = text.split(',').map(str::trim).map(str::to_owned).collect();
    if names.iter().any(|n| !is_ident(n)) {
        return Err(SpecError::Unsupported(format!(
            "unparseable constraint variable list: {text}"
        )));
    }
    Ok(names)
}

/// Maps a constraint variable name onto the schema: declared scalars
/// stay scalar, `BASE_<index>` under a declared array becomes an
/// element bound, everything else is ignored.
fn classify(name: &str, format: &InputFormat) -> VarKey {
    if format.is_scalar(name) {
        return VarKey::Scalar(name.to_owned());
    }
    if let Some(base) = format.element_base(name) {
        return VarKey::Element(base);
    }
    VarKey::Other(name.to_owned())
}

/// Removes a leading list marker (`- `, `・`, `•`, `* `, or `12. `/`3) `)
/// from constraint text extracted out of `<li>`/`<p>` markup. Only
/// marker+whitespace prefixes are stripped, so a real negative bound
/// like `-1 <= N` is untouched.
fn strip_list_marker(text: &str) -> &str {
    let text = text.trim_start();
    for prefix in ["- ", "− ", "– ", "• ", "・ ", "* "] {
        if let Some(rest) = text.strip_prefix(prefix) {
            return rest.trim_start();
        }
    }
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() && bytes[i].is_ascii_digit() {
        i += 1;
    }
    if i > 0
        && i + 1 < bytes.len()
        && matches!(bytes[i], b'.' | b')')
        && bytes[i + 1].is_ascii_whitespace()
    {
        return text[i + 1..].trim_start();
    }
    text
}

/// `true` for `_{...,`-style multi-dimensional index markers in the
/// raw (pre-normalization) line.
fn has_multi_index(raw: &str) -> bool {
    let bytes = raw.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        if b == b'_' && bytes.get(i + 1) == Some(&b'{') {
            if let Some(end) = raw[i + 2..].find('}').map(|e| i + 2 + e) {
                if raw[i + 2..end].contains(',') {
                    return true;
                }
            }
        }
    }
    false
}

/// Removes parenthesized groups that contain comparison operators or
/// `=` — these are index-range annotations like `(1 <= i <= N)` or
/// `(i = 1, ..., N)`, never part of a bound expression. Groups without
/// comparisons (e.g. `(N + 1)`) are kept for the expression parser.
fn strip_annotation_parens(text: &mut String) {
    let mut search_from = 0;
    while let Some(rel) = text[search_from..].find('(') {
        let start = search_from + rel;
        let mut depth = 0i32;
        let mut end = None;
        for (i, ch) in text.char_indices().skip_while(|(i, _)| *i < start) {
            match ch {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        end = Some(i);
                        break;
                    }
                }
                _ => {}
            }
        }
        let Some(end) = end else { return };
        if text[start + 1..end].contains(['<', '>', '=']) {
            text.replace_range(start..=end, " ");
            search_from = start;
        } else {
            search_from = end + 1;
        }
    }
}

/// LaTeX/markup normalization shared by format and constraint lines:
/// math delimiters, `\ldots`-style ellipses, braces, `\_`, unicode
/// comparison/operator glyphs, and NBSP become ASCII equivalents.
/// Commands are matched longest-first so `\leq` wins over `\le`.
fn normalize_markup(text: &str) -> String {
    const COMMANDS: &[(&str, &str)] = &[
        ("\\ldotsb", "..."),
        ("\\ldots", "..."),
        ("\\cdots", "..."),
        ("\\dots", "..."),
        ("\\leq", "<="),
        ("\\le", "<="),
        ("\\geq", ">="),
        ("\\ge", ">="),
        ("\\times", "*"),
        ("\\cdot", "*"),
        ("\\neq", "!="),
        ("\\ne", "!="),
        ("\\_", "_"),
        ("\\(", " "),
        ("\\)", " "),
        ("\\ ", " "),
    ];
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(ch) = rest.chars().next() {
        if ch == '\\' {
            if let Some((command, replacement)) = COMMANDS
                .iter()
                .find(|(command, _)| rest.starts_with(command))
            {
                out.push_str(replacement);
                rest = &rest[command.len()..];
                continue;
            }
            // Unknown command: drop the backslash, keep the letter so
            // prose like `\times` variants still surface as text.
            rest = &rest[1..];
            continue;
        }
        let mapped = match ch {
            '≤' | '≦' | '﹤' => Some("<="),
            '≥' | '≧' | '﹥' => Some(">="),
            '−' | '–' | '—' => Some("-"),
            '×' | '⋅' | '∙' => Some("*"),
            '…' | '⋯' => Some("..."),
            '{' | '}' | '$' => Some(""),
            '\u{a0}' => Some(" "),
            _ => None,
        };
        if let Some(replacement) = mapped {
            out.push_str(replacement);
        } else {
            out.push(ch);
        }
        rest = &rest[ch.len_utf8()..];
    }
    out
}

#[cfg(test)]
pub(crate) mod tests_support {
    use super::*;

    /// `N M` scalars + `A_1 A_2 ... A_N` array, fully bounded.
    pub(crate) fn parse_simple_spec() -> GenSpec {
        GenSpec::parse(
            "N M\nA_1 A_2 ... A_N\n",
            &[
                "1 <= N <= 10".to_owned(),
                "1 <= M <= 10".to_owned(),
                "1 <= A_i <= 10 (1 <= i <= N)".to_owned(),
            ],
        )
        .expect("simple spec")
    }
}

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

    #[test]
    fn parses_scalar_and_array_lines() {
        let format = InputFormat::parse("N M\nA_1 A_2 ... A_N\n").expect("format");
        assert_eq!(format.lines.len(), 2);
        assert_eq!(
            format.lines[0],
            FormatLine::Scalars(vec!["N".to_owned(), "M".to_owned()])
        );
        assert_eq!(
            format.lines[1],
            FormatLine::Array {
                name: "A".to_owned(),
                length_var: "N".to_owned()
            }
        );
    }

    #[test]
    fn rejects_unsupported_format_lines() {
        for text in [
            "S T\n\"string\"\n",       // quoted literal
            "A_{i,j}\n",               // 2-D index braces → token fails ident
            "A_1 A_2 ... A_N extra\n", // tokens after the length var
            "N\n...\n",                // bare ellipsis
            "N, M\n",                  // commas unsupported
        ] {
            assert!(
                InputFormat::parse(text).is_err(),
                "expected unsupported: {text:?}"
            );
        }
    }

    #[test]
    fn parses_constraint_forms() {
        let format = InputFormat::parse("N M\nA_1 A_2 ... A_N\n").expect("format");
        let set = ConstraintSet::parse(
            &[
                "1 <= N <= 10".to_owned(),
                "M <= 5".to_owned(),
                "2 <= N, M <= 8".to_owned(),
                "1 <= A_i <= N \\ (1 \\le i \\le N)".to_owned(),
                "prose line without operators".to_owned(),
            ],
            &format,
        )
        .expect("constraints");
        let n = set
            .bounds
            .get(&VarKey::Scalar("N".to_owned()))
            .expect("N bounds");
        assert_eq!(n.lowers.len(), 2);
        assert_eq!(n.uppers.len(), 2);
        let m = set
            .bounds
            .get(&VarKey::Scalar("M".to_owned()))
            .expect("M bounds");
        assert_eq!(m.lowers.len(), 1);
        assert_eq!(m.uppers.len(), 2);
        let a = set
            .bounds
            .get(&VarKey::Element("A".to_owned()))
            .expect("A bounds");
        assert_eq!(a.lowers.len(), 1);
        assert_eq!(a.uppers.len(), 1);
    }

    #[test]
    fn strict_and_unknown_constraints_are_unsupported() {
        let format = InputFormat::parse("N\n").expect("format");
        for line in [
            "1 <= N < 10".to_owned(),  // strict upper
            "N != 5".to_owned(),       // disequality
            "N <= M +".to_owned(),     // broken expr
            "A_{i,j} <= N".to_owned(), // 2-D
        ] {
            assert!(
                ConstraintSet::parse(std::slice::from_ref(&line), &format).is_err(),
                "expected unsupported: {line}"
            );
        }
    }

    #[test]
    fn evaluates_safe_integer_expressions() {
        let env = BTreeMap::from([("N".to_owned(), 3_i64)]);
        assert_eq!(parse_expr("10^5").expect("expr").eval(&env), Ok(100_000));
        assert_eq!(
            parse_expr("2 * 10^5").expect("expr").eval(&env),
            Ok(200_000)
        );
        assert_eq!(parse_expr("N + 1").expect("expr").eval(&env), Ok(4));
        assert_eq!(parse_expr("-N * 2").expect("expr").eval(&env), Ok(-6));
        assert!(parse_expr("10^100").expect("expr").eval(&env).is_err());
        assert!(parse_expr("M + 1").expect("expr").eval(&env).is_err());
        assert!(parse_expr("1 / 2").is_err());
    }

    #[test]
    fn spec_requires_bounds_for_everything() {
        // Array length var undeclared → unsupported.
        assert!(GenSpec::parse("A_1 A_2 ... A_N\n", &["1 <= A_i <= 10".to_owned()]).is_err());
        // Element bounds missing → unsupported.
        assert!(GenSpec::parse("N\nA_1 A_2 ... A_N\n", &["1 <= N <= 10".to_owned()]).is_err());
    }
}