Skip to main content

ac_algorithm/generate/
mod.rs

1//! Deterministic test-case generation (A-03, issue #26).
2//!
3//! Ports ac-test's Level-1 generation semantics (spike #6 §2.3–§2.5)
4//! onto the domain model: integer scalars and one-dimensional integer
5//! arrays, boundary values plus fixed-seed pseudo-random cases, and
6//! conservative skipping whenever valid input cannot be proven.
7//!
8//! [`spec`] parses the input-format block and constraint lines into a
9//! [`GenSpec`]; [`prng`] holds the xorshift32 generator; this module
10//! drives the five generation modes.
11
12pub mod prng;
13mod spec;
14
15pub use spec::{Expr, FormatLine, GenSpec, InputFormat, SpecError, VarBounds, VarKey};
16
17use std::collections::BTreeMap;
18
19use prng::XorShift32;
20
21/// ac-test's default seed base (`0xac7e57`).
22pub const DEFAULT_SEED_BASE: u32 = 0x00ac_7e57;
23/// Maximum array length; longer arrays discard the case (spike #6 §2.5).
24pub const MAX_ARRAY_LENGTH: i64 = 2_000_000;
25
26/// The five ac-test generation modes, in emission order.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub enum GenMode {
29    /// Every value at its lower bound.
30    Min,
31    /// Every value at lower bound + 1.
32    NearMin,
33    /// Every value at upper bound - 1.
34    NearMax,
35    /// Every value at its upper bound.
36    Max,
37    /// Structure sizes at max; array elements pseudo-random in range.
38    RandomMax,
39}
40
41impl GenMode {
42    /// All modes in emission order.
43    pub const ALL: [Self; 5] = [
44        Self::Min,
45        Self::NearMin,
46        Self::NearMax,
47        Self::Max,
48        Self::RandomMax,
49    ];
50
51    /// Case-name suffix (`generated-<name>`).
52    #[must_use]
53    pub fn name(self) -> &'static str {
54        match self {
55            Self::Min => "min",
56            Self::NearMin => "near-min",
57            Self::NearMax => "near-max",
58            Self::Max => "max",
59            Self::RandomMax => "random-max",
60        }
61    }
62}
63
64/// One generated case: deterministic input text plus its provenance.
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct GeneratedCase {
67    /// Case name (`generated-min`, …).
68    pub name: String,
69    /// Generation mode that produced it.
70    pub mode: GenMode,
71    /// xorshift32 seed actually used (recorded for reproducibility).
72    pub seed: u32,
73    /// Input text, newline-terminated.
74    pub input: String,
75}
76
77/// A mode that could not produce a case (e.g. array length cap).
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct SkippedCase {
80    /// Mode that was attempted.
81    pub mode: GenMode,
82    /// Why the case was discarded.
83    pub reason: String,
84}
85
86/// Result of [`Generator::generate`].
87#[derive(Clone, Debug, Default)]
88pub struct GenOutcome {
89    /// Successfully generated cases, in mode order.
90    pub cases: Vec<GeneratedCase>,
91    /// Modes skipped with their reasons.
92    pub skipped: Vec<SkippedCase>,
93    /// Set when the spec itself is unsupported — no cases are produced.
94    pub unsupported: Option<String>,
95}
96
97/// Runs a parsed [`GenSpec`] through the five modes.
98#[derive(Clone, Debug)]
99pub struct Generator {
100    spec: GenSpec,
101    /// Task identifier mixed into every seed (ac-test used the task
102    /// name; we use the task screen name or directory label).
103    task: String,
104    /// Seed base; [`DEFAULT_SEED_BASE`] unless overridden.
105    seed_base: u32,
106}
107
108impl Generator {
109    /// Builds a generator for `spec` under `task` with `seed_base`.
110    #[must_use]
111    pub fn new(spec: GenSpec, task: impl Into<String>, seed_base: u32) -> Self {
112        Self {
113            spec,
114            task: task.into(),
115            seed_base,
116        }
117    }
118
119    /// Generates all five modes. Deterministic: identical spec, task,
120    /// and seed base always yield identical cases.
121    #[must_use]
122    pub fn generate(&self) -> GenOutcome {
123        let mut outcome = GenOutcome::default();
124        for mode in GenMode::ALL {
125            let seed = self.seed_base
126                ^ u32::try_from(self.task.len()).unwrap_or(u32::MAX)
127                ^ u32::try_from(mode.name().len()).unwrap_or(u32::MAX);
128            match self.generate_mode(mode, seed) {
129                Ok(input) => outcome.cases.push(GeneratedCase {
130                    name: format!("generated-{}", mode.name()),
131                    mode,
132                    seed,
133                    input,
134                }),
135                Err(reason) => outcome.skipped.push(SkippedCase { mode, reason }),
136            }
137        }
138        outcome
139    }
140
141    /// Generates one mode's input text.
142    fn generate_mode(&self, mode: GenMode, seed: u32) -> Result<String, String> {
143        let mut rng = XorShift32::new(seed);
144        let mut chosen: BTreeMap<String, i64> = BTreeMap::new();
145
146        // Resolve scalar values in dependency order: a variable becomes
147        // ready once every variable its bound expressions reference has
148        // been chosen. Unresolvable references (element vars, unknown
149        // names, cycles) leave the variable stuck and skip the case.
150        let scalars: Vec<(&str, &VarBounds)> = self.spec.scalar_bounds().collect();
151        while chosen.len() < scalars.len() {
152            let mut progressed = false;
153            for &(name, bounds) in &scalars {
154                if chosen.contains_key(name) || !bounds_ready(bounds, &chosen) {
155                    continue;
156                }
157                let value = pick_scalar(mode, bounds, &chosen)?;
158                chosen.insert(name.to_owned(), value);
159                progressed = true;
160            }
161            if !progressed {
162                return Err(
163                    "constraint bounds are cyclic or reference unknown variables".to_owned(),
164                );
165            }
166        }
167
168        // Array lengths come from their (already chosen) length
169        // variables; element bounds resolve once against the chosen
170        // scalars, then every element picks per mode.
171        let mut rendered: Vec<String> = Vec::with_capacity(self.spec.format.lines.len());
172        for line in &self.spec.format.lines {
173            match line {
174                FormatLine::Scalars(names) => {
175                    let mut parts = Vec::with_capacity(names.len());
176                    for name in names {
177                        parts.push(
178                            chosen
179                                .get(name)
180                                .map(i64::to_string)
181                                .ok_or_else(|| format!("scalar `{name}` has no value"))?,
182                        );
183                    }
184                    rendered.push(parts.join(" "));
185                }
186                FormatLine::Array {
187                    name, length_var, ..
188                } => {
189                    let length = *chosen.get(length_var).ok_or_else(|| {
190                        format!("array length variable `{length_var}` has no value")
191                    })?;
192                    if !(0..=MAX_ARRAY_LENGTH).contains(&length) {
193                        return Err(format!(
194                            "array `{name}` length {length} exceeds the {MAX_ARRAY_LENGTH} cap"
195                        ));
196                    }
197                    let (lowers, uppers) = self
198                        .spec
199                        .element_bounds(name)
200                        .ok_or_else(|| format!("array `{name}` has no element bounds"))?;
201                    let low = eval_bounds_low(lowers, &chosen)?;
202                    let high = eval_bounds_high(uppers, &chosen)?;
203                    if low > high {
204                        return Err(format!("array `{name}` element range is empty"));
205                    }
206                    let mut elements = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
207                    for _ in 0..length {
208                        elements.push(pick_element(mode, low, high, &mut rng).to_string());
209                    }
210                    rendered.push(elements.join(" "));
211                }
212            }
213        }
214
215        let mut input = rendered.join("\n");
216        input.push('\n');
217        Ok(input)
218    }
219}
220
221/// `true` when every variable referenced by `bounds` already has a
222/// chosen value.
223fn bounds_ready(bounds: &VarBounds, chosen: &BTreeMap<String, i64>) -> bool {
224    bounds
225        .lowers
226        .iter()
227        .chain(bounds.uppers.iter())
228        .flat_map(Expr::vars)
229        .all(|var| chosen.contains_key(var))
230}
231
232/// Evaluates all lower-bound expressions and returns the maximum.
233fn eval_bounds_low(exprs: &[Expr], env: &BTreeMap<String, i64>) -> Result<i64, String> {
234    let mut low = i64::MIN;
235    for expr in exprs {
236        low = low.max(expr.eval(env).map_err(|err| err.to_string())?);
237    }
238    Ok(low)
239}
240
241/// Evaluates all upper-bound expressions and returns the minimum.
242fn eval_bounds_high(exprs: &[Expr], env: &BTreeMap<String, i64>) -> Result<i64, String> {
243    let mut high = i64::MAX;
244    for expr in exprs {
245        high = high.min(expr.eval(env).map_err(|err| err.to_string())?);
246    }
247    Ok(high)
248}
249
250/// Picks a scalar value for `mode` inside the resolved `[low, high]`.
251fn pick_scalar(
252    mode: GenMode,
253    bounds: &VarBounds,
254    chosen: &BTreeMap<String, i64>,
255) -> Result<i64, String> {
256    let low = eval_bounds_low(&bounds.lowers, chosen)?;
257    let high = eval_bounds_high(&bounds.uppers, chosen)?;
258    if low > high {
259        return Err(format!("constraint range [{low}, {high}] is empty"));
260    }
261    Ok(pick_value(mode, low, high))
262}
263
264/// Picks one array element: boundary modes reuse [`pick_value`]; only
265/// [`GenMode::RandomMax`] draws from the seeded generator.
266fn pick_element(mode: GenMode, low: i64, high: i64, rng: &mut XorShift32) -> i64 {
267    if mode == GenMode::RandomMax {
268        rng.below(low, high)
269    } else {
270        pick_value(mode, low, high)
271    }
272}
273
274/// Mode → value inside `[low, high]` (inclusive). `random-max` yields
275/// the upper bound for scalars; array elements randomize separately.
276fn pick_value(mode: GenMode, low: i64, high: i64) -> i64 {
277    match mode {
278        GenMode::Min => low,
279        GenMode::NearMin => low.saturating_add(1).min(high),
280        GenMode::NearMax => high.saturating_sub(1).max(low),
281        GenMode::Max | GenMode::RandomMax => high,
282    }
283    .clamp(low, high)
284}
285
286/// Convenience: parse a spec and generate in one call.
287///
288/// # Errors
289///
290/// Never fails; parse problems surface as [`GenOutcome::unsupported`].
291#[must_use]
292pub fn generate_cases(
293    input_format: &str,
294    constraint_lines: &[String],
295    task: &str,
296    seed_base: u32,
297) -> GenOutcome {
298    match GenSpec::parse(input_format, constraint_lines) {
299        Ok(spec) => Generator::new(spec, task, seed_base).generate(),
300        Err(err) => GenOutcome {
301            unsupported: Some(err.to_string()),
302            ..GenOutcome::default()
303        },
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::spec::tests_support::parse_simple_spec;
310    use super::*;
311
312    #[test]
313    fn modes_emit_boundary_and_random_cases() {
314        let spec = parse_simple_spec();
315        let outcome = Generator::new(spec, "abc351_a", DEFAULT_SEED_BASE).generate();
316        assert!(outcome.unsupported.is_none());
317        assert_eq!(outcome.cases.len(), 5);
318        assert_eq!(outcome.skipped, Vec::new());
319        let by_mode = |m: GenMode| {
320            outcome
321                .cases
322                .iter()
323                .find(|c| c.mode == m)
324                .expect("mode case")
325                .input
326                .clone()
327        };
328        // N M / A_1..A_N with N=length: min → "1 1\n1\n",
329        // near-min → "2 2\n2 2\n", near-max → "9 9\n9×9\n",
330        // max → "10 10\n10×10\n".
331        assert_eq!(by_mode(GenMode::Min), "1 1\n1\n");
332        assert_eq!(by_mode(GenMode::NearMin), "2 2\n2 2\n");
333        assert_eq!(
334            by_mode(GenMode::NearMax),
335            format!("9 9\n{}\n", "9 ".repeat(9).trim_end())
336        );
337        assert_eq!(
338            by_mode(GenMode::Max),
339            format!("10 10\n{}\n", "10 ".repeat(10).trim_end())
340        );
341        // random-max: scalars/length at max, elements random in [1,10].
342        let random = by_mode(GenMode::RandomMax);
343        let mut lines = random.lines();
344        assert_eq!(lines.next(), Some("10 10"));
345        let elements: Vec<i64> = lines
346            .next()
347            .expect("array line")
348            .split_whitespace()
349            .map(|t| t.parse().expect("integer"))
350            .collect();
351        assert_eq!(elements.len(), 10);
352        assert!(elements.iter().all(|&v| (1..=10).contains(&v)));
353    }
354
355    #[test]
356    fn unsupported_spec_produces_no_cases() {
357        let outcome = generate_cases("A_{i,j}\n", &[], "t", DEFAULT_SEED_BASE);
358        assert_eq!(outcome.cases, Vec::new());
359        assert!(outcome.unsupported.is_some());
360    }
361
362    #[test]
363    fn generation_is_deterministic_per_seed() {
364        // Covered above; here: a different seed base changes random-max.
365        let spec = parse_simple_spec();
366        let a = Generator::new(spec.clone(), "abc351_a", DEFAULT_SEED_BASE).generate();
367        let b = Generator::new(spec, "abc351_a", DEFAULT_SEED_BASE ^ 0x1234_5678).generate();
368        assert_ne!(a.cases[4].seed, b.cases[4].seed);
369        assert_ne!(a.cases[4].input, b.cases[4].input);
370        // Boundary modes are seed-independent.
371        assert_eq!(a.cases[0].input, b.cases[0].input);
372        assert_eq!(a.cases[3].input, b.cases[3].input);
373    }
374
375    #[test]
376    fn missing_bounds_skip_generation() {
377        let outcome = generate_cases("N\n", &["1 <= N <= 10".to_owned()], "t", DEFAULT_SEED_BASE);
378        assert_eq!(outcome.cases.len(), 5);
379        // Unbounded scalar → unsupported.
380        let outcome = generate_cases(
381            "N M\n",
382            &["1 <= N <= 10".to_owned()],
383            "t",
384            DEFAULT_SEED_BASE,
385        );
386        assert_eq!(outcome.cases, Vec::new());
387        assert!(outcome.unsupported.is_some());
388    }
389
390    #[test]
391    fn oversized_array_length_skips_only_that_mode() {
392        // N max = 2_000_001 > cap: min/near-min/near-max still generate.
393        let outcome = generate_cases(
394            "N\nA_1 A_2 ... A_N\n",
395            &[
396                "1 <= N <= 2000001".to_owned(),
397                "1 <= A_i <= 10 (1 <= i <= N)".to_owned(),
398            ],
399            "t",
400            DEFAULT_SEED_BASE,
401        );
402        assert!(outcome.unsupported.is_none());
403        assert_eq!(outcome.cases.len(), 3, "min/near-min/near-max survive");
404        assert_eq!(outcome.skipped.len(), 2, "max/random-max exceed cap");
405        assert!(outcome.skipped.iter().all(|s| s.reason.contains("exceeds")));
406    }
407}