Skip to main content

ac_algorithm/generate/
spec.rs

1//! Generation-spec parsing: the problem's input-format block and
2//! constraint lines become a [`GenSpec`] (spike #6 §2.3–§2.4).
3//!
4//! Only the Level-1 subset is recognized: integer scalars and
5//! one-dimensional integer arrays. Anything that cannot be proven to
6//! yield valid input — multi-dimensional arrays, strings, permutations,
7//! strict inequalities, unparseable constraint expressions — marks the
8//! spec [`SpecError::Unsupported`] and generation is skipped entirely.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::fmt;
12
13/// JavaScript `Number.MAX_SAFE_INTEGER`; ac-test evaluated constraint
14/// expressions as safe integers only.
15pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
16
17/// Why a spec cannot drive generation.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub enum SpecError {
20    /// The input format or a constraint line is outside the Level-1
21    /// subset; generation must be skipped conservatively.
22    Unsupported(String),
23}
24
25impl fmt::Display for SpecError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::Unsupported(reason) => write!(f, "generation spec unsupported: {reason}"),
29        }
30    }
31}
32
33impl std::error::Error for SpecError {}
34
35/// One recognized input-format line.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub enum FormatLine {
38    /// Scalar variables emitted space-separated on one line.
39    Scalars(Vec<String>),
40    /// One-dimensional integer array `A_1 A_2 ... A_<length_var>`.
41    /// `name` is the element base (`A` for `A_i`-style constraints).
42    Array {
43        /// Element base name (`A` in `A_i`).
44        name: String,
45        /// Scalar variable that determines the element count.
46        length_var: String,
47    },
48}
49
50/// Parsed input-format block.
51#[derive(Clone, Debug, Default, PartialEq, Eq)]
52pub struct InputFormat {
53    /// Format lines in document order.
54    pub lines: Vec<FormatLine>,
55    /// Declared scalar variable names.
56    scalars: BTreeSet<String>,
57    /// Declared array element base names.
58    arrays: BTreeSet<String>,
59}
60
61impl InputFormat {
62    /// Parses the `<pre>` text of the problem's Input section.
63    ///
64    /// # Errors
65    ///
66    /// [`SpecError::Unsupported`] when any non-empty line is neither an
67    /// all-identifier scalar line nor a recognized 1-D array line.
68    pub fn parse(text: &str) -> Result<Self, SpecError> {
69        let mut format = Self::default();
70        for raw in text.lines() {
71            let normalized = normalize_markup(raw);
72            let tokens: Vec<&str> = normalized.split_whitespace().collect();
73            if tokens.is_empty() {
74                continue;
75            }
76            let line = if tokens.contains(&"...") {
77                parse_array_line(&tokens)?
78            } else if tokens.iter().all(|t| is_ident(t)) {
79                for name in &tokens {
80                    if !format.scalars.insert((*name).to_owned()) {
81                        return Err(SpecError::Unsupported(format!(
82                            "duplicate scalar variable `{name}`"
83                        )));
84                    }
85                }
86                FormatLine::Scalars(tokens.iter().map(|t| (*t).to_owned()).collect())
87            } else {
88                return Err(SpecError::Unsupported(format!(
89                    "unrecognized input-format line: {}",
90                    raw.trim()
91                )));
92            };
93            if let FormatLine::Array { name, .. } = &line {
94                if format.arrays.contains(name) {
95                    return Err(SpecError::Unsupported(format!(
96                        "duplicate array variable `{name}`"
97                    )));
98                }
99                format.arrays.insert(name.clone());
100            }
101            format.lines.push(line);
102        }
103        if format.lines.is_empty() {
104            return Err(SpecError::Unsupported(
105                "input format block is empty".to_owned(),
106            ));
107        }
108        Ok(format)
109    }
110
111    /// `true` when `name` is a declared scalar variable.
112    fn is_scalar(&self, name: &str) -> bool {
113        self.scalars.contains(name)
114    }
115
116    /// Array element base for `name` (`A_i` → `A`), when `name` is not
117    /// itself a scalar.
118    fn element_base(&self, name: &str) -> Option<String> {
119        let (base, _index) = name.rsplit_once('_')?;
120        self.arrays.contains(base).then(|| base.to_owned())
121    }
122
123    /// All declared scalar names (for spec validation).
124    pub(crate) fn scalar_names(&self) -> impl Iterator<Item = &String> {
125        self.scalars.iter()
126    }
127
128    /// Array declarations `(element base, length var)` in line order.
129    pub(crate) fn array_decls(&self) -> Vec<(String, String)> {
130        self.lines
131            .iter()
132            .filter_map(|line| match line {
133                FormatLine::Array {
134                    name, length_var, ..
135                } => Some((name.clone(), length_var.clone())),
136                FormatLine::Scalars(_) => None,
137            })
138            .collect()
139    }
140}
141
142/// Recognizes `X_1 X_2 ... X_<len>` array lines.
143fn parse_array_line(tokens: &[&str]) -> Result<FormatLine, SpecError> {
144    let unsupported = || {
145        SpecError::Unsupported(format!(
146            "unrecognized input-format line: {}",
147            tokens.join(" ")
148        ))
149    };
150    let ellipsis = tokens
151        .iter()
152        .position(|t| *t == "...")
153        .ok_or_else(unsupported)?;
154    if tokens.iter().filter(|t| **t == "...").count() != 1
155        || ellipsis == 0
156        || ellipsis + 1 != tokens.len() - 1
157    {
158        return Err(unsupported());
159    }
160    let before = &tokens[..ellipsis];
161    let after = tokens[ellipsis + 1];
162    // Every token must be `BASE_<suffix>` with one shared base; the
163    // after-ellipsis token's suffix is the length variable.
164    let mut base: Option<&str> = None;
165    for token in before.iter().chain(std::iter::once(&after)) {
166        let Some((token_base, suffix)) = token.rsplit_once('_') else {
167            return Err(unsupported());
168        };
169        if suffix.is_empty()
170            || !suffix
171                .chars()
172                .all(|c| c.is_ascii_alphanumeric() || c == '_')
173        {
174            return Err(unsupported());
175        }
176        match base {
177            None => base = Some(token_base),
178            Some(existing) if existing != token_base => return Err(unsupported()),
179            _ => {}
180        }
181    }
182    let base = base.ok_or_else(unsupported)?;
183    if !is_ident(base) {
184        return Err(unsupported());
185    }
186    let Some((_, length_var)) = after.rsplit_once('_') else {
187        return Err(unsupported());
188    };
189    if !is_ident(length_var) {
190        return Err(unsupported());
191    }
192    Ok(FormatLine::Array {
193        name: base.to_owned(),
194        length_var: length_var.to_owned(),
195    })
196}
197
198/// `true` for `[A-Za-z][A-Za-z0-9_]*` (ac-test's identifier rule).
199fn is_ident(text: &str) -> bool {
200    let mut chars = text.chars();
201    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
202        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
203}
204
205/// What a constraint line bounds.
206#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
207pub enum VarKey {
208    /// A declared scalar variable.
209    Scalar(String),
210    /// Elements of a declared array (`A` bounds `A_i`, `A_1`, …).
211    Element(String),
212    /// Anything else (index variables, prose) — ignored.
213    Other(String),
214}
215
216/// Lower/upper bound expressions for one variable. Multiple
217/// constraints on the same variable accumulate; generation takes the
218/// tightest resolved bound.
219#[derive(Clone, Debug, Default)]
220pub struct VarBounds {
221    /// Lower-bound expressions (`l <= X`).
222    pub lowers: Vec<Expr>,
223    /// Upper-bound expressions (`X <= r`).
224    pub uppers: Vec<Expr>,
225}
226
227/// A parsed safe-integer expression. Variables resolve against the
228/// scalar values chosen earlier in generation order.
229#[derive(Clone, Debug, PartialEq)]
230pub enum Expr {
231    /// Integer literal.
232    Int(i64),
233    /// Variable reference (scalar name).
234    Var(String),
235    /// `-e`.
236    Neg(Box<Expr>),
237    /// `a + b`.
238    Add(Box<Expr>, Box<Expr>),
239    /// `a - b`.
240    Sub(Box<Expr>, Box<Expr>),
241    /// `a * b`.
242    Mul(Box<Expr>, Box<Expr>),
243    /// `a ^ b` (non-negative integer exponent).
244    Pow(Box<Expr>, Box<Expr>),
245}
246
247impl Expr {
248    /// Variable names referenced by this expression.
249    #[must_use]
250    pub fn vars(&self) -> Vec<&str> {
251        match self {
252            Self::Int(_) => Vec::new(),
253            Self::Var(name) => vec![name.as_str()],
254            Self::Neg(inner) => inner.vars(),
255            Self::Add(a, b) | Self::Sub(a, b) | Self::Mul(a, b) | Self::Pow(a, b) => {
256                let mut vars = a.vars();
257                vars.extend(b.vars());
258                vars
259            }
260        }
261    }
262
263    /// Evaluates against `env` (chosen scalar values). Fails on unknown
264    /// variables, non-integer/negative exponents, overflow, or results
265    /// outside the JS safe-integer range ac-test used.
266    ///
267    /// # Errors
268    ///
269    /// Returns a description when the expression cannot be evaluated to
270    /// a safe integer.
271    pub fn eval(&self, env: &BTreeMap<String, i64>) -> Result<i64, ExprError> {
272        let value = self.eval_wide(env)?;
273        if value.unsigned_abs() > MAX_SAFE_INTEGER as u128 {
274            return Err(ExprError::Unsafe(value.to_string()));
275        }
276        i64::try_from(value).map_err(|_| ExprError::Unsafe(value.to_string()))
277    }
278
279    /// Wide evaluation in `i128`; overflow or invalid operations are
280    /// [`ExprError`].
281    fn eval_wide(&self, env: &BTreeMap<String, i64>) -> Result<i128, ExprError> {
282        match self {
283            Self::Int(value) => Ok(i128::from(*value)),
284            Self::Var(name) => env
285                .get(name)
286                .map(|v| i128::from(*v))
287                .ok_or_else(|| ExprError::UnknownVar(name.clone())),
288            Self::Neg(inner) => Ok(-inner.eval_wide(env)?),
289            Self::Add(a, b) => Ok(a.eval_wide(env)? + b.eval_wide(env)?),
290            Self::Sub(a, b) => Ok(a.eval_wide(env)? - b.eval_wide(env)?),
291            Self::Mul(a, b) => Ok(a.eval_wide(env)? * b.eval_wide(env)?),
292            Self::Pow(base, exp) => {
293                let base = base.eval_wide(env)?;
294                let exp = exp.eval_wide(env)?;
295                if !(0..=62).contains(&exp) {
296                    return Err(ExprError::BadExponent(exp.to_string()));
297                }
298                base.checked_pow(
299                    u32::try_from(exp).map_err(|_| ExprError::BadExponent(exp.to_string()))?,
300                )
301                .ok_or(ExprError::Overflow)
302            }
303        }
304    }
305}
306
307/// Expression evaluation failure.
308#[derive(Clone, Debug, PartialEq, Eq)]
309pub enum ExprError {
310    /// Referenced variable has no chosen value.
311    UnknownVar(String),
312    /// Exponent is negative or too large.
313    BadExponent(String),
314    /// Arithmetic overflowed `i128`.
315    Overflow,
316    /// Result exceeds the safe-integer range.
317    Unsafe(String),
318}
319
320impl fmt::Display for ExprError {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        match self {
323            Self::UnknownVar(name) => write!(f, "unknown variable `{name}`"),
324            Self::BadExponent(exp) => write!(f, "invalid exponent {exp}"),
325            Self::Overflow => write!(f, "expression overflow"),
326            Self::Unsafe(value) => write!(f, "expression result {value} is not a safe integer"),
327        }
328    }
329}
330
331impl std::error::Error for ExprError {}
332
333/// Recursive-descent parser for the constraint-expression subset:
334/// integers, variable references, `+ - * ^`, parentheses, unary minus.
335/// Division and other operators are rejected (conservative).
336struct ExprParser<'a> {
337    chars: std::str::Chars<'a>,
338    peeked: Option<char>,
339}
340
341impl<'a> ExprParser<'a> {
342    fn new(text: &'a str) -> Self {
343        Self {
344            chars: text.chars(),
345            peeked: None,
346        }
347    }
348
349    fn parse(mut self) -> Result<Expr, ()> {
350        let expr = self.expr()?;
351        self.skip_ws();
352        if self.peeked.is_some() || self.chars.next().is_some() {
353            return Err(());
354        }
355        Ok(expr)
356    }
357
358    fn peek(&mut self) -> Option<char> {
359        if self.peeked.is_none() {
360            self.peeked = self.chars.next();
361        }
362        self.peeked
363    }
364
365    fn bump(&mut self) -> Option<char> {
366        let ch = self.peek()?;
367        self.peeked = None;
368        Some(ch)
369    }
370
371    fn skip_ws(&mut self) {
372        while self.peek().is_some_and(char::is_whitespace) {
373            self.bump();
374        }
375    }
376
377    fn expr(&mut self) -> Result<Expr, ()> {
378        let mut left = self.term()?;
379        loop {
380            self.skip_ws();
381            match self.peek() {
382                Some('+') => {
383                    self.bump();
384                    let right = self.term()?;
385                    left = Expr::Add(Box::new(left), Box::new(right));
386                }
387                Some('-') => {
388                    self.bump();
389                    let right = self.term()?;
390                    left = Expr::Sub(Box::new(left), Box::new(right));
391                }
392                _ => return Ok(left),
393            }
394        }
395    }
396
397    fn term(&mut self) -> Result<Expr, ()> {
398        let mut left = self.factor()?;
399        loop {
400            self.skip_ws();
401            if self.peek() == Some('*') {
402                self.bump();
403                let right = self.factor()?;
404                left = Expr::Mul(Box::new(left), Box::new(right));
405            } else {
406                return Ok(left);
407            }
408        }
409    }
410
411    fn factor(&mut self) -> Result<Expr, ()> {
412        self.skip_ws();
413        let mut negative = false;
414        while self.peek() == Some('-') {
415            self.bump();
416            negative = !negative;
417        }
418        let mut base = self.atom()?;
419        self.skip_ws();
420        if self.peek() == Some('^') {
421            self.bump();
422            let exp = self.factor()?;
423            base = Expr::Pow(Box::new(base), Box::new(exp));
424        }
425        if negative {
426            base = Expr::Neg(Box::new(base));
427        }
428        Ok(base)
429    }
430
431    fn atom(&mut self) -> Result<Expr, ()> {
432        self.skip_ws();
433        match self.peek() {
434            Some('(') => {
435                self.bump();
436                let inner = self.expr()?;
437                self.skip_ws();
438                if self.bump() != Some(')') {
439                    return Err(());
440                }
441                Ok(inner)
442            }
443            Some(c) if c.is_ascii_digit() => self.integer(),
444            Some(c) if c.is_ascii_alphabetic() || c == '_' => self.ident(),
445            _ => Err(()),
446        }
447    }
448
449    fn integer(&mut self) -> Result<Expr, ()> {
450        let mut text = String::new();
451        while self.peek().is_some_and(|c| c.is_ascii_digit()) {
452            text.push(self.bump().expect("peeked digit"));
453        }
454        let value: i64 = text.parse().map_err(|_| ())?;
455        Ok(Expr::Int(value))
456    }
457
458    fn ident(&mut self) -> Result<Expr, ()> {
459        let mut text = String::new();
460        while self
461            .peek()
462            .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
463        {
464            text.push(self.bump().expect("peeked ident char"));
465        }
466        if !is_ident(&text) {
467            return Err(());
468        }
469        Ok(Expr::Var(text))
470    }
471}
472
473/// Parses an `Expr` from `text`; the whole string must be consumed.
474pub fn parse_expr(text: &str) -> Result<Expr, SpecError> {
475    ExprParser::new(text)
476        .parse()
477        .map_err(|()| SpecError::Unsupported(format!("unparseable expression: {text}")))
478}
479
480/// Parsed constraint set: bounds keyed by schema variable.
481#[derive(Clone, Debug, Default)]
482pub struct ConstraintSet {
483    /// Bounds for scalar and array-element variables.
484    pub bounds: BTreeMap<VarKey, VarBounds>,
485}
486
487/// The merged generation spec: input format plus constraint bounds.
488#[derive(Clone, Debug)]
489pub struct GenSpec {
490    /// Recognized input-format lines.
491    pub format: InputFormat,
492    /// Constraint bounds (scalar and element keys only).
493    pub bounds: BTreeMap<VarKey, VarBounds>,
494}
495
496impl GenSpec {
497    /// Builds a spec from input-format text and raw constraint lines.
498    ///
499    /// # Errors
500    ///
501    /// [`SpecError::Unsupported`] when the format is unrecognized, a
502    /// constraint line looks like a constraint but cannot be parsed,
503    /// required bounds are missing, or array length variables are not
504    /// declared scalars.
505    pub fn parse(input_format: &str, constraint_lines: &[String]) -> Result<Self, SpecError> {
506        let format = InputFormat::parse(input_format)?;
507        let constraints = ConstraintSet::parse(constraint_lines, &format)?;
508        let spec = Self {
509            format,
510            bounds: constraints.bounds,
511        };
512        spec.validate()?;
513        Ok(spec)
514    }
515
516    /// Scalar bounds `(name, bounds)` for declared scalar variables.
517    pub(crate) fn scalar_bounds(&self) -> impl Iterator<Item = (&str, &VarBounds)> {
518        self.bounds.iter().filter_map(|(key, bounds)| match key {
519            VarKey::Scalar(name) => Some((name.as_str(), bounds)),
520            _ => None,
521        })
522    }
523
524    /// Element bounds `(lowers, uppers)` for array `name`.
525    pub(crate) fn element_bounds(&self, name: &str) -> Option<(&[Expr], &[Expr])> {
526        let bounds = self.bounds.get(&VarKey::Element(name.to_owned()))?;
527        Some((&bounds.lowers, &bounds.uppers))
528    }
529
530    /// Validates that every generated value is bounded: each scalar has
531    /// at least one lower and one upper expression, each array has
532    /// element bounds, and every array length variable is a declared
533    /// scalar.
534    fn validate(&self) -> Result<(), SpecError> {
535        for name in self.format.scalar_names() {
536            let bounds = self
537                .bounds
538                .get(&VarKey::Scalar(name.clone()))
539                .ok_or_else(|| {
540                    SpecError::Unsupported(format!("scalar `{name}` has no constraints"))
541                })?;
542            if bounds.lowers.is_empty() || bounds.uppers.is_empty() {
543                return Err(SpecError::Unsupported(format!(
544                    "scalar `{name}` lacks a lower or upper bound"
545                )));
546            }
547        }
548        for (name, length_var) in self.format.array_decls() {
549            if !self.format.is_scalar(&length_var) {
550                return Err(SpecError::Unsupported(format!(
551                    "array `{name}` length variable `{length_var}` is not a declared scalar"
552                )));
553            }
554            let bounds = self
555                .bounds
556                .get(&VarKey::Element(name.clone()))
557                .ok_or_else(|| {
558                    SpecError::Unsupported(format!("array `{name}` elements have no constraints"))
559                })?;
560            if bounds.lowers.is_empty() || bounds.uppers.is_empty() {
561                return Err(SpecError::Unsupported(format!(
562                    "array `{name}` elements lack a lower or upper bound"
563                )));
564            }
565        }
566        Ok(())
567    }
568}
569
570impl ConstraintSet {
571    /// Parses constraint lines against the input format. Lines without
572    /// comparison operators are prose and ignored; lines that look like
573    /// constraints but cannot be parsed are [`SpecError::Unsupported`].
574    ///
575    /// # Errors
576    ///
577    /// [`SpecError::Unsupported`] on the first unparseable constraint.
578    pub fn parse(lines: &[String], format: &InputFormat) -> Result<Self, SpecError> {
579        let mut set = Self::default();
580        for raw in lines {
581            // Entries may embed newlines (e.g. `<pre>`-sourced text).
582            for line in raw.lines() {
583                set.parse_line(line, format)?;
584            }
585        }
586        Ok(set)
587    }
588
589    fn parse_line(&mut self, raw: &str, format: &InputFormat) -> Result<(), SpecError> {
590        let trimmed = strip_list_marker(raw.trim());
591        if trimmed.is_empty() {
592            return Ok(());
593        }
594        if has_multi_index(trimmed) {
595            return Err(SpecError::Unsupported(format!(
596                "multi-dimensional constraint: {trimmed}"
597            )));
598        }
599        let mut normalized = normalize_markup(trimmed);
600        strip_annotation_parens(&mut normalized);
601        let normalized = normalized.trim();
602        if normalized.is_empty() || !normalized.contains(['<', '>', '=']) {
603            return Ok(());
604        }
605        let (segments, ops) = split_comparisons(normalized)
606            .ok_or_else(|| SpecError::Unsupported(format!("unparseable constraint: {trimmed}")))?;
607        match (segments.as_slice(), ops.as_slice()) {
608            ([low, vars, high], [op1, op2]) if op1 == op2 => {
609                let names = parse_var_list(vars)?;
610                for name in &names {
611                    self.add_bound(name, format, *op1, low, high)?;
612                }
613            }
614            ([left, right], [op]) => {
615                if is_ident(left.trim()) {
616                    self.add_two_part(left.trim(), right.trim(), *op, format, true)?;
617                } else if is_ident(right.trim()) {
618                    self.add_two_part(right.trim(), left.trim(), *op, format, false)?;
619                } else {
620                    return Err(SpecError::Unsupported(format!(
621                        "unparseable constraint: {trimmed}"
622                    )));
623                }
624            }
625            _ => {
626                return Err(SpecError::Unsupported(format!(
627                    "unparseable constraint: {trimmed}"
628                )));
629            }
630        }
631        Ok(())
632    }
633
634    /// `l OP X OP r` three-part form: `l <= X <= r` bounds below/above;
635    /// `l >= X >= r` swaps the sides.
636    fn add_bound(
637        &mut self,
638        name: &str,
639        format: &InputFormat,
640        op: CmpOp,
641        low_text: &str,
642        high_text: &str,
643    ) -> Result<(), SpecError> {
644        let (lower_text, upper_text) = match op {
645            CmpOp::Le => (low_text, high_text),
646            CmpOp::Ge => (high_text, low_text),
647        };
648        let lower = parse_expr(lower_text)?;
649        let upper = parse_expr(upper_text)?;
650        self.insert(name, format, lower, upper);
651        Ok(())
652    }
653
654    /// Two-part form `A OP B`. `var_is_left` records which side held
655    /// the identifier so `<=`/`>=` map to upper/lower correctly.
656    ///
657    /// `X <= r` → upper bound; `l <= X` → lower bound; `X >= r` →
658    /// lower bound; `l >= X` → upper bound.
659    fn add_two_part(
660        &mut self,
661        var: &str,
662        expr_text: &str,
663        op: CmpOp,
664        format: &InputFormat,
665        var_is_left: bool,
666    ) -> Result<(), SpecError> {
667        let expr = parse_expr(expr_text)?;
668        // For `var OP expr`: `<=` gives an upper bound, `>=` a lower.
669        // For `expr OP var` the relation flips.
670        let (lower, upper) = match (op, var_is_left) {
671            (CmpOp::Le, true) | (CmpOp::Ge, false) => (None, Some(expr)),
672            _ => (Some(expr), None),
673        };
674        self.push_bound(var, format, lower, upper);
675        Ok(())
676    }
677
678    /// Three-part insert helper shared by `add_bound`.
679    fn insert(&mut self, name: &str, format: &InputFormat, lower: Expr, upper: Expr) {
680        self.push_bound(name, format, Some(lower), Some(upper));
681    }
682
683    /// Adds bound expressions for `name`; `Other` variables (index
684    /// names, prose) are dropped.
685    fn push_bound(
686        &mut self,
687        name: &str,
688        format: &InputFormat,
689        lower: Option<Expr>,
690        upper: Option<Expr>,
691    ) {
692        let key = classify(name, format);
693        if matches!(key, VarKey::Other(_)) {
694            return;
695        }
696        let bounds = self.bounds.entry(key).or_default();
697        if let Some(expr) = lower {
698            bounds.lowers.push(expr);
699        }
700        if let Some(expr) = upper {
701            bounds.uppers.push(expr);
702        }
703    }
704}
705
706/// Comparison operator direction.
707#[derive(Clone, Copy, Debug, PartialEq, Eq)]
708enum CmpOp {
709    /// `<=`.
710    Le,
711    /// `>=`.
712    Ge,
713}
714
715/// Splits `a <= b <= c`-style text into operand segments and operators.
716/// Returns `None` when the comparison structure is not a chain of
717/// `<=`/`>=` (strict `<`/`>`, `=`, `!=` all fail here).
718fn split_comparisons(text: &str) -> Option<(Vec<String>, Vec<CmpOp>)> {
719    let bytes = text.as_bytes();
720    let mut segments = Vec::new();
721    let mut ops = Vec::new();
722    let mut start = 0;
723    let mut i = 0;
724    while i < bytes.len() {
725        match bytes[i] {
726            b'<' | b'>' if bytes.get(i + 1) == Some(&b'=') => {
727                segments.push(text[start..i].to_owned());
728                ops.push(if bytes[i] == b'<' {
729                    CmpOp::Le
730                } else {
731                    CmpOp::Ge
732                });
733                i += 2;
734                start = i;
735            }
736            b'<' | b'>' | b'=' | b'!' => return None,
737            _ => i += 1,
738        }
739    }
740    // A trailing/leading operator or empty operand is malformed.
741    if start == 0 || start >= text.len() {
742        return None;
743    }
744    segments.push(text[start..].to_owned());
745    if segments.iter().any(|s| s.trim().is_empty()) {
746        return None;
747    }
748    Some((segments, ops))
749}
750
751/// Parses the comma-separated variable list of a three-part constraint.
752fn parse_var_list(text: &str) -> Result<Vec<String>, SpecError> {
753    let names: Vec<String> = text.split(',').map(str::trim).map(str::to_owned).collect();
754    if names.iter().any(|n| !is_ident(n)) {
755        return Err(SpecError::Unsupported(format!(
756            "unparseable constraint variable list: {text}"
757        )));
758    }
759    Ok(names)
760}
761
762/// Maps a constraint variable name onto the schema: declared scalars
763/// stay scalar, `BASE_<index>` under a declared array becomes an
764/// element bound, everything else is ignored.
765fn classify(name: &str, format: &InputFormat) -> VarKey {
766    if format.is_scalar(name) {
767        return VarKey::Scalar(name.to_owned());
768    }
769    if let Some(base) = format.element_base(name) {
770        return VarKey::Element(base);
771    }
772    VarKey::Other(name.to_owned())
773}
774
775/// Removes a leading list marker (`- `, `・`, `•`, `* `, or `12. `/`3) `)
776/// from constraint text extracted out of `<li>`/`<p>` markup. Only
777/// marker+whitespace prefixes are stripped, so a real negative bound
778/// like `-1 <= N` is untouched.
779fn strip_list_marker(text: &str) -> &str {
780    let text = text.trim_start();
781    for prefix in ["- ", "− ", "– ", "• ", "・ ", "* "] {
782        if let Some(rest) = text.strip_prefix(prefix) {
783            return rest.trim_start();
784        }
785    }
786    let bytes = text.as_bytes();
787    let mut i = 0;
788    while i < bytes.len() && bytes[i].is_ascii_digit() {
789        i += 1;
790    }
791    if i > 0
792        && i + 1 < bytes.len()
793        && matches!(bytes[i], b'.' | b')')
794        && bytes[i + 1].is_ascii_whitespace()
795    {
796        return text[i + 1..].trim_start();
797    }
798    text
799}
800
801/// `true` for `_{...,`-style multi-dimensional index markers in the
802/// raw (pre-normalization) line.
803fn has_multi_index(raw: &str) -> bool {
804    let bytes = raw.as_bytes();
805    for (i, &b) in bytes.iter().enumerate() {
806        if b == b'_' && bytes.get(i + 1) == Some(&b'{') {
807            if let Some(end) = raw[i + 2..].find('}').map(|e| i + 2 + e) {
808                if raw[i + 2..end].contains(',') {
809                    return true;
810                }
811            }
812        }
813    }
814    false
815}
816
817/// Removes parenthesized groups that contain comparison operators or
818/// `=` — these are index-range annotations like `(1 <= i <= N)` or
819/// `(i = 1, ..., N)`, never part of a bound expression. Groups without
820/// comparisons (e.g. `(N + 1)`) are kept for the expression parser.
821fn strip_annotation_parens(text: &mut String) {
822    let mut search_from = 0;
823    while let Some(rel) = text[search_from..].find('(') {
824        let start = search_from + rel;
825        let mut depth = 0i32;
826        let mut end = None;
827        for (i, ch) in text.char_indices().skip_while(|(i, _)| *i < start) {
828            match ch {
829                '(' => depth += 1,
830                ')' => {
831                    depth -= 1;
832                    if depth == 0 {
833                        end = Some(i);
834                        break;
835                    }
836                }
837                _ => {}
838            }
839        }
840        let Some(end) = end else { return };
841        if text[start + 1..end].contains(['<', '>', '=']) {
842            text.replace_range(start..=end, " ");
843            search_from = start;
844        } else {
845            search_from = end + 1;
846        }
847    }
848}
849
850/// LaTeX/markup normalization shared by format and constraint lines:
851/// math delimiters, `\ldots`-style ellipses, braces, `\_`, unicode
852/// comparison/operator glyphs, and NBSP become ASCII equivalents.
853/// Commands are matched longest-first so `\leq` wins over `\le`.
854fn normalize_markup(text: &str) -> String {
855    const COMMANDS: &[(&str, &str)] = &[
856        ("\\ldotsb", "..."),
857        ("\\ldots", "..."),
858        ("\\cdots", "..."),
859        ("\\dots", "..."),
860        ("\\leq", "<="),
861        ("\\le", "<="),
862        ("\\geq", ">="),
863        ("\\ge", ">="),
864        ("\\times", "*"),
865        ("\\cdot", "*"),
866        ("\\neq", "!="),
867        ("\\ne", "!="),
868        ("\\_", "_"),
869        ("\\(", " "),
870        ("\\)", " "),
871        ("\\ ", " "),
872    ];
873    let mut out = String::with_capacity(text.len());
874    let mut rest = text;
875    while let Some(ch) = rest.chars().next() {
876        if ch == '\\' {
877            if let Some((command, replacement)) = COMMANDS
878                .iter()
879                .find(|(command, _)| rest.starts_with(command))
880            {
881                out.push_str(replacement);
882                rest = &rest[command.len()..];
883                continue;
884            }
885            // Unknown command: drop the backslash, keep the letter so
886            // prose like `\times` variants still surface as text.
887            rest = &rest[1..];
888            continue;
889        }
890        let mapped = match ch {
891            '≤' | '≦' | '﹤' => Some("<="),
892            '≥' | '≧' | '﹥' => Some(">="),
893            '−' | '–' | '—' => Some("-"),
894            '×' | '⋅' | '∙' => Some("*"),
895            '…' | '⋯' => Some("..."),
896            '{' | '}' | '$' => Some(""),
897            '\u{a0}' => Some(" "),
898            _ => None,
899        };
900        if let Some(replacement) = mapped {
901            out.push_str(replacement);
902        } else {
903            out.push(ch);
904        }
905        rest = &rest[ch.len_utf8()..];
906    }
907    out
908}
909
910#[cfg(test)]
911pub(crate) mod tests_support {
912    use super::*;
913
914    /// `N M` scalars + `A_1 A_2 ... A_N` array, fully bounded.
915    pub(crate) fn parse_simple_spec() -> GenSpec {
916        GenSpec::parse(
917            "N M\nA_1 A_2 ... A_N\n",
918            &[
919                "1 <= N <= 10".to_owned(),
920                "1 <= M <= 10".to_owned(),
921                "1 <= A_i <= 10 (1 <= i <= N)".to_owned(),
922            ],
923        )
924        .expect("simple spec")
925    }
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931
932    #[test]
933    fn parses_scalar_and_array_lines() {
934        let format = InputFormat::parse("N M\nA_1 A_2 ... A_N\n").expect("format");
935        assert_eq!(format.lines.len(), 2);
936        assert_eq!(
937            format.lines[0],
938            FormatLine::Scalars(vec!["N".to_owned(), "M".to_owned()])
939        );
940        assert_eq!(
941            format.lines[1],
942            FormatLine::Array {
943                name: "A".to_owned(),
944                length_var: "N".to_owned()
945            }
946        );
947    }
948
949    #[test]
950    fn rejects_unsupported_format_lines() {
951        for text in [
952            "S T\n\"string\"\n",       // quoted literal
953            "A_{i,j}\n",               // 2-D index braces → token fails ident
954            "A_1 A_2 ... A_N extra\n", // tokens after the length var
955            "N\n...\n",                // bare ellipsis
956            "N, M\n",                  // commas unsupported
957        ] {
958            assert!(
959                InputFormat::parse(text).is_err(),
960                "expected unsupported: {text:?}"
961            );
962        }
963    }
964
965    #[test]
966    fn parses_constraint_forms() {
967        let format = InputFormat::parse("N M\nA_1 A_2 ... A_N\n").expect("format");
968        let set = ConstraintSet::parse(
969            &[
970                "1 <= N <= 10".to_owned(),
971                "M <= 5".to_owned(),
972                "2 <= N, M <= 8".to_owned(),
973                "1 <= A_i <= N \\ (1 \\le i \\le N)".to_owned(),
974                "prose line without operators".to_owned(),
975            ],
976            &format,
977        )
978        .expect("constraints");
979        let n = set
980            .bounds
981            .get(&VarKey::Scalar("N".to_owned()))
982            .expect("N bounds");
983        assert_eq!(n.lowers.len(), 2);
984        assert_eq!(n.uppers.len(), 2);
985        let m = set
986            .bounds
987            .get(&VarKey::Scalar("M".to_owned()))
988            .expect("M bounds");
989        assert_eq!(m.lowers.len(), 1);
990        assert_eq!(m.uppers.len(), 2);
991        let a = set
992            .bounds
993            .get(&VarKey::Element("A".to_owned()))
994            .expect("A bounds");
995        assert_eq!(a.lowers.len(), 1);
996        assert_eq!(a.uppers.len(), 1);
997    }
998
999    #[test]
1000    fn strict_and_unknown_constraints_are_unsupported() {
1001        let format = InputFormat::parse("N\n").expect("format");
1002        for line in [
1003            "1 <= N < 10".to_owned(),  // strict upper
1004            "N != 5".to_owned(),       // disequality
1005            "N <= M +".to_owned(),     // broken expr
1006            "A_{i,j} <= N".to_owned(), // 2-D
1007        ] {
1008            assert!(
1009                ConstraintSet::parse(std::slice::from_ref(&line), &format).is_err(),
1010                "expected unsupported: {line}"
1011            );
1012        }
1013    }
1014
1015    #[test]
1016    fn evaluates_safe_integer_expressions() {
1017        let env = BTreeMap::from([("N".to_owned(), 3_i64)]);
1018        assert_eq!(parse_expr("10^5").expect("expr").eval(&env), Ok(100_000));
1019        assert_eq!(
1020            parse_expr("2 * 10^5").expect("expr").eval(&env),
1021            Ok(200_000)
1022        );
1023        assert_eq!(parse_expr("N + 1").expect("expr").eval(&env), Ok(4));
1024        assert_eq!(parse_expr("-N * 2").expect("expr").eval(&env), Ok(-6));
1025        assert!(parse_expr("10^100").expect("expr").eval(&env).is_err());
1026        assert!(parse_expr("M + 1").expect("expr").eval(&env).is_err());
1027        assert!(parse_expr("1 / 2").is_err());
1028    }
1029
1030    #[test]
1031    fn spec_requires_bounds_for_everything() {
1032        // Array length var undeclared → unsupported.
1033        assert!(GenSpec::parse("A_1 A_2 ... A_N\n", &["1 <= A_i <= 10".to_owned()]).is_err());
1034        // Element bounds missing → unsupported.
1035        assert!(GenSpec::parse("N\nA_1 A_2 ... A_N\n", &["1 <= N <= 10".to_owned()]).is_err());
1036    }
1037}