Skip to main content

logicaffeine_web/
generator.rs

1//! Exercise generation from templates.
2//!
3//! Transforms exercise configurations from the curriculum into concrete
4//! challenges by filling template slots with words from the lexicon.
5//!
6//! # Template Syntax
7//!
8//! Templates use curly braces for slots: `{SlotType}` or `{SlotType:Modifier}`.
9//!
10//! ## Slot Types
11//!
12//! | Slot | Description | Example Output |
13//! |------|-------------|----------------|
14//! | `{ProperName}` | Random proper noun | "Alice", "Bob" |
15//! | `{Noun}` | Random common noun (singular) | "cat", "dog" |
16//! | `{Noun:Plural}` | Pluralized common noun | "cats", "dogs" |
17//! | `{Verb}` | Base form verb | "run", "eat" |
18//! | `{Verb:Past}` | Past tense | "ran", "ate" |
19//! | `{Verb:Present3s}` | Third person singular | "runs", "eats" |
20//! | `{Verb:Gerund}` | Present participle | "running", "eating" |
21//! | `{Adjective}` | Intersective adjective | "tall", "red" |
22//!
23//! ## Constraints
24//!
25//! Constraints filter word selection by semantic features. They're specified
26//! in the exercise config's `constraints` map:
27//!
28//! ```json
29//! {
30//!   "Verb": ["Intransitive"],
31//!   "Noun": ["Animate"]
32//! }
33//! ```
34//!
35//! ## Example
36//!
37//! Template: `"{ProperName} {Verb:Present3s}."`
38//! With constraint `Verb: ["Intransitive"]`
39//! Output: `"Alice runs."`
40//!
41//! # Usage
42//!
43//! ```no_run
44//! use logicaffeine_web::generator::Generator;
45//! use logicaffeine_web::content::ExerciseConfig;
46//! use rand::SeedableRng;
47//!
48//! let generator = Generator::new();
49//! let mut rng = rand::rngs::StdRng::seed_from_u64(42);
50//! # let exercise_config: ExerciseConfig = serde_json::from_str(r#"{"id":"test","type":"Translation","difficulty":1,"prompt":"test"}"#).unwrap();
51//!
52//! if let Some(challenge) = generator.generate(&exercise_config, &mut rng) {
53//!     println!("Sentence: {}", challenge.sentence);
54//! }
55//! ```
56
57use crate::content::{ExerciseConfig, ExerciseType};
58use logicaffeine_language::runtime_lexicon::{
59    gerund, past_tense, pluralize, present_3s, LexiconIndex,
60};
61use logicaffeine_language::{compile, compile_all_scopes};
62use rand::seq::SliceRandom;
63use rand::Rng;
64use std::collections::HashMap;
65#[cfg(not(target_arch = "wasm32"))]
66use std::sync::LazyLock;
67#[cfg(target_arch = "wasm32")]
68use std::sync::OnceLock;
69
70// The process-wide lexicon, parsed exactly once. Native builds parse the embedded
71// JSON on first use; wasm pins the copy fetched from /data/lexicon.json (staged by
72// scripts/web/stage-web-data.sh) so the 279 KB document never rides in the binary.
73#[cfg(not(target_arch = "wasm32"))]
74static LEXICON: LazyLock<LexiconIndex> = LazyLock::new(LexiconIndex::new);
75#[cfg(target_arch = "wasm32")]
76static LEXICON: OnceLock<LexiconIndex> = OnceLock::new();
77
78/// The pinned lexicon. `None` only on wasm before [`ensure_lexicon`] resolves —
79/// the `LexiconGate` component holds Learn content back until it has.
80pub fn lexicon() -> Option<&'static LexiconIndex> {
81    #[cfg(not(target_arch = "wasm32"))]
82    {
83        Some(&LEXICON)
84    }
85    #[cfg(target_arch = "wasm32")]
86    {
87        LEXICON.get()
88    }
89}
90
91/// Resolves once the lexicon is pinned — instant on native and on repeat calls.
92pub async fn ensure_lexicon() -> Result<(), String> {
93    #[cfg(target_arch = "wasm32")]
94    if LEXICON.get().is_none() {
95        let text = crate::ui::data_fetch::fetch_static_text("/data/lexicon.json").await?;
96        let index = LexiconIndex::from_json(&text)
97            .map_err(|e| format!("parsing /data/lexicon.json: {e}"))?;
98        let _ = LEXICON.set(index);
99    }
100    Ok(())
101}
102
103/// Exercise generator that fills templates with lexicon words.
104///
105/// Holds a reference to the lexicon index for word selection.
106/// Stateless; create one instance and reuse for all exercise generation.
107pub struct Generator {
108    lexicon: &'static LexiconIndex,
109}
110
111/// A generated exercise instance ready for display and grading.
112///
113/// Contains the filled template, expected answer(s), and optional hints.
114#[derive(Debug, Clone)]
115pub struct Challenge {
116    /// Unique identifier linking back to the exercise config.
117    pub exercise_id: String,
118    /// Instructions shown to the user (e.g., "Translate this sentence").
119    pub prompt: String,
120    /// The filled template sentence for the user to translate.
121    pub sentence: String,
122    /// The expected answer format and content.
123    pub answer: AnswerType,
124    /// Optional hint revealed on request.
125    pub hint: Option<String>,
126    /// Detailed explanation shown after answering.
127    pub explanation: Option<String>,
128}
129
130/// Expected answer format for a challenge.
131#[derive(Debug, Clone)]
132pub enum AnswerType {
133    /// User enters free-form FOL expression, compared against golden answer.
134    FreeForm {
135        /// The correct FOL translation, pre-compiled from the sentence.
136        golden_logic: String,
137    },
138    /// User selects from multiple predefined options.
139    MultipleChoice {
140        /// List of answer choices to display.
141        options: Vec<String>,
142        /// Zero-based index of the correct option.
143        correct_index: usize,
144    },
145    /// Sentence has multiple valid readings; user must provide all.
146    Ambiguity {
147        /// All valid FOL translations for the ambiguous sentence.
148        readings: Vec<String>,
149    },
150}
151
152impl Generator {
153    /// How many sentences a generator may draw before giving up on an
154    /// exercise. Lexicon pools contain words the compiler rejects in some
155    /// frames, so generation rejection-samples; the bound keeps a
156    /// misconfigured template from looping forever.
157    const MAX_DRAWS: usize = 32;
158
159    /// Creates a new generator over the pinned lexicon index.
160    pub fn new() -> Self {
161        Self {
162            lexicon: lexicon()
163                .expect("gated: LexiconGate resolves the lexicon before Learn content renders"),
164        }
165    }
166
167    /// Generates a challenge from an exercise configuration.
168    ///
169    /// Returns `None` if:
170    /// - The template cannot be filled (missing word categories)
171    /// - The generated sentence fails to compile (invalid grammar)
172    /// - Required fields are missing from the exercise config
173    pub fn generate(&self, exercise: &ExerciseConfig, rng: &mut impl Rng) -> Option<Challenge> {
174        match exercise.exercise_type {
175            ExerciseType::Translation => self.generate_translation(exercise, rng),
176            ExerciseType::MultipleChoice => self.generate_multiple_choice(exercise, rng),
177            ExerciseType::Ambiguity => self.generate_ambiguity(exercise, rng),
178        }
179    }
180
181    fn generate_translation(
182        &self,
183        exercise: &ExerciseConfig,
184        rng: &mut impl Rng,
185    ) -> Option<Challenge> {
186        let template = exercise.template.as_ref()?;
187
188        // Rejection sampling: a draw whose sentence the compiler rejects is
189        // discarded and redrawn, so one unparseable word in a pool can never
190        // sink the exercise.
191        for _ in 0..Self::MAX_DRAWS {
192            let Some(sentence) = self.fill_template(template, &exercise.constraints, rng) else {
193                return None;
194            };
195            let Ok(golden_logic) = compile(&sentence) else {
196                continue;
197            };
198
199            return Some(Challenge {
200                exercise_id: exercise.id.clone(),
201                prompt: exercise.prompt.clone(),
202                sentence,
203                answer: AnswerType::FreeForm { golden_logic },
204                hint: exercise.hint.clone(),
205                explanation: exercise.explanation.clone(),
206            });
207        }
208        None
209    }
210
211    fn generate_multiple_choice(
212        &self,
213        exercise: &ExerciseConfig,
214        rng: &mut impl Rng,
215    ) -> Option<Challenge> {
216        let options = exercise.options.clone()?;
217        let correct_index = exercise.correct?;
218
219        let sentence = if let Some(template) = &exercise.template {
220            self.fill_template(template, &exercise.constraints, rng)?
221        } else {
222            exercise.prompt.clone()
223        };
224
225        Some(Challenge {
226            exercise_id: exercise.id.clone(),
227            prompt: exercise.prompt.clone(),
228            sentence,
229            answer: AnswerType::MultipleChoice {
230                options,
231                correct_index,
232            },
233            hint: exercise.hint.clone(),
234            explanation: exercise.explanation.clone(),
235        })
236    }
237
238    fn generate_ambiguity(
239        &self,
240        exercise: &ExerciseConfig,
241        rng: &mut impl Rng,
242    ) -> Option<Challenge> {
243        let template = exercise.template.as_ref()?;
244
245        for _ in 0..Self::MAX_DRAWS {
246            let Some(sentence) = self.fill_template(template, &exercise.constraints, rng) else {
247                return None;
248            };
249            let Ok(readings) = compile_all_scopes(&sentence) else {
250                continue;
251            };
252
253            return Some(Challenge {
254                exercise_id: exercise.id.clone(),
255                prompt: exercise.prompt.clone(),
256                sentence,
257                answer: AnswerType::Ambiguity { readings },
258                hint: exercise.hint.clone(),
259                explanation: exercise.explanation.clone(),
260            });
261        }
262        None
263    }
264
265    fn fill_template(
266        &self,
267        template: &str,
268        constraints: &HashMap<String, Vec<String>>,
269        rng: &mut impl Rng,
270    ) -> Option<String> {
271        let mut result = template.to_string();
272        let mut used_names: HashMap<String, String> = HashMap::new();
273
274        while let Some(start) = result.find('{') {
275            let end = result[start..].find('}')? + start;
276            let slot = &result[start + 1..end];
277
278            let (slot_type, modifier) = if let Some(colon_pos) = slot.find(':') {
279                (&slot[..colon_pos], Some(&slot[colon_pos + 1..]))
280            } else {
281                (slot, None)
282            };
283
284            let slot_constraints = constraints
285                .get(slot_type)
286                .map(|v| v.as_slice())
287                .unwrap_or(&[]);
288            let word =
289                self.fill_slot(slot_type, slot_constraints, modifier, &mut used_names, rng)?;
290
291            result = format!("{}{}{}", &result[..start], word, &result[end + 1..]);
292        }
293
294        Some(result)
295    }
296
297    fn fill_slot(
298        &self,
299        slot_type: &str,
300        constraints: &[String],
301        modifier: Option<&str>,
302        used_names: &mut HashMap<String, String>,
303        rng: &mut impl Rng,
304    ) -> Option<String> {
305        match slot_type {
306            "ProperName" => {
307                let key = format!("ProperName_{}", used_names.len());
308                if let Some(existing) = used_names.get(&key) {
309                    return Some(existing.clone());
310                }
311
312                let proper_nouns = self.lexicon.proper_nouns();
313                let available: Vec<_> = proper_nouns
314                    .iter()
315                    .filter(|n| !used_names.values().any(|v| v == &n.lemma))
316                    .copied()
317                    .collect();
318
319                let entry = if !available.is_empty() {
320                    available.choose(rng)?
321                } else {
322                    proper_nouns.choose(rng)?
323                };
324                let name = entry.lemma.clone();
325                used_names.insert(key, name.clone());
326                Some(name)
327            }
328            "Noun" => {
329                let nouns = if constraints.is_empty() {
330                    self.lexicon.common_nouns()
331                } else {
332                    let mut filtered = Vec::new();
333                    for constraint in constraints {
334                        filtered.extend(self.lexicon.nouns_with_feature(constraint));
335                    }
336                    filtered
337                };
338
339                let entry = nouns.choose(rng)?;
340                let word = entry.lemma.to_lowercase();
341
342                match modifier {
343                    Some("Plural") => Some(pluralize(entry)),
344                    _ => Some(word),
345                }
346            }
347            "Verb" => {
348                let verbs = if constraints.contains(&"Intransitive".to_string()) {
349                    self.lexicon.intransitive_verbs()
350                } else if constraints.contains(&"Transitive".to_string()) {
351                    self.lexicon.transitive_verbs()
352                } else {
353                    let mut result = Vec::new();
354                    for constraint in constraints {
355                        result.extend(self.lexicon.verbs_with_feature(constraint));
356                    }
357                    if result.is_empty() {
358                        self.lexicon.intransitive_verbs()
359                    } else {
360                        result
361                    }
362                };
363
364                let entry = verbs.choose(rng)?;
365
366                match modifier {
367                    Some("Past") => Some(past_tense(entry)),
368                    Some("Gerund") => Some(gerund(entry)),
369                    Some("Present3s") => Some(present_3s(entry)),
370                    _ => Some(entry.lemma.to_lowercase()),
371                }
372            }
373            "Adjective" => {
374                let adjectives = if constraints.contains(&"Intersective".to_string()) {
375                    self.lexicon.intersective_adjectives()
376                } else if constraints.is_empty() {
377                    self.lexicon.intersective_adjectives()
378                } else {
379                    let mut result = Vec::new();
380                    for constraint in constraints {
381                        result.extend(self.lexicon.adjectives_with_feature(constraint));
382                    }
383                    result
384                };
385
386                let entry = adjectives.choose(rng)?;
387                Some(entry.lemma.to_lowercase())
388            }
389            _ => Some("thing".to_string()),
390        }
391    }
392}
393
394impl Default for Generator {
395    fn default() -> Self {
396        Self::new()
397    }
398}
399
400#[cfg(test)]
401#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_web/generator/tests.rs"]
402mod tests;